hexsha
stringlengths
40
40
size
int64
2
1.05M
content
stringlengths
2
1.05M
avg_line_length
float64
1.33
100
max_line_length
int64
1
1k
alphanum_fraction
float64
0.25
1
69367648270b4f4f4837e4ec6f04853877aebde4
4,395
use serde::{Deserialize, Serialize}; use std::io::{self, Write}; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Program { pub functions: Vec<Function>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Function { pub name: String, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub args: Vec<Argument>, #[serde(rename = "type")] #[serde(skip_serializing_if = "Option::is_none")] pub return_type: Option<Type>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub instrs: Vec<Code>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Argument { pub name: String, #[serde(rename = "type")] pub arg_type: Type, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] #[serde(untagged)] pub enum Code { Label { label: String }, Instruction(Instruction), } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] #[serde(untagged)] pub enum Instruction { Constant { op: ConstOps, dest: String, #[serde(rename = "type")] const_type: Type, value: Literal, }, Value { op: ValueOps, dest: String, #[serde(rename = "type")] op_type: Type, #[serde(default, skip_serializing_if = "Vec::is_empty")] args: Vec<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] funcs: Vec<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] labels: Vec<String>, }, Effect { op: EffectOps, #[serde(default, skip_serializing_if = "Vec::is_empty")] args: Vec<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] funcs: Vec<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] labels: Vec<String>, }, } #[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum ConstOps { #[serde(rename = "const")] Const, } #[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq, Eq, Hash)] #[serde(rename_all = "lowercase")] pub enum EffectOps { #[serde(rename = "jmp")] Jump, #[serde(rename = "br")] Branch, Call, #[serde(rename = "ret")] Return, Print, Nop, #[cfg(feature = "memory")] Store, #[cfg(feature = "memory")] Free, #[cfg(feature = "speculate")] Speculate, #[cfg(feature = "speculate")] Commit, #[cfg(feature = "speculate")] Guard, } #[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq, Eq, Hash)] #[serde(rename_all = "lowercase")] pub enum ValueOps { Add, Sub, Mul, Div, Eq, Lt, Gt, Le, Ge, Not, And, Or, Call, Id, #[cfg(feature = "ssa")] Phi, #[cfg(feature = "float")] Fadd, #[cfg(feature = "float")] Fsub, #[cfg(feature = "float")] Fmul, #[cfg(feature = "float")] Fdiv, #[cfg(feature = "float")] Feq, #[cfg(feature = "float")] Flt, #[cfg(feature = "float")] Fgt, #[cfg(feature = "float")] Fle, #[cfg(feature = "float")] Fge, #[cfg(feature = "memory")] Alloc, #[cfg(feature = "memory")] Load, #[cfg(feature = "memory")] PtrAdd, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash)] #[serde(rename_all = "lowercase")] pub enum Type { Int, Bool, #[cfg(feature = "float")] Float, #[cfg(feature = "memory")] #[serde(rename = "ptr")] Pointer(Box<Type>), } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] #[serde(untagged)] pub enum Literal { Int(i64), Bool(bool), #[cfg(feature = "float")] Float(f64), } impl Literal { pub fn get_type(&self) -> Type { match self { Literal::Int(_) => Type::Int, Literal::Bool(_) => Type::Bool, #[cfg(feature = "float")] Literal::Float(_) => Type::Float, } } } pub fn load_program_from_read<R: std::io::Read>(mut input: R) -> Program { let mut buffer = String::new(); input.read_to_string(&mut buffer).unwrap(); serde_json::from_str(&buffer).unwrap() } pub fn load_program() -> Program { load_program_from_read(std::io::stdin()) } pub fn output_program(p: &Program) { io::stdout() .write_all(serde_json::to_string(p).unwrap().as_bytes()) .unwrap(); }
23.131579
74
0.577929
1c7b129d7ff9fc982c18cc89e6b049059c4757e2
12,666
//! This module contains the code to compact chunks together use super::{error::Result, merge_schemas, LockableCatalogChunk, LockableCatalogPartition}; use crate::{ catalog::{chunk::CatalogChunk, partition::Partition}, lifecycle::collect_rub, DbChunk, }; use data_types::{chunk_metadata::ChunkOrder, delete_predicate::DeletePredicate, job::Job}; use lifecycle::LifecycleWriteGuard; use observability_deps::tracing::info; use query::{compute_sort_key, exec::ExecutorType, frontend::reorg::ReorgPlanner, QueryChunkMeta}; use std::{collections::HashSet, future::Future, sync::Arc}; use time::Time; use tracker::{TaskTracker, TrackedFuture, TrackedFutureExt}; /// Compact the provided chunks into a single chunk, /// returning the newly created chunk /// /// TODO: Replace low-level locks with transaction object pub(crate) fn compact_chunks( partition: LifecycleWriteGuard<'_, Partition, LockableCatalogPartition>, chunks: Vec<LifecycleWriteGuard<'_, CatalogChunk, LockableCatalogChunk>>, ) -> Result<( TaskTracker<Job>, TrackedFuture<impl Future<Output = Result<Option<Arc<DbChunk>>>> + Send>, )> { assert!( !chunks.is_empty(), "must provide at least 1 chunk for compaction" ); let now = std::time::Instant::now(); // time compaction duration. let db = Arc::clone(&partition.data().db); let addr = partition.addr().clone(); let chunk_ids: Vec<_> = chunks.iter().map(|x| x.id()).collect(); info!(%addr, ?chunk_ids, "compacting chunks"); let (tracker, registration) = db.jobs.register(Job::CompactChunks { partition: partition.addr().clone(), chunks: chunk_ids.clone(), }); // Mark and snapshot chunks, then drop locks let mut input_rows = 0; let mut time_of_first_write: Option<Time> = None; let mut time_of_last_write: Option<Time> = None; let mut delete_predicates_before: HashSet<Arc<DeletePredicate>> = HashSet::new(); let mut min_order = ChunkOrder::MAX; let query_chunks = chunks .into_iter() .map(|mut chunk| { // Sanity-check assert!(Arc::ptr_eq(&db, &chunk.data().db)); assert_eq!(chunk.table_name().as_ref(), addr.table_name.as_ref()); input_rows += chunk.table_summary().total_count(); let candidate_first = chunk.time_of_first_write(); time_of_first_write = time_of_first_write .map(|prev_first| prev_first.min(candidate_first)) .or(Some(candidate_first)); let candidate_last = chunk.time_of_last_write(); time_of_last_write = time_of_last_write .map(|prev_last| prev_last.max(candidate_last)) .or(Some(candidate_last)); delete_predicates_before.extend(chunk.delete_predicates().iter().cloned()); min_order = min_order.min(chunk.order()); chunk.set_compacting(&registration)?; Ok(DbChunk::snapshot(&*chunk)) }) .collect::<Result<Vec<_>>>()?; // drop partition lock let partition = partition.into_data().partition; let time_of_first_write = time_of_first_write.expect("Should have had a first write somewhere"); let time_of_last_write = time_of_last_write.expect("Should have had a last write somewhere"); let metric_registry = Arc::clone(&db.metric_registry); let ctx = db.exec.new_context(ExecutorType::Reorg); let fut = async move { let fut_now = std::time::Instant::now(); let key = compute_sort_key(query_chunks.iter().map(|x| x.summary())); let key_str = format!("\"{}\"", key); // for logging // build schema // // Note: we only use the merged schema from the to-be-compacted // chunks - not the table-wide schema, since we don't need to // bother with other columns (e.g. ones that only exist in other // partitions). let schema = merge_schemas(&query_chunks); // Cannot move query_chunks as the sort key borrows the column names let (schema, plan) = ReorgPlanner::new().compact_plan(schema, query_chunks.iter().map(Arc::clone), key)?; let physical_plan = ctx.prepare_plan(&plan).await?; let stream = ctx.execute_stream(physical_plan).await?; let maybe_rb_chunk = collect_rub(stream, &addr, metric_registry.as_ref()).await?; let mut partition = partition.write(); let mut delete_predicates_after = HashSet::new(); for id in &chunk_ids { let chunk = partition .force_drop_chunk(*id) .expect("There was a lifecycle action attached to this chunk, who deleted it?!"); let chunk = chunk.read(); for pred in chunk.delete_predicates() { if !delete_predicates_before.contains(pred) { delete_predicates_after.insert(Arc::clone(pred)); } } } let delete_predicates = { let mut tmp: Vec<_> = delete_predicates_after.into_iter().collect(); tmp.sort(); tmp }; let rb_chunk = match maybe_rb_chunk { Some(rb_chunk) => rb_chunk, None => { info!(%addr, ?chunk_ids, "no rows to persist, no chunk created"); return Ok(None); } }; let rub_row_groups = rb_chunk.row_groups(); let output_rows = rb_chunk.rows(); let (_, chunk) = partition.create_rub_chunk( rb_chunk, time_of_first_write, time_of_last_write, schema, delete_predicates, min_order, None, ); // input rows per second let elapsed = now.elapsed(); let throughput = (input_rows as u128 * 1_000_000_000) / elapsed.as_nanos(); info!(input_chunks=chunk_ids.len(), %rub_row_groups, %input_rows, %output_rows, sort_key=%key_str, compaction_took = ?elapsed, fut_execution_duration= ?fut_now.elapsed(), rows_per_sec=?throughput, "chunk(s) compacted"); let snapshot = DbChunk::snapshot(&chunk.read()); Ok(Some(snapshot)) }; Ok((tracker, fut.track(registration))) } #[cfg(test)] mod tests { use super::*; use crate::{ test_helpers::write_lp, utils::{make_db, make_db_time}, }; use data_types::{ chunk_metadata::ChunkStorage, delete_predicate::{DeleteExpr, Op, Scalar}, timestamp::TimestampRange, }; use lifecycle::{LockableChunk, LockablePartition}; use query::QueryDatabase; use std::time::Duration; #[tokio::test] async fn test_compact_freeze() { let (db, time) = make_db_time().await; let t_first_write = time.inc(Duration::from_secs(1)); write_lp(db.as_ref(), "cpu,tag1=cupcakes bar=1 10"); write_lp(db.as_ref(), "cpu,tag1=asfd,tag2=foo bar=2 20"); write_lp(db.as_ref(), "cpu,tag1=bingo,tag2=foo bar=2 10"); write_lp(db.as_ref(), "cpu,tag1=bongo,tag2=a bar=2 20"); let t_last_write = time.inc(Duration::from_secs(1)); write_lp(db.as_ref(), "cpu,tag1=bongo,tag2=a bar=2 10"); let partition_keys = db.partition_keys().unwrap(); assert_eq!(partition_keys.len(), 1); let partition = db.lockable_partition("cpu", &partition_keys[0]).unwrap(); let partition_guard = partition.read(); let chunks = LockablePartition::chunks(&partition_guard); assert_eq!(chunks.len(), 1); let chunk = chunks[0].read(); let (_, fut) = compact_chunks(partition_guard.upgrade(), vec![chunk.upgrade()]).unwrap(); // NB: perform the write before spawning the background task that performs the compaction let t_later_write = time.inc(Duration::from_secs(1)); write_lp(db.as_ref(), "cpu,tag1=bongo,tag2=a bar=2 40"); tokio::spawn(fut).await.unwrap().unwrap().unwrap(); let mut chunk_summaries: Vec<_> = partition.read().chunk_summaries().collect(); chunk_summaries.sort_unstable(); let mub_summary = &chunk_summaries[1]; let first_mub_write = mub_summary.time_of_first_write; let last_mub_write = mub_summary.time_of_last_write; assert_eq!(mub_summary.storage, ChunkStorage::OpenMutableBuffer); assert_eq!(first_mub_write, last_mub_write); assert_eq!(first_mub_write, t_later_write); let rub_summary = &chunk_summaries[0]; let first_rub_write = rub_summary.time_of_first_write; let last_rub_write = rub_summary.time_of_last_write; assert_eq!(rub_summary.storage, ChunkStorage::ReadBuffer); assert_eq!(first_rub_write, t_first_write); assert_eq!(last_rub_write, t_last_write); let summaries: Vec<_> = chunk_summaries .iter() .map(|summary| (summary.storage, summary.row_count)) .collect(); assert_eq!( summaries, vec![ (ChunkStorage::ReadBuffer, 5), (ChunkStorage::OpenMutableBuffer, 1), ] ) } #[tokio::test] async fn test_compact_delete_all() { let db = make_db().await.db; write_lp(db.as_ref(), "cpu,tag1=cupcakes bar=1 10"); write_lp(db.as_ref(), "cpu,tag1=cupcakes bar=3 23"); write_lp(db.as_ref(), "cpu,tag1=cupcakes bar=2 26"); let partition_keys = db.partition_keys().unwrap(); assert_eq!(partition_keys.len(), 1); // Cannot simply use empty predicate (#2687) let predicate = Arc::new(DeletePredicate { range: TimestampRange { start: 0, end: 1_000, }, exprs: vec![], }); // Delete everything db.delete("cpu", predicate).unwrap(); let chunk = db .compact_partition("cpu", partition_keys[0].as_str()) .await .unwrap(); assert!(chunk.is_none()); } #[tokio::test] async fn test_delete_predicate_propagation() { // setup DB let db = make_db().await.db; // | foo | delete before compaction | delete during compaction | // | --- | ------------------------ | ------------------------ | // | 1 | yes | no | // | 2 | yes | yes | // | 3 | no | yes | // | 4 | no | no | write_lp(db.as_ref(), "cpu foo=1 10"); write_lp(db.as_ref(), "cpu foo=2 20"); write_lp(db.as_ref(), "cpu foo=3 20"); write_lp(db.as_ref(), "cpu foo=4 20"); let range = TimestampRange { start: 0, end: 1_000, }; let pred1 = Arc::new(DeletePredicate { range, exprs: vec![DeleteExpr::new("foo".to_string(), Op::Eq, Scalar::I64(1))], }); let pred2 = Arc::new(DeletePredicate { range, exprs: vec![DeleteExpr::new("foo".to_string(), Op::Eq, Scalar::I64(2))], }); let pred3 = Arc::new(DeletePredicate { range, exprs: vec![DeleteExpr::new("foo".to_string(), Op::Eq, Scalar::I64(3))], }); db.delete("cpu", Arc::clone(&pred1)).unwrap(); db.delete("cpu", Arc::clone(&pred2)).unwrap(); // start compaction job (but don't poll the future yet) let partition_keys = db.partition_keys().unwrap(); assert_eq!(partition_keys.len(), 1); let partition_key: &str = partition_keys[0].as_ref(); let partition = db.lockable_partition("cpu", partition_key).unwrap(); let partition = partition.read(); let chunks = LockablePartition::chunks(&partition); assert_eq!(chunks.len(), 1); let chunk = chunks[0].read(); let (_, fut) = compact_chunks(partition.upgrade(), vec![chunk.upgrade()]).unwrap(); // add more delete predicates db.delete("cpu", Arc::clone(&pred2)).unwrap(); db.delete("cpu", Arc::clone(&pred3)).unwrap(); // finish future tokio::spawn(fut).await.unwrap().unwrap().unwrap(); // check delete predicates let chunks = db.catalog.chunks(); assert_eq!(chunks.len(), 1); let chunk = &chunks[0]; let chunk = chunk.read(); let actual = chunk.delete_predicates(); let expected = vec![pred3]; assert_eq!(actual, &expected); } }
37.362832
114
0.589294
f9bdf99106ec1d82d74e3f446dc0ea10c944a88d
639
// test2.rs // This is a test for the following sections: // - Tests // This test isn't testing our function -- make it do that in such a way that // the test passes. Then write a second test that tests that we get the result // we expect to get when we call `times_two` with a negative number. // No hints, you can do this :) pub fn times_two(num: i32) -> i32 { num * 2 } #[cfg(test)] mod tests { use super::*; #[test] fn returns_twice_of_positive_numbers() { assert_eq!(times_two(4), 8); } #[test] fn returns_twice_of_negative_numbers() { // TODO write an assert for `times_two(-4)` assert_eq!(times_two(-4), -8); } }
22.034483
78
0.672926
0e61957a83f88b90c1a7d1e99e5b98741910b83d
4,976
use crate::prelude::*; use super::error::ValidationError as Error; /// Path separator (ie. forward slash '/') const PATH_SEPARATOR: char = '/'; const VALID_SPECIAL_CHARS: &str = "._+-#[]<>"; /// Default validator function for identifiers. /// /// A valid identifier only contain lowercase alphabetic characters, and be of a given min and max /// length. pub fn validate_identifier(id: &str, min: usize, max: usize) -> Result<(), Error> { assert!(max >= min); // Check identifier is not empty if id.is_empty() { return Err(Error::empty()); } // Check identifier does not contain path separators if id.contains(PATH_SEPARATOR) { return Err(Error::contain_separator(id.to_string())); } // Check identifier length is between given min/max if id.len() < min || id.len() > max { return Err(Error::invalid_length(id.to_string(), id.len(), min, max)); } // Check that the identifier comprises only valid characters: // - Alphanumeric // - `.`, `_`, `+`, `-`, `#` // - `[`, `]`, `<`, `>` if !id .chars() .all(|c| c.is_alphanumeric() || VALID_SPECIAL_CHARS.contains(c)) { return Err(Error::invalid_character(id.to_string())); } // All good! Ok(()) } /// Default validator function for Client identifiers. /// /// A valid identifier must be between 9-64 characters and only contain lowercase /// alphabetic characters, pub fn validate_client_identifier(id: &str) -> Result<(), Error> { validate_identifier(id, 9, 64) } /// Default validator function for Connection identifiers. /// /// A valid Identifier must be between 10-64 characters and only contain lowercase /// alphabetic characters, pub fn validate_connection_identifier(id: &str) -> Result<(), Error> { validate_identifier(id, 10, 64) } /// Default validator function for Port identifiers. /// /// A valid Identifier must be between 2-64 characters and only contain lowercase /// alphabetic characters, pub fn validate_port_identifier(id: &str) -> Result<(), Error> { validate_identifier(id, 2, 64) } /// Default validator function for Channel identifiers. /// /// A valid Identifier must be between 10-64 characters and only contain lowercase /// alphabetic characters, pub fn validate_channel_identifier(id: &str) -> Result<(), Error> { validate_identifier(id, 8, 64) } #[cfg(test)] mod tests { use crate::ics24_host::validate::{ validate_channel_identifier, validate_client_identifier, validate_connection_identifier, validate_identifier, validate_port_identifier, }; use test_env_log::test; #[test] fn parse_invalid_port_id_min() { // invalid min port id let id = validate_port_identifier("p"); assert!(id.is_err()) } #[test] fn parse_invalid_port_id_max() { // invalid max port id (test string length is 65 chars) let id = validate_port_identifier( "9anxkcme6je544d5lnj46zqiiiygfqzf8w4bjecbnyj4lj6s7zlpst67yln64tixp", ); assert!(id.is_err()) } #[test] fn parse_invalid_connection_id_min() { // invalid min connection id let id = validate_connection_identifier("connect01"); assert!(id.is_err()) } #[test] fn parse_connection_id_max() { // invalid max connection id (test string length is 65) let id = validate_connection_identifier( "ihhankr30iy4nna65hjl2wjod7182io1t2s7u3ip3wqtbbn1sl0rgcntqc540r36r", ); assert!(id.is_err()) } #[test] fn parse_invalid_client_id_min() { // invalid min client id let id = validate_client_identifier("client"); assert!(id.is_err()) } #[test] fn parse_client_id_max() { // invalid max client id (test string length is 65) let id = validate_client_identifier( "f0isrs5enif9e4td3r2jcbxoevhz6u1fthn4aforq7ams52jn5m48eiesfht9ckpn", ); assert!(id.is_err()) } #[test] fn parse_invalid_channel_id_min() { // invalid min channel id let id = validate_channel_identifier("channel"); assert!(id.is_err()) } #[test] fn parse_channel_id_max() { // invalid max channel id (test string length is 65) let id = validate_channel_identifier( "hlkbzrbmrh0rjrh8f8a8d9lmtjuhww7a9ev3blskc58amhwfq07zwp1xevxz1p098", ); assert!(id.is_err()) } #[test] fn parse_invalid_id_chars() { // invalid id chars let id = validate_identifier("channel@01", 1, 10); assert!(id.is_err()) } #[test] fn parse_invalid_id_empty() { // invalid id empty let id = validate_identifier("", 1, 10); assert!(id.is_err()) } #[test] fn parse_invalid_id_path_separator() { // invalid id with path separator let id = validate_identifier("id/1", 1, 10); assert!(id.is_err()) } }
29.099415
98
0.63746
502dde44cbe1b1e83649541fd81567c745cf6649
1,125
pub trait MinMaxIdentities { fn min_identity() -> Self; fn max_identity() -> Self; } macro_rules! impl_int_min_max_identities { ($int:ty) => { impl MinMaxIdentities for $int { fn min_identity() -> $int { <$int>::MAX } fn max_identity() -> $int { <$int>::MIN } } }; } impl_int_min_max_identities!(i8); impl_int_min_max_identities!(i16); impl_int_min_max_identities!(i32); impl_int_min_max_identities!(i64); impl_int_min_max_identities!(isize); impl_int_min_max_identities!(u8); impl_int_min_max_identities!(u16); impl_int_min_max_identities!(u32); impl_int_min_max_identities!(u64); impl_int_min_max_identities!(usize); macro_rules! impl_float_min_max_identities { ($float:ty) => { impl MinMaxIdentities for $float { fn min_identity() -> $float { <$float>::INFINITY } fn max_identity() -> $float { <$float>::NEG_INFINITY } } }; } impl_float_min_max_identities!(f32); impl_float_min_max_identities!(f64);
23.93617
44
0.608
38cae6323203481078d8198957c52ae4b8e69f5d
603
// 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. // error-pattern:mismatched types: expected `()` but found `bool` fn main() { let a = if true { true }; println!("{:?}", a); }
35.470588
68
0.701493
f97ff13c5e9b961fa91beaadbc9696f5b76903f4
1,426
pub struct IconStorage { props: crate::Props, } impl yew::Component for IconStorage { type Properties = crate::Props; type Message = (); fn create(props: Self::Properties, _: yew::prelude::ComponentLink<Self>) -> Self { Self { props } } fn update(&mut self, _: Self::Message) -> yew::prelude::ShouldRender { true } fn change(&mut self, _: Self::Properties) -> yew::prelude::ShouldRender { false } fn view(&self) -> yew::prelude::Html { yew::prelude::html! { <svg class=self.props.class.unwrap_or("") width=self.props.size.unwrap_or(24).to_string() height=self.props.size.unwrap_or(24).to_string() viewBox="0 0 24 24" fill=self.props.fill.unwrap_or("none") stroke=self.props.color.unwrap_or("currentColor") stroke-width=self.props.stroke_width.unwrap_or(2).to_string() stroke-linecap=self.props.stroke_linecap.unwrap_or("round") stroke-linejoin=self.props.stroke_linejoin.unwrap_or("round") > <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0z" fill="none"/><path d="M2 20h20v-4H2v4zm2-3h2v2H4v-2zM2 4v4h20V4H2zm4 3H4V5h2v2zm-4 7h20v-4H2v4zm2-3h2v2H4v-2z"/></svg> </svg> } } }
31
237
0.580645
03c745587e90dc1f424ee9964d5b0e227d8cfbd6
78,624
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// <p>Activates a partner event source that has been deactivated. Once activated, your matching /// event bus will start receiving events from the event source.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct ActivateEventSource { _private: (), } impl ActivateEventSource { /// Creates a new builder-style object to manufacture [`ActivateEventSourceInput`](crate::input::ActivateEventSourceInput) pub fn builder() -> crate::input::activate_event_source_input::Builder { crate::input::activate_event_source_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for ActivateEventSource { type Output = std::result::Result< crate::output::ActivateEventSourceOutput, crate::error::ActivateEventSourceError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_activate_event_source_error(response) } else { crate::operation_deser::parse_activate_event_source_response(response) } } } /// <p>Cancels the specified replay.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct CancelReplay { _private: (), } impl CancelReplay { /// Creates a new builder-style object to manufacture [`CancelReplayInput`](crate::input::CancelReplayInput) pub fn builder() -> crate::input::cancel_replay_input::Builder { crate::input::cancel_replay_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for CancelReplay { type Output = std::result::Result<crate::output::CancelReplayOutput, crate::error::CancelReplayError>; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_cancel_replay_error(response) } else { crate::operation_deser::parse_cancel_replay_response(response) } } } /// <p>Creates an API destination, which is an HTTP invocation endpoint configured as a target /// for events.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct CreateApiDestination { _private: (), } impl CreateApiDestination { /// Creates a new builder-style object to manufacture [`CreateApiDestinationInput`](crate::input::CreateApiDestinationInput) pub fn builder() -> crate::input::create_api_destination_input::Builder { crate::input::create_api_destination_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for CreateApiDestination { type Output = std::result::Result< crate::output::CreateApiDestinationOutput, crate::error::CreateApiDestinationError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_create_api_destination_error(response) } else { crate::operation_deser::parse_create_api_destination_response(response) } } } /// <p>Creates an archive of events with the specified settings. When you create an archive, /// incoming events might not immediately start being sent to the archive. Allow a short period of /// time for changes to take effect. If you do not specify a pattern to filter events sent to the /// archive, all events are sent to the archive except replayed events. Replayed events are not /// sent to an archive.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct CreateArchive { _private: (), } impl CreateArchive { /// Creates a new builder-style object to manufacture [`CreateArchiveInput`](crate::input::CreateArchiveInput) pub fn builder() -> crate::input::create_archive_input::Builder { crate::input::create_archive_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for CreateArchive { type Output = std::result::Result<crate::output::CreateArchiveOutput, crate::error::CreateArchiveError>; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_create_archive_error(response) } else { crate::operation_deser::parse_create_archive_response(response) } } } /// <p>Creates a connection. A connection defines the authorization type and credentials to use /// for authorization with an API destination HTTP endpoint.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct CreateConnection { _private: (), } impl CreateConnection { /// Creates a new builder-style object to manufacture [`CreateConnectionInput`](crate::input::CreateConnectionInput) pub fn builder() -> crate::input::create_connection_input::Builder { crate::input::create_connection_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for CreateConnection { type Output = std::result::Result< crate::output::CreateConnectionOutput, crate::error::CreateConnectionError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_create_connection_error(response) } else { crate::operation_deser::parse_create_connection_response(response) } } } /// <p>Creates a new event bus within your account. This can be a custom event bus which you can /// use to receive events from your custom applications and services, or it can be a partner event /// bus which can be matched to a partner event source.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct CreateEventBus { _private: (), } impl CreateEventBus { /// Creates a new builder-style object to manufacture [`CreateEventBusInput`](crate::input::CreateEventBusInput) pub fn builder() -> crate::input::create_event_bus_input::Builder { crate::input::create_event_bus_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for CreateEventBus { type Output = std::result::Result<crate::output::CreateEventBusOutput, crate::error::CreateEventBusError>; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_create_event_bus_error(response) } else { crate::operation_deser::parse_create_event_bus_response(response) } } } /// <p>Called by an SaaS partner to create a partner event source. This operation is not used by /// Amazon Web Services customers.</p> /// <p>Each partner event source can be used by one Amazon Web Services account to create a matching partner /// event bus in that Amazon Web Services account. A SaaS partner must create one partner event source for each /// Amazon Web Services account that wants to receive those event types. </p> /// <p>A partner event source creates events based on resources within the SaaS partner's service /// or application.</p> /// <p>An Amazon Web Services account that creates a partner event bus that matches the partner event source can /// use that event bus to receive events from the partner, and then process them using Amazon Web Services Events /// rules and targets.</p> /// <p>Partner event source names follow this format:</p> /// <p> /// <code> /// <i>partner_name</i>/<i>event_namespace</i>/<i>event_name</i> /// </code> /// </p> /// <p> /// <i>partner_name</i> is determined during partner registration and identifies /// the partner to Amazon Web Services customers. <i>event_namespace</i> is determined by the /// partner and is a way for the partner to categorize their events. /// <i>event_name</i> is determined by the partner, and should uniquely identify /// an event-generating resource within the partner system. The combination of /// <i>event_namespace</i> and <i>event_name</i> should help Amazon Web Services /// customers decide whether to create an event bus to receive these events.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct CreatePartnerEventSource { _private: (), } impl CreatePartnerEventSource { /// Creates a new builder-style object to manufacture [`CreatePartnerEventSourceInput`](crate::input::CreatePartnerEventSourceInput) pub fn builder() -> crate::input::create_partner_event_source_input::Builder { crate::input::create_partner_event_source_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for CreatePartnerEventSource { type Output = std::result::Result< crate::output::CreatePartnerEventSourceOutput, crate::error::CreatePartnerEventSourceError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_create_partner_event_source_error(response) } else { crate::operation_deser::parse_create_partner_event_source_response(response) } } } /// <p>You can use this operation to temporarily stop receiving events from the specified partner /// event source. The matching event bus is not deleted. </p> /// <p>When you deactivate a partner event source, the source goes into PENDING state. If it /// remains in PENDING state for more than two weeks, it is deleted.</p> /// <p>To activate a deactivated partner event source, use <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_ActivateEventSource.html">ActivateEventSource</a>.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct DeactivateEventSource { _private: (), } impl DeactivateEventSource { /// Creates a new builder-style object to manufacture [`DeactivateEventSourceInput`](crate::input::DeactivateEventSourceInput) pub fn builder() -> crate::input::deactivate_event_source_input::Builder { crate::input::deactivate_event_source_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for DeactivateEventSource { type Output = std::result::Result< crate::output::DeactivateEventSourceOutput, crate::error::DeactivateEventSourceError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_deactivate_event_source_error(response) } else { crate::operation_deser::parse_deactivate_event_source_response(response) } } } /// <p>Removes all authorization parameters from the connection. This lets you remove the secret /// from the connection so you can reuse it without having to create a new connection.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct DeauthorizeConnection { _private: (), } impl DeauthorizeConnection { /// Creates a new builder-style object to manufacture [`DeauthorizeConnectionInput`](crate::input::DeauthorizeConnectionInput) pub fn builder() -> crate::input::deauthorize_connection_input::Builder { crate::input::deauthorize_connection_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for DeauthorizeConnection { type Output = std::result::Result< crate::output::DeauthorizeConnectionOutput, crate::error::DeauthorizeConnectionError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_deauthorize_connection_error(response) } else { crate::operation_deser::parse_deauthorize_connection_response(response) } } } /// <p>Deletes the specified API destination.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct DeleteApiDestination { _private: (), } impl DeleteApiDestination { /// Creates a new builder-style object to manufacture [`DeleteApiDestinationInput`](crate::input::DeleteApiDestinationInput) pub fn builder() -> crate::input::delete_api_destination_input::Builder { crate::input::delete_api_destination_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for DeleteApiDestination { type Output = std::result::Result< crate::output::DeleteApiDestinationOutput, crate::error::DeleteApiDestinationError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_delete_api_destination_error(response) } else { crate::operation_deser::parse_delete_api_destination_response(response) } } } /// <p>Deletes the specified archive.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct DeleteArchive { _private: (), } impl DeleteArchive { /// Creates a new builder-style object to manufacture [`DeleteArchiveInput`](crate::input::DeleteArchiveInput) pub fn builder() -> crate::input::delete_archive_input::Builder { crate::input::delete_archive_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for DeleteArchive { type Output = std::result::Result<crate::output::DeleteArchiveOutput, crate::error::DeleteArchiveError>; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_delete_archive_error(response) } else { crate::operation_deser::parse_delete_archive_response(response) } } } /// <p>Deletes a connection.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct DeleteConnection { _private: (), } impl DeleteConnection { /// Creates a new builder-style object to manufacture [`DeleteConnectionInput`](crate::input::DeleteConnectionInput) pub fn builder() -> crate::input::delete_connection_input::Builder { crate::input::delete_connection_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for DeleteConnection { type Output = std::result::Result< crate::output::DeleteConnectionOutput, crate::error::DeleteConnectionError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_delete_connection_error(response) } else { crate::operation_deser::parse_delete_connection_response(response) } } } /// <p>Deletes the specified custom event bus or partner event bus. All rules associated with /// this event bus need to be deleted. You can't delete your account's default event bus.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct DeleteEventBus { _private: (), } impl DeleteEventBus { /// Creates a new builder-style object to manufacture [`DeleteEventBusInput`](crate::input::DeleteEventBusInput) pub fn builder() -> crate::input::delete_event_bus_input::Builder { crate::input::delete_event_bus_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for DeleteEventBus { type Output = std::result::Result<crate::output::DeleteEventBusOutput, crate::error::DeleteEventBusError>; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_delete_event_bus_error(response) } else { crate::operation_deser::parse_delete_event_bus_response(response) } } } /// <p>This operation is used by SaaS partners to delete a partner event source. This operation /// is not used by Amazon Web Services customers.</p> /// <p>When you delete an event source, the status of the corresponding partner event bus in the /// Amazon Web Services customer account becomes DELETED.</p> /// <p></p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct DeletePartnerEventSource { _private: (), } impl DeletePartnerEventSource { /// Creates a new builder-style object to manufacture [`DeletePartnerEventSourceInput`](crate::input::DeletePartnerEventSourceInput) pub fn builder() -> crate::input::delete_partner_event_source_input::Builder { crate::input::delete_partner_event_source_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for DeletePartnerEventSource { type Output = std::result::Result< crate::output::DeletePartnerEventSourceOutput, crate::error::DeletePartnerEventSourceError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_delete_partner_event_source_error(response) } else { crate::operation_deser::parse_delete_partner_event_source_response(response) } } } /// <p>Deletes the specified rule.</p> /// <p>Before you can delete the rule, you must remove all targets, using <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_RemoveTargets.html">RemoveTargets</a>.</p> /// <p>When you delete a rule, incoming events might continue to match to the deleted rule. Allow /// a short period of time for changes to take effect.</p> /// <p>If you call delete rule multiple times for the same rule, all calls will succeed. When you /// call delete rule for a non-existent custom eventbus, <code>ResourceNotFoundException</code> is /// returned.</p> /// <p>Managed rules are rules created and managed by another Amazon Web Services service on your behalf. These /// rules are created by those other Amazon Web Services services to support functionality in those services. You /// can delete these rules using the <code>Force</code> option, but you should do so only if you /// are sure the other service is not still using that rule.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct DeleteRule { _private: (), } impl DeleteRule { /// Creates a new builder-style object to manufacture [`DeleteRuleInput`](crate::input::DeleteRuleInput) pub fn builder() -> crate::input::delete_rule_input::Builder { crate::input::delete_rule_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for DeleteRule { type Output = std::result::Result<crate::output::DeleteRuleOutput, crate::error::DeleteRuleError>; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_delete_rule_error(response) } else { crate::operation_deser::parse_delete_rule_response(response) } } } /// <p>Retrieves details about an API destination.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct DescribeApiDestination { _private: (), } impl DescribeApiDestination { /// Creates a new builder-style object to manufacture [`DescribeApiDestinationInput`](crate::input::DescribeApiDestinationInput) pub fn builder() -> crate::input::describe_api_destination_input::Builder { crate::input::describe_api_destination_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for DescribeApiDestination { type Output = std::result::Result< crate::output::DescribeApiDestinationOutput, crate::error::DescribeApiDestinationError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_describe_api_destination_error(response) } else { crate::operation_deser::parse_describe_api_destination_response(response) } } } /// <p>Retrieves details about an archive.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct DescribeArchive { _private: (), } impl DescribeArchive { /// Creates a new builder-style object to manufacture [`DescribeArchiveInput`](crate::input::DescribeArchiveInput) pub fn builder() -> crate::input::describe_archive_input::Builder { crate::input::describe_archive_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for DescribeArchive { type Output = std::result::Result< crate::output::DescribeArchiveOutput, crate::error::DescribeArchiveError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_describe_archive_error(response) } else { crate::operation_deser::parse_describe_archive_response(response) } } } /// <p>Retrieves details about a connection.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct DescribeConnection { _private: (), } impl DescribeConnection { /// Creates a new builder-style object to manufacture [`DescribeConnectionInput`](crate::input::DescribeConnectionInput) pub fn builder() -> crate::input::describe_connection_input::Builder { crate::input::describe_connection_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for DescribeConnection { type Output = std::result::Result< crate::output::DescribeConnectionOutput, crate::error::DescribeConnectionError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_describe_connection_error(response) } else { crate::operation_deser::parse_describe_connection_response(response) } } } /// <p>Displays details about an event bus in your account. This can include the external Amazon Web Services /// accounts that are permitted to write events to your default event bus, and the associated /// policy. For custom event buses and partner event buses, it displays the name, ARN, policy, /// state, and creation time.</p> /// <p> To enable your account to receive events from other accounts on its default event bus, /// use <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_PutPermission.html">PutPermission</a>.</p> /// <p>For more information about partner event buses, see <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_CreateEventBus.html">CreateEventBus</a>.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct DescribeEventBus { _private: (), } impl DescribeEventBus { /// Creates a new builder-style object to manufacture [`DescribeEventBusInput`](crate::input::DescribeEventBusInput) pub fn builder() -> crate::input::describe_event_bus_input::Builder { crate::input::describe_event_bus_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for DescribeEventBus { type Output = std::result::Result< crate::output::DescribeEventBusOutput, crate::error::DescribeEventBusError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_describe_event_bus_error(response) } else { crate::operation_deser::parse_describe_event_bus_response(response) } } } /// <p>This operation lists details about a partner event source that is shared with your /// account.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct DescribeEventSource { _private: (), } impl DescribeEventSource { /// Creates a new builder-style object to manufacture [`DescribeEventSourceInput`](crate::input::DescribeEventSourceInput) pub fn builder() -> crate::input::describe_event_source_input::Builder { crate::input::describe_event_source_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for DescribeEventSource { type Output = std::result::Result< crate::output::DescribeEventSourceOutput, crate::error::DescribeEventSourceError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_describe_event_source_error(response) } else { crate::operation_deser::parse_describe_event_source_response(response) } } } /// <p>An SaaS partner can use this operation to list details about a partner event source that /// they have created. Amazon Web Services customers do not use this operation. Instead, Amazon Web Services customers can use <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_DescribeEventSource.html">DescribeEventSource</a> /// to see details about a partner event source that is /// shared with them.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct DescribePartnerEventSource { _private: (), } impl DescribePartnerEventSource { /// Creates a new builder-style object to manufacture [`DescribePartnerEventSourceInput`](crate::input::DescribePartnerEventSourceInput) pub fn builder() -> crate::input::describe_partner_event_source_input::Builder { crate::input::describe_partner_event_source_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for DescribePartnerEventSource { type Output = std::result::Result< crate::output::DescribePartnerEventSourceOutput, crate::error::DescribePartnerEventSourceError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_describe_partner_event_source_error(response) } else { crate::operation_deser::parse_describe_partner_event_source_response(response) } } } /// <p>Retrieves details about a replay. Use <code>DescribeReplay</code> to determine the /// progress of a running replay. A replay processes events to replay based on the time in the /// event, and replays them using 1 minute intervals. If you use <code>StartReplay</code> and /// specify an <code>EventStartTime</code> and an <code>EventEndTime</code> that covers a 20 /// minute time range, the events are replayed from the first minute of that 20 minute range /// first. Then the events from the second minute are replayed. You can use /// <code>DescribeReplay</code> to determine the progress of a replay. The value returned for /// <code>EventLastReplayedTime</code> indicates the time within the specified time range /// associated with the last event replayed.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct DescribeReplay { _private: (), } impl DescribeReplay { /// Creates a new builder-style object to manufacture [`DescribeReplayInput`](crate::input::DescribeReplayInput) pub fn builder() -> crate::input::describe_replay_input::Builder { crate::input::describe_replay_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for DescribeReplay { type Output = std::result::Result<crate::output::DescribeReplayOutput, crate::error::DescribeReplayError>; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_describe_replay_error(response) } else { crate::operation_deser::parse_describe_replay_response(response) } } } /// <p>Describes the specified rule.</p> /// <p>DescribeRule does not list the targets of a rule. To see the targets associated with a /// rule, use <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_ListTargetsByRule.html">ListTargetsByRule</a>.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct DescribeRule { _private: (), } impl DescribeRule { /// Creates a new builder-style object to manufacture [`DescribeRuleInput`](crate::input::DescribeRuleInput) pub fn builder() -> crate::input::describe_rule_input::Builder { crate::input::describe_rule_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for DescribeRule { type Output = std::result::Result<crate::output::DescribeRuleOutput, crate::error::DescribeRuleError>; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_describe_rule_error(response) } else { crate::operation_deser::parse_describe_rule_response(response) } } } /// <p>Disables the specified rule. A disabled rule won't match any events, and won't /// self-trigger if it has a schedule expression.</p> /// <p>When you disable a rule, incoming events might continue to match to the disabled rule. /// Allow a short period of time for changes to take effect.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct DisableRule { _private: (), } impl DisableRule { /// Creates a new builder-style object to manufacture [`DisableRuleInput`](crate::input::DisableRuleInput) pub fn builder() -> crate::input::disable_rule_input::Builder { crate::input::disable_rule_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for DisableRule { type Output = std::result::Result<crate::output::DisableRuleOutput, crate::error::DisableRuleError>; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_disable_rule_error(response) } else { crate::operation_deser::parse_disable_rule_response(response) } } } /// <p>Enables the specified rule. If the rule does not exist, the operation fails.</p> /// <p>When you enable a rule, incoming events might not immediately start matching to a newly /// enabled rule. Allow a short period of time for changes to take effect.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct EnableRule { _private: (), } impl EnableRule { /// Creates a new builder-style object to manufacture [`EnableRuleInput`](crate::input::EnableRuleInput) pub fn builder() -> crate::input::enable_rule_input::Builder { crate::input::enable_rule_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for EnableRule { type Output = std::result::Result<crate::output::EnableRuleOutput, crate::error::EnableRuleError>; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_enable_rule_error(response) } else { crate::operation_deser::parse_enable_rule_response(response) } } } /// <p>Retrieves a list of API destination in the account in the current Region.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct ListApiDestinations { _private: (), } impl ListApiDestinations { /// Creates a new builder-style object to manufacture [`ListApiDestinationsInput`](crate::input::ListApiDestinationsInput) pub fn builder() -> crate::input::list_api_destinations_input::Builder { crate::input::list_api_destinations_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for ListApiDestinations { type Output = std::result::Result< crate::output::ListApiDestinationsOutput, crate::error::ListApiDestinationsError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_list_api_destinations_error(response) } else { crate::operation_deser::parse_list_api_destinations_response(response) } } } /// <p>Lists your archives. You can either list all the archives or you can provide a prefix to /// match to the archive names. Filter parameters are exclusive.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct ListArchives { _private: (), } impl ListArchives { /// Creates a new builder-style object to manufacture [`ListArchivesInput`](crate::input::ListArchivesInput) pub fn builder() -> crate::input::list_archives_input::Builder { crate::input::list_archives_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for ListArchives { type Output = std::result::Result<crate::output::ListArchivesOutput, crate::error::ListArchivesError>; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_list_archives_error(response) } else { crate::operation_deser::parse_list_archives_response(response) } } } /// <p>Retrieves a list of connections from the account.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct ListConnections { _private: (), } impl ListConnections { /// Creates a new builder-style object to manufacture [`ListConnectionsInput`](crate::input::ListConnectionsInput) pub fn builder() -> crate::input::list_connections_input::Builder { crate::input::list_connections_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for ListConnections { type Output = std::result::Result< crate::output::ListConnectionsOutput, crate::error::ListConnectionsError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_list_connections_error(response) } else { crate::operation_deser::parse_list_connections_response(response) } } } /// <p>Lists all the event buses in your account, including the default event bus, custom event /// buses, and partner event buses.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct ListEventBuses { _private: (), } impl ListEventBuses { /// Creates a new builder-style object to manufacture [`ListEventBusesInput`](crate::input::ListEventBusesInput) pub fn builder() -> crate::input::list_event_buses_input::Builder { crate::input::list_event_buses_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for ListEventBuses { type Output = std::result::Result<crate::output::ListEventBusesOutput, crate::error::ListEventBusesError>; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_list_event_buses_error(response) } else { crate::operation_deser::parse_list_event_buses_response(response) } } } /// <p>You can use this to see all the partner event sources that have been shared with your Amazon Web Services /// account. For more information about partner event sources, see <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_CreateEventBus.html">CreateEventBus</a>.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct ListEventSources { _private: (), } impl ListEventSources { /// Creates a new builder-style object to manufacture [`ListEventSourcesInput`](crate::input::ListEventSourcesInput) pub fn builder() -> crate::input::list_event_sources_input::Builder { crate::input::list_event_sources_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for ListEventSources { type Output = std::result::Result< crate::output::ListEventSourcesOutput, crate::error::ListEventSourcesError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_list_event_sources_error(response) } else { crate::operation_deser::parse_list_event_sources_response(response) } } } /// <p>An SaaS partner can use this operation to display the Amazon Web Services account ID that a particular /// partner event source name is associated with. This operation is not used by Amazon Web Services /// customers.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct ListPartnerEventSourceAccounts { _private: (), } impl ListPartnerEventSourceAccounts { /// Creates a new builder-style object to manufacture [`ListPartnerEventSourceAccountsInput`](crate::input::ListPartnerEventSourceAccountsInput) pub fn builder() -> crate::input::list_partner_event_source_accounts_input::Builder { crate::input::list_partner_event_source_accounts_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for ListPartnerEventSourceAccounts { type Output = std::result::Result< crate::output::ListPartnerEventSourceAccountsOutput, crate::error::ListPartnerEventSourceAccountsError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_list_partner_event_source_accounts_error(response) } else { crate::operation_deser::parse_list_partner_event_source_accounts_response(response) } } } /// <p>An SaaS partner can use this operation to list all the partner event source names that /// they have created. This operation is not used by Amazon Web Services customers.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct ListPartnerEventSources { _private: (), } impl ListPartnerEventSources { /// Creates a new builder-style object to manufacture [`ListPartnerEventSourcesInput`](crate::input::ListPartnerEventSourcesInput) pub fn builder() -> crate::input::list_partner_event_sources_input::Builder { crate::input::list_partner_event_sources_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for ListPartnerEventSources { type Output = std::result::Result< crate::output::ListPartnerEventSourcesOutput, crate::error::ListPartnerEventSourcesError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_list_partner_event_sources_error(response) } else { crate::operation_deser::parse_list_partner_event_sources_response(response) } } } /// <p>Lists your replays. You can either list all the replays or you can provide a prefix to /// match to the replay names. Filter parameters are exclusive.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct ListReplays { _private: (), } impl ListReplays { /// Creates a new builder-style object to manufacture [`ListReplaysInput`](crate::input::ListReplaysInput) pub fn builder() -> crate::input::list_replays_input::Builder { crate::input::list_replays_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for ListReplays { type Output = std::result::Result<crate::output::ListReplaysOutput, crate::error::ListReplaysError>; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_list_replays_error(response) } else { crate::operation_deser::parse_list_replays_response(response) } } } /// <p>Lists the rules for the specified target. You can see which of the rules in Amazon /// EventBridge can invoke a specific target in your account.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct ListRuleNamesByTarget { _private: (), } impl ListRuleNamesByTarget { /// Creates a new builder-style object to manufacture [`ListRuleNamesByTargetInput`](crate::input::ListRuleNamesByTargetInput) pub fn builder() -> crate::input::list_rule_names_by_target_input::Builder { crate::input::list_rule_names_by_target_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for ListRuleNamesByTarget { type Output = std::result::Result< crate::output::ListRuleNamesByTargetOutput, crate::error::ListRuleNamesByTargetError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_list_rule_names_by_target_error(response) } else { crate::operation_deser::parse_list_rule_names_by_target_response(response) } } } /// <p>Lists your Amazon EventBridge rules. You can either list all the rules or you can provide /// a prefix to match to the rule names.</p> /// <p>ListRules does not list the targets of a rule. To see the targets associated with a rule, /// use <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_ListTargetsByRule.html">ListTargetsByRule</a>.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct ListRules { _private: (), } impl ListRules { /// Creates a new builder-style object to manufacture [`ListRulesInput`](crate::input::ListRulesInput) pub fn builder() -> crate::input::list_rules_input::Builder { crate::input::list_rules_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for ListRules { type Output = std::result::Result<crate::output::ListRulesOutput, crate::error::ListRulesError>; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_list_rules_error(response) } else { crate::operation_deser::parse_list_rules_response(response) } } } /// <p>Displays the tags associated with an EventBridge resource. In EventBridge, rules and event /// buses can be tagged.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct ListTagsForResource { _private: (), } impl ListTagsForResource { /// Creates a new builder-style object to manufacture [`ListTagsForResourceInput`](crate::input::ListTagsForResourceInput) pub fn builder() -> crate::input::list_tags_for_resource_input::Builder { crate::input::list_tags_for_resource_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for ListTagsForResource { type Output = std::result::Result< crate::output::ListTagsForResourceOutput, crate::error::ListTagsForResourceError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_list_tags_for_resource_error(response) } else { crate::operation_deser::parse_list_tags_for_resource_response(response) } } } /// <p>Lists the targets assigned to the specified rule.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct ListTargetsByRule { _private: (), } impl ListTargetsByRule { /// Creates a new builder-style object to manufacture [`ListTargetsByRuleInput`](crate::input::ListTargetsByRuleInput) pub fn builder() -> crate::input::list_targets_by_rule_input::Builder { crate::input::list_targets_by_rule_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for ListTargetsByRule { type Output = std::result::Result< crate::output::ListTargetsByRuleOutput, crate::error::ListTargetsByRuleError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_list_targets_by_rule_error(response) } else { crate::operation_deser::parse_list_targets_by_rule_response(response) } } } /// <p>Sends custom events to Amazon EventBridge so that they can be matched to rules.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct PutEvents { _private: (), } impl PutEvents { /// Creates a new builder-style object to manufacture [`PutEventsInput`](crate::input::PutEventsInput) pub fn builder() -> crate::input::put_events_input::Builder { crate::input::put_events_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for PutEvents { type Output = std::result::Result<crate::output::PutEventsOutput, crate::error::PutEventsError>; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_put_events_error(response) } else { crate::operation_deser::parse_put_events_response(response) } } } /// <p>This is used by SaaS partners to write events to a customer's partner event bus. Amazon Web Services /// customers do not use this operation.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct PutPartnerEvents { _private: (), } impl PutPartnerEvents { /// Creates a new builder-style object to manufacture [`PutPartnerEventsInput`](crate::input::PutPartnerEventsInput) pub fn builder() -> crate::input::put_partner_events_input::Builder { crate::input::put_partner_events_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for PutPartnerEvents { type Output = std::result::Result< crate::output::PutPartnerEventsOutput, crate::error::PutPartnerEventsError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_put_partner_events_error(response) } else { crate::operation_deser::parse_put_partner_events_response(response) } } } /// <p>Running <code>PutPermission</code> permits the specified Amazon Web Services account or Amazon Web Services organization /// to put events to the specified <i>event bus</i>. Amazon EventBridge (CloudWatch /// Events) rules in your account are triggered by these events arriving to an event bus in your /// account. </p> /// <p>For another account to send events to your account, that external account must have an /// EventBridge rule with your account's event bus as a target.</p> /// <p>To enable multiple Amazon Web Services accounts to put events to your event bus, run /// <code>PutPermission</code> once for each of these accounts. Or, if all the accounts are /// members of the same Amazon Web Services organization, you can run <code>PutPermission</code> once specifying /// <code>Principal</code> as "*" and specifying the Amazon Web Services organization ID in /// <code>Condition</code>, to grant permissions to all accounts in that organization.</p> /// <p>If you grant permissions using an organization, then accounts in that organization must /// specify a <code>RoleArn</code> with proper permissions when they use <code>PutTarget</code> to /// add your account's event bus as a target. For more information, see <a href="https://docs.aws.amazon.com/eventbridge/latest/userguide/eventbridge-cross-account-event-delivery.html">Sending and /// Receiving Events Between Amazon Web Services Accounts</a> in the <i>Amazon EventBridge User /// Guide</i>.</p> /// <p>The permission policy on the event bus cannot exceed 10 KB in size.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct PutPermission { _private: (), } impl PutPermission { /// Creates a new builder-style object to manufacture [`PutPermissionInput`](crate::input::PutPermissionInput) pub fn builder() -> crate::input::put_permission_input::Builder { crate::input::put_permission_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for PutPermission { type Output = std::result::Result<crate::output::PutPermissionOutput, crate::error::PutPermissionError>; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_put_permission_error(response) } else { crate::operation_deser::parse_put_permission_response(response) } } } /// <p>Creates or updates the specified rule. Rules are enabled by default, or based on value of /// the state. You can disable a rule using <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_DisableRule.html">DisableRule</a>.</p> /// <p>A single rule watches for events from a single event bus. Events generated by Amazon Web Services services /// go to your account's default event bus. Events generated by SaaS partner services or /// applications go to the matching partner event bus. If you have custom applications or /// services, you can specify whether their events go to your default event bus or a custom event /// bus that you have created. For more information, see <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_CreateEventBus.html">CreateEventBus</a>.</p> /// <p>If you are updating an existing rule, the rule is replaced with what you specify in this /// <code>PutRule</code> command. If you omit arguments in <code>PutRule</code>, the old values /// for those arguments are not kept. Instead, they are replaced with null values.</p> /// <p>When you create or update a rule, incoming events might not immediately start matching to /// new or updated rules. Allow a short period of time for changes to take effect.</p> /// <p>A rule must contain at least an EventPattern or ScheduleExpression. Rules with /// EventPatterns are triggered when a matching event is observed. Rules with ScheduleExpressions /// self-trigger based on the given schedule. A rule can have both an EventPattern and a /// ScheduleExpression, in which case the rule triggers on matching events as well as on a /// schedule.</p> /// <p>When you initially create a rule, you can optionally assign one or more tags to the rule. /// Tags can help you organize and categorize your resources. You can also use them to scope user /// permissions, by granting a user permission to access or change only rules with certain tag /// values. To use the <code>PutRule</code> operation and assign tags, you must have both the /// <code>events:PutRule</code> and <code>events:TagResource</code> permissions.</p> /// <p>If you are updating an existing rule, any tags you specify in the <code>PutRule</code> /// operation are ignored. To update the tags of an existing rule, use <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_TagResource.html">TagResource</a> and <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_UntagResource.html">UntagResource</a>.</p> /// <p>Most services in Amazon Web Services treat : or / as the same character in Amazon Resource Names (ARNs). /// However, EventBridge uses an exact match in event patterns and rules. Be sure to use the /// correct ARN characters when creating event patterns so that they match the ARN syntax in the /// event you want to match.</p> /// <p>In EventBridge, it is possible to create rules that lead to infinite loops, where a rule /// is fired repeatedly. For example, a rule might detect that ACLs have changed on an S3 bucket, /// and trigger software to change them to the desired state. If the rule is not written /// carefully, the subsequent change to the ACLs fires the rule again, creating an infinite /// loop.</p> /// <p>To prevent this, write the rules so that the triggered actions do not re-fire the same /// rule. For example, your rule could fire only if ACLs are found to be in a bad state, instead /// of after any change. </p> /// <p>An infinite loop can quickly cause higher than expected charges. We recommend that you use /// budgeting, which alerts you when charges exceed your specified limit. For more information, /// see <a href="https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/budgets-managing-costs.html">Managing Your Costs with /// Budgets</a>.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct PutRule { _private: (), } impl PutRule { /// Creates a new builder-style object to manufacture [`PutRuleInput`](crate::input::PutRuleInput) pub fn builder() -> crate::input::put_rule_input::Builder { crate::input::put_rule_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for PutRule { type Output = std::result::Result<crate::output::PutRuleOutput, crate::error::PutRuleError>; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_put_rule_error(response) } else { crate::operation_deser::parse_put_rule_response(response) } } } /// <p>Adds the specified targets to the specified rule, or updates the targets if they are /// already associated with the rule.</p> /// <p>Targets are the resources that are invoked when a rule is triggered.</p> /// <p>You can configure the following as targets for Events:</p> /// <ul> /// <li> /// <p> /// <a href="https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-api-destinations.html">API /// destination</a> /// </p> /// </li> /// <li> /// <p>Amazon API Gateway REST API endpoints</p> /// </li> /// <li> /// <p>API Gateway</p> /// </li> /// <li> /// <p>Batch job queue</p> /// </li> /// <li> /// <p>CloudWatch Logs group</p> /// </li> /// <li> /// <p>CodeBuild project</p> /// </li> /// <li> /// <p>CodePipeline</p> /// </li> /// <li> /// <p>Amazon EC2 <code>CreateSnapshot</code> API call</p> /// </li> /// <li> /// <p>Amazon EC2 <code>RebootInstances</code> API call</p> /// </li> /// <li> /// <p>Amazon EC2 <code>StopInstances</code> API call</p> /// </li> /// <li> /// <p>Amazon EC2 <code>TerminateInstances</code> API call</p> /// </li> /// <li> /// <p>Amazon ECS tasks</p> /// </li> /// <li> /// <p>Event bus in a different Amazon Web Services account or Region.</p> /// <p>You can use an event bus in the US East (N. Virginia) us-east-1, US West (Oregon) /// us-west-2, or Europe (Ireland) eu-west-1 Regions as a target for a rule.</p> /// </li> /// <li> /// <p>Firehose delivery stream (Kinesis Data Firehose)</p> /// </li> /// <li> /// <p>Inspector assessment template (Amazon Inspector)</p> /// </li> /// <li> /// <p>Kinesis stream (Kinesis Data Stream)</p> /// </li> /// <li> /// <p>Lambda function</p> /// </li> /// <li> /// <p>Redshift clusters (Data API statement execution)</p> /// </li> /// <li> /// <p>Amazon SNS topic</p> /// </li> /// <li> /// <p>Amazon SQS queues (includes FIFO queues</p> /// </li> /// <li> /// <p>SSM Automation</p> /// </li> /// <li> /// <p>SSM OpsItem</p> /// </li> /// <li> /// <p>SSM Run Command</p> /// </li> /// <li> /// <p>Step Functions state machines</p> /// </li> /// </ul> /// <p>Creating rules with built-in targets is supported only in the Amazon Web Services Management Console. The /// built-in targets are <code>EC2 CreateSnapshot API call</code>, <code>EC2 RebootInstances API /// call</code>, <code>EC2 StopInstances API call</code>, and <code>EC2 TerminateInstances API /// call</code>. </p> /// <p>For some target types, <code>PutTargets</code> provides target-specific parameters. If the /// target is a Kinesis data stream, you can optionally specify which shard the event goes to by /// using the <code>KinesisParameters</code> argument. To invoke a command on multiple EC2 /// instances with one rule, you can use the <code>RunCommandParameters</code> field.</p> /// <p>To be able to make API calls against the resources that you own, Amazon EventBridge /// needs the appropriate permissions. For Lambda and Amazon SNS /// resources, EventBridge relies on resource-based policies. For EC2 instances, Kinesis Data Streams, /// Step Functions state machines and API Gateway REST APIs, EventBridge relies on /// IAM roles that you specify in the <code>RoleARN</code> argument in <code>PutTargets</code>. /// For more information, see <a href="https://docs.aws.amazon.com/eventbridge/latest/userguide/auth-and-access-control-eventbridge.html">Authentication /// and Access Control</a> in the <i>Amazon EventBridge User Guide</i>.</p> /// <p>If another Amazon Web Services account is in the same region and has granted you permission (using /// <code>PutPermission</code>), you can send events to that account. Set that account's event /// bus as a target of the rules in your account. To send the matched events to the other account, /// specify that account's event bus as the <code>Arn</code> value when you run /// <code>PutTargets</code>. If your account sends events to another account, your account is /// charged for each sent event. Each event sent to another account is charged as a custom event. /// The account receiving the event is not charged. For more information, see <a href="http://aws.amazon.com/eventbridge/pricing/">Amazon EventBridge /// Pricing</a>.</p> /// <note> /// <p> /// <code>Input</code>, <code>InputPath</code>, and <code>InputTransformer</code> are not /// available with <code>PutTarget</code> if the target is an event bus of a different Amazon Web Services /// account.</p> /// </note> /// <p>If you are setting the event bus of another account as the target, and that account /// granted permission to your account through an organization instead of directly by the account /// ID, then you must specify a <code>RoleArn</code> with proper permissions in the /// <code>Target</code> structure. For more information, see <a href="https://docs.aws.amazon.com/eventbridge/latest/userguide/eventbridge-cross-account-event-delivery.html">Sending and /// Receiving Events Between Amazon Web Services Accounts</a> in the <i>Amazon EventBridge User /// Guide</i>.</p> /// <p>For more information about enabling cross-account events, see <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_PutPermission.html">PutPermission</a>.</p> /// <p> /// <b>Input</b>, <b>InputPath</b>, and /// <b>InputTransformer</b> are mutually exclusive and optional /// parameters of a target. When a rule is triggered due to a matched event:</p> /// <ul> /// <li> /// <p>If none of the following arguments are specified for a target, then the entire event /// is passed to the target in JSON format (unless the target is Amazon EC2 Run Command or /// Amazon ECS task, in which case nothing from the event is passed to the target).</p> /// </li> /// <li> /// <p>If <b>Input</b> is specified in the form of valid JSON, then /// the matched event is overridden with this constant.</p> /// </li> /// <li> /// <p>If <b>InputPath</b> is specified in the form of JSONPath /// (for example, <code>$.detail</code>), then only the part of the event specified in the /// path is passed to the target (for example, only the detail part of the event is /// passed).</p> /// </li> /// <li> /// <p>If <b>InputTransformer</b> is specified, then one or more /// specified JSONPaths are extracted from the event and used as values in a template that you /// specify as the input to the target.</p> /// </li> /// </ul> /// <p>When you specify <code>InputPath</code> or <code>InputTransformer</code>, you must use /// JSON dot notation, not bracket notation.</p> /// <p>When you add targets to a rule and the associated rule triggers soon after, new or updated /// targets might not be immediately invoked. Allow a short period of time for changes to take /// effect.</p> /// <p>This action can partially fail if too many requests are made at the same time. If that /// happens, <code>FailedEntryCount</code> is non-zero in the response and each entry in /// <code>FailedEntries</code> provides the ID of the failed target and the error code.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct PutTargets { _private: (), } impl PutTargets { /// Creates a new builder-style object to manufacture [`PutTargetsInput`](crate::input::PutTargetsInput) pub fn builder() -> crate::input::put_targets_input::Builder { crate::input::put_targets_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for PutTargets { type Output = std::result::Result<crate::output::PutTargetsOutput, crate::error::PutTargetsError>; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_put_targets_error(response) } else { crate::operation_deser::parse_put_targets_response(response) } } } /// <p>Revokes the permission of another Amazon Web Services account to be able to put events to the specified /// event bus. Specify the account to revoke by the <code>StatementId</code> value that you /// associated with the account when you granted it permission with <code>PutPermission</code>. /// You can find the <code>StatementId</code> by using <a href="https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_DescribeEventBus.html">DescribeEventBus</a>.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct RemovePermission { _private: (), } impl RemovePermission { /// Creates a new builder-style object to manufacture [`RemovePermissionInput`](crate::input::RemovePermissionInput) pub fn builder() -> crate::input::remove_permission_input::Builder { crate::input::remove_permission_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for RemovePermission { type Output = std::result::Result< crate::output::RemovePermissionOutput, crate::error::RemovePermissionError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_remove_permission_error(response) } else { crate::operation_deser::parse_remove_permission_response(response) } } } /// <p>Removes the specified targets from the specified rule. When the rule is triggered, those /// targets are no longer be invoked.</p> /// <p>When you remove a target, when the associated rule triggers, removed targets might /// continue to be invoked. Allow a short period of time for changes to take effect.</p> /// <p>This action can partially fail if too many requests are made at the same time. If that /// happens, <code>FailedEntryCount</code> is non-zero in the response and each entry in /// <code>FailedEntries</code> provides the ID of the failed target and the error code.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct RemoveTargets { _private: (), } impl RemoveTargets { /// Creates a new builder-style object to manufacture [`RemoveTargetsInput`](crate::input::RemoveTargetsInput) pub fn builder() -> crate::input::remove_targets_input::Builder { crate::input::remove_targets_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for RemoveTargets { type Output = std::result::Result<crate::output::RemoveTargetsOutput, crate::error::RemoveTargetsError>; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_remove_targets_error(response) } else { crate::operation_deser::parse_remove_targets_response(response) } } } /// <p>Starts the specified replay. Events are not necessarily replayed in the exact same order /// that they were added to the archive. A replay processes events to replay based on the time in /// the event, and replays them using 1 minute intervals. If you specify an /// <code>EventStartTime</code> and an <code>EventEndTime</code> that covers a 20 minute time /// range, the events are replayed from the first minute of that 20 minute range first. Then the /// events from the second minute are replayed. You can use <code>DescribeReplay</code> to /// determine the progress of a replay. The value returned for <code>EventLastReplayedTime</code> /// indicates the time within the specified time range associated with the last event /// replayed.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct StartReplay { _private: (), } impl StartReplay { /// Creates a new builder-style object to manufacture [`StartReplayInput`](crate::input::StartReplayInput) pub fn builder() -> crate::input::start_replay_input::Builder { crate::input::start_replay_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for StartReplay { type Output = std::result::Result<crate::output::StartReplayOutput, crate::error::StartReplayError>; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_start_replay_error(response) } else { crate::operation_deser::parse_start_replay_response(response) } } } /// <p>Assigns one or more tags (key-value pairs) to the specified EventBridge resource. Tags can /// help you organize and categorize your resources. You can also use them to scope user /// permissions by granting a user permission to access or change only resources with certain tag /// values. In EventBridge, rules and event buses can be tagged.</p> /// <p>Tags don't have any semantic meaning to Amazon Web Services and are interpreted strictly as strings of /// characters.</p> /// <p>You can use the <code>TagResource</code> action with a resource that already has tags. If /// you specify a new tag key, this tag is appended to the list of tags associated with the /// resource. If you specify a tag key that is already associated with the resource, the new tag /// value that you specify replaces the previous value for that tag.</p> /// <p>You can associate as many as 50 tags with a resource.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct TagResource { _private: (), } impl TagResource { /// Creates a new builder-style object to manufacture [`TagResourceInput`](crate::input::TagResourceInput) pub fn builder() -> crate::input::tag_resource_input::Builder { crate::input::tag_resource_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for TagResource { type Output = std::result::Result<crate::output::TagResourceOutput, crate::error::TagResourceError>; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_tag_resource_error(response) } else { crate::operation_deser::parse_tag_resource_response(response) } } } /// <p>Tests whether the specified event pattern matches the provided event.</p> /// <p>Most services in Amazon Web Services treat : or / as the same character in Amazon Resource Names (ARNs). /// However, EventBridge uses an exact match in event patterns and rules. Be sure to use the /// correct ARN characters when creating event patterns so that they match the ARN syntax in the /// event you want to match.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct TestEventPattern { _private: (), } impl TestEventPattern { /// Creates a new builder-style object to manufacture [`TestEventPatternInput`](crate::input::TestEventPatternInput) pub fn builder() -> crate::input::test_event_pattern_input::Builder { crate::input::test_event_pattern_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for TestEventPattern { type Output = std::result::Result< crate::output::TestEventPatternOutput, crate::error::TestEventPatternError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_test_event_pattern_error(response) } else { crate::operation_deser::parse_test_event_pattern_response(response) } } } /// <p>Removes one or more tags from the specified EventBridge resource. In Amazon EventBridge /// (CloudWatch Events), rules and event buses can be tagged.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct UntagResource { _private: (), } impl UntagResource { /// Creates a new builder-style object to manufacture [`UntagResourceInput`](crate::input::UntagResourceInput) pub fn builder() -> crate::input::untag_resource_input::Builder { crate::input::untag_resource_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for UntagResource { type Output = std::result::Result<crate::output::UntagResourceOutput, crate::error::UntagResourceError>; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_untag_resource_error(response) } else { crate::operation_deser::parse_untag_resource_response(response) } } } /// <p>Updates an API destination.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct UpdateApiDestination { _private: (), } impl UpdateApiDestination { /// Creates a new builder-style object to manufacture [`UpdateApiDestinationInput`](crate::input::UpdateApiDestinationInput) pub fn builder() -> crate::input::update_api_destination_input::Builder { crate::input::update_api_destination_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for UpdateApiDestination { type Output = std::result::Result< crate::output::UpdateApiDestinationOutput, crate::error::UpdateApiDestinationError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_update_api_destination_error(response) } else { crate::operation_deser::parse_update_api_destination_response(response) } } } /// <p>Updates the specified archive.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct UpdateArchive { _private: (), } impl UpdateArchive { /// Creates a new builder-style object to manufacture [`UpdateArchiveInput`](crate::input::UpdateArchiveInput) pub fn builder() -> crate::input::update_archive_input::Builder { crate::input::update_archive_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for UpdateArchive { type Output = std::result::Result<crate::output::UpdateArchiveOutput, crate::error::UpdateArchiveError>; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_update_archive_error(response) } else { crate::operation_deser::parse_update_archive_response(response) } } } /// <p>Updates settings for a connection.</p> #[derive(std::default::Default, std::clone::Clone, std::fmt::Debug)] pub struct UpdateConnection { _private: (), } impl UpdateConnection { /// Creates a new builder-style object to manufacture [`UpdateConnectionInput`](crate::input::UpdateConnectionInput) pub fn builder() -> crate::input::update_connection_input::Builder { crate::input::update_connection_input::Builder::default() } pub fn new() -> Self { Self { _private: () } } } impl smithy_http::response::ParseStrictResponse for UpdateConnection { type Output = std::result::Result< crate::output::UpdateConnectionOutput, crate::error::UpdateConnectionError, >; fn parse(&self, response: &http::Response<bytes::Bytes>) -> Self::Output { if !response.status().is_success() && response.status().as_u16() != 200 { crate::operation_deser::parse_update_connection_error(response) } else { crate::operation_deser::parse_update_connection_response(response) } } }
46.005851
297
0.690603
641a9554d1cf6ab04fc3d63e06ee44424d48f7c0
19,641
// Copyright 2018 The Grin Developers // // 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. //! Values that should be shared across all modules, without necessarily //! having to pass them all over the place, but aren't consensus values. //! should be used sparingly. use crate::consensus; use crate::consensus::HeaderInfo; use crate::consensus::{ graph_weight, BASE_EDGE_BITS, BLOCK_TIME_SEC, COINBASE_MATURITY, CUT_THROUGH_HORIZON, DAY_HEIGHT, DEFAULT_MIN_EDGE_BITS, DIFFICULTY_ADJUST_WINDOW, INITIAL_DIFFICULTY, MAX_BLOCK_WEIGHT, PROOFSIZE, SECOND_POW_EDGE_BITS, STATE_SYNC_THRESHOLD, }; use crate::core::block::feijoada::{AllowPolicy, Policy, PolicyConfig}; use crate::pow::{self, new_cuckaroo_ctx, new_cuckatoo_ctx, EdgeType, PoWContext}; /// An enum collecting sets of parameters used throughout the /// code wherever mining is needed. This should allow for /// different sets of parameters for different purposes, /// e.g. CI, User testing, production values use crate::util::RwLock; use chrono::prelude::Utc; use sha2::{Digest, Sha256}; use std::collections::HashMap; use std::env; use std::fs::File; use std::path::Path; /// Define these here, as they should be developer-set, not really tweakable /// by users /// Automated testing edge_bits pub const AUTOMATED_TESTING_MIN_EDGE_BITS: u8 = 9; /// Automated testing proof size pub const AUTOMATED_TESTING_PROOF_SIZE: usize = 4; /// User testing edge_bits pub const USER_TESTING_MIN_EDGE_BITS: u8 = 15; /// User testing proof size pub const USER_TESTING_PROOF_SIZE: usize = 42; /// Automated testing coinbase maturity pub const AUTOMATED_TESTING_COINBASE_MATURITY: u64 = 3; /// User testing coinbase maturity pub const USER_TESTING_COINBASE_MATURITY: u64 = 3; /// Foonet coinbase maturity pub const FLOONET_COINBASE_MATURITY: u64 = 30; /// Testing cut through horizon in blocks pub const TESTING_CUT_THROUGH_HORIZON: u32 = 70; /// Testing state sync threshold in blocks pub const TESTING_STATE_SYNC_THRESHOLD: u32 = 20; /// Testing initial graph weight pub const TESTING_INITIAL_GRAPH_WEIGHT: u32 = 1; /// Testing initial block difficulty pub const TESTING_INITIAL_DIFFICULTY: u64 = 1; /// Testing max_block_weight (artifically low, just enough to support a few txs). pub const TESTING_MAX_BLOCK_WEIGHT: usize = 150; /// If a peer's last updated difficulty is 2 hours ago and its difficulty's lower than ours, /// we're sure this peer is a stuck node, and we will kick out such kind of stuck peers. pub const STUCK_PEER_KICK_TIME: i64 = 2 * 3600 * 1000; /// If a peer's last seen time is 2 weeks ago we will forget such kind of defunct peers. const PEER_EXPIRATION_DAYS: i64 = 7 * 2; /// Constant that expresses defunct peer timeout in seconds to be used in checks. pub const PEER_EXPIRATION_REMOVE_TIME: i64 = PEER_EXPIRATION_DAYS * 24 * 3600; /// Trigger compaction check on average every day for all nodes. /// Randomized per node - roll the dice on every block to decide. /// Will compact the txhashset to remove pruned data. /// Will also remove old blocks and associated data from the database. /// For a node configured as "archival_mode = true" only the txhashset will be compacted. pub const COMPACTION_CHECK: u64 = DAY_HEIGHT; pub const CURRENT_HEADER_VERSION: u16 = 6; #[cfg(target_family = "unix")] pub const FOUNDATION_JSON_SHA256: &str = "2613717d04128587b8c3fa24db873b2c4b33232cffe1849b4b5e1ff6d39cd12d"; #[cfg(target_family = "windows")] pub const FOUNDATION_JSON_SHA256: &str = "2613717d04128587b8c3fa24db873b2c4b33232cffe1849b4b5e1ff6d39cd12d"; /// Types of chain a server can run with, dictates the genesis block and /// and mining parameters used. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum ChainTypes { /// For CI testing AutomatedTesting, /// For User testing UserTesting, /// Protocol testing network Floonet, /// Main production network Mainnet, } impl ChainTypes { /// Short name representing the chain type ("floo", "main", etc.) pub fn shortname(&self) -> String { match *self { ChainTypes::AutomatedTesting => "auto".to_owned(), ChainTypes::UserTesting => "user".to_owned(), ChainTypes::Floonet => "floo".to_owned(), ChainTypes::Mainnet => "main".to_owned(), } } } impl Default for ChainTypes { fn default() -> ChainTypes { ChainTypes::Mainnet } } /// PoW test mining and verifier context #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum PoWContextTypes { /// Classic Cuckoo Cuckoo, /// ASIC-friendly Cuckatoo Cuckatoo, /// ASIC-resistant Cuckaroo Cuckaroo, } lazy_static! { /// The mining parameter mode pub static ref CHAIN_TYPE: RwLock<ChainTypes> = RwLock::new(ChainTypes::Mainnet); /// PoW context type to instantiate pub static ref POW_CONTEXT_TYPE: RwLock<PoWContextTypes> = RwLock::new(PoWContextTypes::Cuckoo); /// The policy parameters pub static ref POLICY_CONFIG : RwLock<PolicyConfig> = RwLock::new(PolicyConfig::default()); /// The path to the file that contains the foundation pub static ref FOUNDATION_FILE : RwLock<Option<String>> = RwLock::new(None); /// Store the current epic version being executed pub static ref EPIC_VERSION : RwLock<Option<Version>> = RwLock::new(None); /// Store the timeout for the header sync pub static ref HEADER_SYNC_TIMEOUT : RwLock<i64> = RwLock::new(10); /// Store the median timestamp from all peers pub static ref NETWORK_ADJUSTED_TIME : RwLock<i64> = RwLock::new(Utc::now().timestamp()); } /// Get the current median offset for Network-adjusted pub fn get_network_adjusted_time() -> i64 { let network_adjusted_time = NETWORK_ADJUSTED_TIME.read(); network_adjusted_time.clone() } /// Set the current median offset for Network-adjusted pub fn set_network_adjusted_time(timestamp: i64) { let mut network_adjusted_time = NETWORK_ADJUSTED_TIME.write(); *network_adjusted_time = if timestamp <= 0 { Utc::now().timestamp() } else { timestamp } } /// Get the current Timeout without the verification of the existence of more headers to be synced, /// after all header were processed pub fn get_header_sync_timeout() -> i64 { let header_sync_timeout = HEADER_SYNC_TIMEOUT.read(); header_sync_timeout.clone() } /// Set the current Timeout without the verification of the existence of more headers to be synced, /// after all header were processed pub fn set_header_sync_timeout(timeout: i64) { let mut header_sync_timeout = HEADER_SYNC_TIMEOUT.write(); *header_sync_timeout = if timeout <= 0 { 10 } else { timeout } } /// Set the version of the current epic executable pub fn set_epic_version(version_major: String, version_minor: String) { let mut epic_version = EPIC_VERSION.write(); let major_int: u32 = version_major.parse().expect("The current version of the epic node in the Cargo.toml is not valid! The major release value should be an integer"); let minor_int: u32 = version_minor.parse().expect("The current version of the epic node in the Cargo.toml is not valid! The minor release value should be an integer"); *epic_version = Some(Version::new(major_int, minor_int)); } /// Get the version of the current epic executable pub fn get_epic_version() -> Option<Version> { let epic_version = EPIC_VERSION.read(); epic_version.clone() } /// Set the path to the foundation.json file (file with the foundation wallet outputs/kernels) pub fn set_foundation_path(path: String) { let mut foundation_path = FOUNDATION_FILE.write(); let path_str = use_alternative_path(path); *foundation_path = Some(path_str); } /// Check if the foundation.json exists in the directory appointed by the .toml file, if not, /// use the alternative path ../../debian/foundation.json relative to the folder where the executable is in. pub fn use_alternative_path(path_str: String) -> String { let check_path = Path::new(&path_str); if !check_path.exists() { let mut p = env::current_exe().expect("Failed to get the executable's directory and no path to the foundation.json was provided!"); //removing the file from the path and going back 2 directories for _ in 0..3 { p.pop(); } p.push("debian"); p.push("foundation.json"); warn!( "The file `{}` was not found! Will try to use the alternative file `{}`!", check_path.display(), p.display() ); p.to_str().expect("Failed to get the executable's directory and no path to the foundation.json was provided!").to_owned() } else { path_str } } /// Get the current path to the foundation.json file (file with the foundation wallet outputs/kernels) pub fn get_foundation_path() -> Option<String> { let foundation_path = FOUNDATION_FILE.read(); foundation_path.clone() } /// Set the policy configuration that will be used by the blockchain pub fn set_policy_config(policy: PolicyConfig) { let mut policy_config = POLICY_CONFIG.write(); *policy_config = policy; } pub fn add_allowed_policy(height: u64, value: u64) { let mut policy_config = POLICY_CONFIG.write(); policy_config .allowed_policies .push(AllowPolicy { height, value }); } pub fn get_allowed_policies() -> Vec<AllowPolicy> { let policy_config = POLICY_CONFIG.read(); policy_config.allowed_policies.clone() } pub fn get_emitted_policy(height: u64) -> u8 { let policy_config = POLICY_CONFIG.read(); if (height <= consensus::BLOCK_ERA_1) { 0 } else if (height <= consensus::BLOCK_ERA_2) { 1 } else if (height <= consensus::BLOCK_ERA_3) { 2 } else if (height <= consensus::BLOCK_ERA_4) { 3 } else if (height <= consensus::BLOCK_ERA_5) { 4 } else { 5 } } pub fn get_policies(index: u8) -> Option<Policy> { let policy_config = POLICY_CONFIG.read(); policy_config .policies .get(index as usize) .map(|x| x.clone()) } /// Get the policy configuration that is being used by the blockchain pub fn get_policy_config() -> PolicyConfig { let policy_config = POLICY_CONFIG.read(); policy_config.clone() } /// Set the mining mode pub fn set_mining_mode(mode: ChainTypes) { let mut param_ref = CHAIN_TYPE.write(); *param_ref = mode; } /// Return either a cuckoo context or a cuckatoo context /// Single change point pub fn create_pow_context<T>( _height: u64, edge_bits: u8, proof_size: usize, max_sols: u32, ) -> Result<Box<dyn PoWContext<T>>, pow::Error> where T: EdgeType + 'static, { let chain_type = CHAIN_TYPE.read().clone(); match chain_type { // Mainnet has Cuckaroo29 for AR and Cuckatoo30+ for AF ChainTypes::Mainnet => new_cuckatoo_ctx(edge_bits, proof_size, max_sols), //ChainTypes::Mainnet => new_cuckaroo_ctx(edge_bits, proof_size), // Same for Floonet ChainTypes::Floonet => new_cuckatoo_ctx(edge_bits, proof_size, max_sols), //ChainTypes::Floonet => new_cuckaroo_ctx(edge_bits, proof_size), // Everything else is Cuckatoo only _ => new_cuckatoo_ctx(edge_bits, proof_size, max_sols), } } /// The minimum acceptable edge_bits pub fn min_edge_bits() -> u8 { let param_ref = CHAIN_TYPE.read(); match *param_ref { ChainTypes::AutomatedTesting => AUTOMATED_TESTING_MIN_EDGE_BITS, ChainTypes::UserTesting => USER_TESTING_MIN_EDGE_BITS, _ => DEFAULT_MIN_EDGE_BITS, } } /// Reference edge_bits used to compute factor on higher Cuck(at)oo graph sizes, /// while the min_edge_bits can be changed on a soft fork, changing /// base_edge_bits is a hard fork. pub fn base_edge_bits() -> u8 { let param_ref = CHAIN_TYPE.read(); match *param_ref { ChainTypes::AutomatedTesting => AUTOMATED_TESTING_MIN_EDGE_BITS, ChainTypes::UserTesting => USER_TESTING_MIN_EDGE_BITS, _ => BASE_EDGE_BITS, } } /// The proofsize pub fn proofsize() -> usize { let param_ref = CHAIN_TYPE.read(); match *param_ref { ChainTypes::AutomatedTesting => AUTOMATED_TESTING_PROOF_SIZE, ChainTypes::UserTesting => USER_TESTING_PROOF_SIZE, _ => PROOFSIZE, } } /// Coinbase maturity for coinbases to be spent pub fn coinbase_maturity() -> u64 { let param_ref = CHAIN_TYPE.read(); match *param_ref { ChainTypes::AutomatedTesting => AUTOMATED_TESTING_COINBASE_MATURITY, ChainTypes::UserTesting => USER_TESTING_COINBASE_MATURITY, ChainTypes::Floonet => FLOONET_COINBASE_MATURITY, _ => COINBASE_MATURITY, } } /// Initial mining difficulty pub fn initial_block_difficulty() -> u64 { let param_ref = CHAIN_TYPE.read(); match *param_ref { ChainTypes::AutomatedTesting => TESTING_INITIAL_DIFFICULTY, ChainTypes::UserTesting => TESTING_INITIAL_DIFFICULTY, ChainTypes::Floonet => INITIAL_DIFFICULTY, ChainTypes::Mainnet => INITIAL_DIFFICULTY, } } /// Initial mining secondary scale pub fn initial_graph_weight() -> u32 { let param_ref = CHAIN_TYPE.read(); match *param_ref { ChainTypes::AutomatedTesting => TESTING_INITIAL_GRAPH_WEIGHT, ChainTypes::UserTesting => TESTING_INITIAL_GRAPH_WEIGHT, ChainTypes::Floonet => graph_weight(0, SECOND_POW_EDGE_BITS) as u32, ChainTypes::Mainnet => graph_weight(0, SECOND_POW_EDGE_BITS) as u32, } } /// Maximum allowed block weight. pub fn max_block_weight() -> usize { let param_ref = CHAIN_TYPE.read(); match *param_ref { ChainTypes::AutomatedTesting => TESTING_MAX_BLOCK_WEIGHT, ChainTypes::UserTesting => TESTING_MAX_BLOCK_WEIGHT, ChainTypes::Floonet => MAX_BLOCK_WEIGHT, ChainTypes::Mainnet => MAX_BLOCK_WEIGHT, } } /// Horizon at which we can cut-through and do full local pruning pub fn cut_through_horizon() -> u32 { let param_ref = CHAIN_TYPE.read(); match *param_ref { ChainTypes::AutomatedTesting => TESTING_CUT_THROUGH_HORIZON, ChainTypes::UserTesting => TESTING_CUT_THROUGH_HORIZON, _ => CUT_THROUGH_HORIZON, } } /// Threshold at which we can request a txhashset (and full blocks from) pub fn state_sync_threshold() -> u32 { let param_ref = CHAIN_TYPE.read(); match *param_ref { ChainTypes::AutomatedTesting => TESTING_STATE_SYNC_THRESHOLD, ChainTypes::UserTesting => TESTING_STATE_SYNC_THRESHOLD, _ => STATE_SYNC_THRESHOLD, } } /// Are we in automated testing mode? pub fn is_automated_testing_mode() -> bool { let param_ref = CHAIN_TYPE.read(); ChainTypes::AutomatedTesting == *param_ref } /// Are we in user testing mode? pub fn is_user_testing_mode() -> bool { let param_ref = CHAIN_TYPE.read(); ChainTypes::UserTesting == *param_ref } /// Are we in production mode? /// Production defined as a live public network, testnet[n] or mainnet. pub fn is_production_mode() -> bool { let param_ref = CHAIN_TYPE.read(); ChainTypes::Floonet == *param_ref || ChainTypes::Mainnet == *param_ref } /// Are we in floonet? /// Note: We do not have a corresponding is_mainnet() as we want any tests to be as close /// as possible to "mainnet" configuration as possible. /// We want to avoid missing any mainnet only code paths. pub fn is_floonet() -> bool { let param_ref = CHAIN_TYPE.read(); ChainTypes::Floonet == *param_ref } /// Are we for real? pub fn is_mainnet() -> bool { let param_ref = CHAIN_TYPE.read(); ChainTypes::Mainnet == *param_ref } /// Helper function to get a nonce known to create a valid POW on /// the genesis block, to prevent it taking ages. Should be fine for now /// as the genesis block POW solution turns out to be the same for every new /// block chain at the moment pub fn get_genesis_nonce() -> u64 { let param_ref = CHAIN_TYPE.read(); match *param_ref { // won't make a difference ChainTypes::AutomatedTesting => 0, // Magic nonce for current genesis block at cuckatoo15 ChainTypes::UserTesting => 27944, // Placeholder, obviously not the right value ChainTypes::Floonet => 0, // Placeholder, obviously not the right value ChainTypes::Mainnet => 0, } } /// Short name representing the current chain type ("floo", "main", etc.) pub fn chain_shortname() -> String { let param_ref = CHAIN_TYPE.read(); param_ref.shortname() } /// Converts an iterator of block difficulty data to more a more manageable /// vector and pads if needed (which will) only be needed for the first few /// blocks after genesis pub fn difficulty_data_to_vector<T>(cursor: T, needed_block_count: u64) -> Vec<HeaderInfo> where T: IntoIterator<Item = HeaderInfo>, { // Convert iterator to vector, so we can append to it if necessary let needed_block_count = needed_block_count as usize + 1; let mut last_n: Vec<HeaderInfo> = cursor.into_iter().take(needed_block_count).collect(); for i in 1..last_n.len() { last_n[i].timestamp = last_n[i - 1] .timestamp .saturating_sub(last_n[i - 1].prev_timespan); } // Only needed just after blockchain launch... basically ensures there's // always enough data by simulating perfectly timed pre-genesis // blocks at the genesis difficulty as needed. let n = last_n.len(); if needed_block_count > n { let last_ts_delta = if n > 1 { last_n[0].timestamp - last_n[1].timestamp } else { BLOCK_TIME_SEC }; let last_diff = last_n[0].difficulty.clone(); // fill in simulated blocks with values from the previous real block let mut last_ts = last_n.last().unwrap().timestamp; for _ in n..needed_block_count { last_ts = last_ts.saturating_sub(last_ts_delta); last_n.push(HeaderInfo::from_ts_diff(last_ts, last_diff.clone())); } } last_n.reverse(); last_n } pub fn ts_data_to_vector<T>(cursor: T, needed_block_count: u64) -> Vec<HeaderInfo> where T: IntoIterator<Item = HeaderInfo>, { // Convert iterator to vector, so we can append to it if necessary let needed_block_count = needed_block_count as usize + 1; let mut last_n: Vec<HeaderInfo> = cursor.into_iter().take(needed_block_count).collect(); for i in 1..last_n.len() { last_n[i].timestamp = last_n[i - 1] .timestamp .saturating_sub(last_n[i - 1].prev_timespan); } // Only needed just after blockchain launch... basically ensures there's // always enough data by simulating perfectly timed pre-genesis // blocks at the genesis difficulty as needed. let n = last_n.len(); if needed_block_count > n { let last_ts_delta = if n > 1 { last_n[0].timestamp - last_n[1].timestamp } else { BLOCK_TIME_SEC }; let last_diff = last_n[0].difficulty.clone(); // fill in simulated blocks with values from the previous real block let mut last_ts = last_n.last().unwrap().timestamp; for _ in n..needed_block_count { last_ts = last_ts.saturating_sub(last_ts_delta); last_n.push(HeaderInfo::from_ts_diff(last_ts, last_diff.clone())); } } last_n } /// Strcut that store the major and minor release versions #[derive(Debug, Clone)] pub struct Version { /// Store the major release number of an application pub version_major: u32, /// Store the minor release number of an application pub version_minor: u32, } impl Version { /// Create a new Version Struct pub fn new(version_major: u32, version_minor: u32) -> Version { Version { version_major, version_minor, } } } pub fn get_file_sha256(path: &str) -> String { let mut file = File::open(path).expect( format!( "Error trying to read the foundation.json. Couldn't find/open the file {}!", path ) .as_str(), ); let mut sha256 = Sha256::new(); std::io::copy(&mut file, &mut sha256).expect( format!( "Error trying to read the foundation.json. Couldn't find/open the file {}!", path ) .as_str(), ); let hash = sha256.result(); format!("{:x}", hash) }
32.626246
168
0.736979
1427fd7fd085e13e3193e1e92321663b961a21ed
2,866
//! Sudokuboard controller. //This code is extended from piston crate tutorial //for sudoku game. //https://github.com/PistonDevelopers/Piston-Tutorials // This work is released under the "MIT License". // Please see the file LICENSE in the source // distribution of this software for license terms. use piston::input::GenericEvent; use crate::sudokuboard::Matrix9; /// Handles events for Sudoku game. pub struct SudokuboardController { /// Stores the sudokuboard state. pub sudokuboard: Matrix9, /// Selected cell. pub selected_cell: Option<[usize; 2]>, /// Stores last mouse cursor position. cursor_pos: [f64; 2], } impl SudokuboardController { /// Creates a new sudokuboard controller. pub fn new(sudokuboard: Matrix9) -> SudokuboardController { SudokuboardController { sudokuboard: sudokuboard, selected_cell: None, cursor_pos: [0.0; 2], } } /// Handles events. pub fn event<E: GenericEvent>(&mut self, pos: [f64; 2], size: f64, e: &E) { use piston::input::{Button, Key, MouseButton}; if let Some(pos) = e.mouse_cursor_args() { self.cursor_pos = pos; } if let Some(Button::Mouse(MouseButton::Left)) = e.press_args() { // Find coordinates relative to upper left corner. let x = self.cursor_pos[0] - pos[0]; let y = self.cursor_pos[1] - pos[1]; // Check that coordinates are inside board boundaries. if x >= 0.0 && x < size && y >= 0.0 && y < size { // Compute the cell position. let cell_x = (x / size * 9.0) as usize; let cell_y = (y / size * 9.0) as usize; self.selected_cell = Some([cell_x, cell_y]); } } if let Some(Button::Keyboard(key)) = e.press_args() { if let Some(ind) = self.selected_cell { // Set cell value. match key { Key::D1 => self.sudokuboard.set(ind, 1) , Key::D2 => self.sudokuboard.set(ind, 2), Key::D3 => self.sudokuboard.set(ind, 3), Key::D4 => self.sudokuboard.set(ind, 4), Key::D5 => self.sudokuboard.set(ind, 5), Key::D6 => self.sudokuboard.set(ind, 6), Key::D7 => self.sudokuboard.set(ind, 7), Key::D8 => self.sudokuboard.set(ind, 8), Key::D9 => self.sudokuboard.set(ind, 9), Key::S => self.sudokuboard.print_solution(), Key::N => self.sudokuboard.generate(), Key::B => self.sudokuboard.backspace(ind), _ => {} } } } } }
38.72973
80
0.523726
75efadc663d7a4612defd626a64ad6fc9ec73f47
4,056
use tract_core::internal::*; #[derive(Debug, Clone, new)] pub struct Max { t: DatumType, t_idx: DatumType, keep_dims: bool, } pub fn max(pb: &crate::tfpb::node_def::NodeDef) -> TractResult<Box<Op>> { let t = pb.get_attr_datum_type("T")?; let t_idx = pb.get_attr_datum_type("Tidx")?; let keep_dims = pb.get_attr_bool("keep_dims")?; Ok(Box::new(Max::new(t, t_idx, keep_dims))) } impl Max { fn eval_t<T>( &self, input: Arc<Tensor>, full_output_shape: TVec<usize>, axes: TVec<usize>, ) -> TractResult<TVec<Arc<Tensor>>> where T: Copy + Datum + PartialOrd + num_traits::Bounded, { use ndarray::*; let input = input.to_array_view::<T>()?; let mut result = Array::from_shape_fn(&*full_output_shape, |coords| { let slice_spec: Vec<SliceOrIndex> = coords .slice() .iter() .enumerate() .map(|(ax, &d)| if axes.contains(&ax) { (..).into() } else { d.into() }) .collect(); let slice_info = SliceInfo::<_, IxDyn>::new(&slice_spec).unwrap(); let slice = input.slice(slice_info.as_ref()); slice.iter().fold(T::min_value(), |a, &b| if a < b { b } else { a }) }); if !self.keep_dims { for ax in (0..full_output_shape.len()).rev() { if axes.contains(&ax) { result = result.index_axis_move(Axis(ax), 0); } } } Ok(tvec!(result.into_arc_tensor())) } } impl Op for Max { fn name(&self) -> Cow<str> { "tf.Max".into() } } impl StatelessOp for Max { fn eval(&self, mut inputs: TVec<Arc<Tensor>>) -> TractResult<TVec<Arc<Tensor>>> { let (input, axes) = args_2!(inputs); let axes: TVec<usize> = axes .cast_to::<i32>()? .as_slice::<i32>()? .iter() .map(|&ax| if ax >= 0 { ax as usize } else { ax as usize + input.shape().len() }) .collect(); let full_output_shape: TVec<usize> = input .shape() .iter() .enumerate() .map(|(ax, &d)| if axes.contains(&ax) { 1 } else { d }) .collect(); dispatch_numbers!(Self::eval_t(self.t)(self, input, full_output_shape, axes)) } } impl InferenceRulesOp for Max { fn rules<'r, 'p: 'r, 's: 'r>( &'s self, s: &mut Solver<'r>, inputs: &'p [TensorProxy], outputs: &'p [TensorProxy], ) -> InferenceResult { check_input_arity(&inputs, 2)?; check_output_arity(&outputs, 1)?; s.equals(&outputs[0].datum_type, &inputs[0].datum_type)?; s.equals(&inputs[1].rank, 1)?; if self.keep_dims { s.equals(&inputs[0].rank, &outputs[0].rank)?; } else { s.equals( inputs[0].rank.bex().to_dim(), inputs[1].shape[0].bex() + outputs[0].rank.bex().to_dim(), )?; } s.given_3( &inputs[0].rank, &outputs[0].rank, &inputs[1].value, move |s, irank, orank, axes| { let axes: TVec<usize> = axes .cast_to::<i32>()? .as_slice::<i32>()? .iter() .map(|&ax| if ax > 0 { ax } else { ax + irank } as usize) .collect(); let mut od = 0; for id in 0..(irank as usize) { if axes.contains(&id) { if self.keep_dims { s.equals(&outputs[0].shape[od], 1.to_dim())?; od += 1; } } else { if od < orank as usize { s.equals(&outputs[0].shape[od], &inputs[0].shape[id])?; } } } Ok(()) }, )?; Ok(()) } }
32.448
93
0.45217
0abbea3db26e159c054c46016709f1dc69dd0b8d
225
#![feature(test)] extern crate test; use morgan::create_keys::GenKeys; use test::Bencher; #[bench] fn bench_gen_keys(b: &mut Bencher) { let mut rnd = GenKeys::new([0u8; 32]); b.iter(|| rnd.gen_n_keypairs(1000)); }
17.307692
42
0.662222
758956006762e04c60ebc280ccaf225a3ed53914
689
use std::env::var; use anyhow::Result; use grambot::{methods::SendMessage, Bot}; #[tokio::main(flavor = "current_thread")] async fn main() -> Result<()> { let bot = Bot::new(var("GRAMBOT_EXAMPLE_TOKEN")?); let chat_id = var("GRAMBOT_EXAMPLE_CHATID")?.parse::<i64>()?; let mut request = SendMessage::new(chat_id, "Hello, world!"); request.disable_notification = Some(true); let message = bot.send(request).await?; println!("{message:#?}"); let request = SendMessage::builder() .disable_notification(true) .build(chat_id, "Hello again, world!"); let message = bot.send(request).await?; println!("{:#?}", message.text()); Ok(()) }
28.708333
65
0.628447
098ed6fc5d9429dfc71dc9c7daad5d5b9425713c
5,130
use std::collections::HashMap; use std::io; use std::net::SocketAddr; use anyhow::anyhow; use async_trait::async_trait; use byteorder::{BigEndian, ByteOrder}; use bytes::{BufMut, BytesMut}; use futures::TryFutureExt; use sha2::{Digest, Sha224}; use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; use crate::{ proxy::*, session::{DatagramSource, Network, Session, SocksAddr, SocksAddrWireType}, }; struct Datagram { stream: AnyStream, source: DatagramSource, } impl Datagram { pub fn new(stream: AnyStream, source: DatagramSource) -> Self { Self { stream, source } } } impl InboundDatagram for Datagram { fn split( self: Box<Self>, ) -> ( Box<dyn InboundDatagramRecvHalf>, Box<dyn InboundDatagramSendHalf>, ) { let (r, s) = tokio::io::split(self.stream); ( Box::new(DatagramRecvHalf(r, self.source)), Box::new(DatagramSendHalf(s)), ) } fn into_std(self: Box<Self>) -> io::Result<std::net::UdpSocket> { Err(io::Error::new(io::ErrorKind::Other, "stream transport")) } } struct DatagramRecvHalf<T>(T, DatagramSource); #[async_trait] impl<T> InboundDatagramRecvHalf for DatagramRecvHalf<T> where T: AsyncRead + Send + Sync + Unpin, { async fn recv_from( &mut self, buf: &mut [u8], ) -> ProxyResult<(usize, DatagramSource, SocksAddr)> { let dst_addr = SocksAddr::read_from(&mut self.0, SocksAddrWireType::PortLast) .map_err(|e| ProxyError::DatagramFatal(e.into())) .await?; let mut buf2 = BytesMut::new(); buf2.resize(2, 0); let _ = self .0 .read_exact(&mut buf2) .map_err(|e| ProxyError::DatagramFatal(e.into())) .await?; let payload_len = BigEndian::read_u16(&buf2) as usize; if buf.len() < payload_len { return Err(ProxyError::DatagramFatal(anyhow!("Small buffer"))); } let _ = self .0 .read_exact(&mut buf2) .map_err(|e| ProxyError::DatagramFatal(e.into())) .await?; if &buf2[..2] != b"\r\n" { return Err(ProxyError::DatagramFatal(anyhow!("Expeced CRLF"))); } buf2.resize(payload_len, 0); let _ = self .0 .read_exact(&mut buf2) .map_err(|e| ProxyError::DatagramFatal(e.into())) .await?; buf[..payload_len].copy_from_slice(&buf2[..payload_len]); Ok((payload_len, self.1, dst_addr)) } } struct DatagramSendHalf<T>(T); #[async_trait] impl<T> InboundDatagramSendHalf for DatagramSendHalf<T> where T: AsyncWrite + Send + Sync + Unpin, { async fn send_to( &mut self, buf: &[u8], src_addr: &SocksAddr, _dst_addr: &SocketAddr, ) -> io::Result<usize> { let mut data = BytesMut::new(); src_addr.write_buf(&mut data, SocksAddrWireType::PortLast); data.put_u16(buf.len() as u16); data.put_slice(b"\r\n"); data.put_slice(buf); self.0.write_all(&data).map_ok(|_| buf.len()).await } async fn close(&mut self) -> io::Result<()> { self.0.shutdown().await } } pub struct Handler { keys: HashMap<Vec<u8>, ()>, } impl Handler { pub fn new(passwords: Vec<String>) -> Self { let mut keys = HashMap::new(); for pass in passwords { let key = Sha224::digest(pass.as_bytes()); let key = hex::encode(&key[..]); keys.insert(key.as_bytes().to_vec(), ()); } Handler { keys } } } #[async_trait] impl TcpInboundHandler for Handler { async fn handle<'a>( &'a self, mut sess: Session, mut stream: AnyStream, ) -> std::io::Result<AnyInboundTransport> { let mut buf = BytesMut::new(); // read key buf.resize(56, 0); stream.read_exact(&mut buf).await?; if !self.keys.contains_key(&buf[..]) { return Err(io::Error::new(io::ErrorKind::Other, "invalid key")); } // read crlf buf.resize(2, 0); stream.read_exact(&mut buf).await?; // read cmd buf.resize(1, 0); stream.read_exact(&mut buf).await?; let cmd = buf[0]; // read addr let dst_addr = SocksAddr::read_from(&mut stream, SocksAddrWireType::PortLast).await?; sess.destination = dst_addr; // read crlf buf.resize(2, 0); stream.read_exact(&mut buf).await?; match cmd { // tcp 0x01 => Ok(InboundTransport::Stream(stream, sess)), // udp 0x03 => { sess.network = Network::Udp; Ok(InboundTransport::Datagram( Box::new(Datagram::new( stream, DatagramSource::new(sess.source, sess.stream_id), )), Some(sess), )) } _ => Err(io::Error::new(io::ErrorKind::Other, "invalid command")), } } }
28.659218
93
0.549318
1ea35a00b322201a87b8e5da6659fff52101ff60
584
//! Module that contains the json types binding used to communicate with a cosmos based blockchain node. use serde::{Deserialize, Serialize}; /// NodeInfoResponse contains the response of the LCD request `/node_info`. #[derive(Clone, Serialize, Deserialize)] pub struct NodeInfoResponse { pub node_info: NodeInfo, } /// NodeInfo contains the information of a cosmos based blockchain node. #[derive(Clone, Serialize, Deserialize)] pub struct NodeInfo { pub id: String, pub listen_addr: String, pub network: String, pub version: String, pub moniker: String, }
30.736842
104
0.739726
64fd4ba0cb8da6b390e4e8ee4c6487312e651882
10,103
#![allow(clippy::many_single_char_names)] #![allow(clippy::cast_ptr_alignment)] // Safe to cast without alignment checks as the loads and stores do not require alignment. #[cfg(target_arch = "x86")] use std::arch::x86::*; #[cfg(target_arch = "x86_64")] use std::arch::x86_64::*; /// Process a block with the SHA-256 algorithm. /// Based on https://github.com/noloader/SHA-Intrinsics/blob/master/sha256-x86.c #[inline(always)] pub unsafe fn compress256(state: &mut [u32; 8], blocks: &[&[u8]]) { assert_eq!(blocks.len() % 2, 0); let mut state0: __m128i; let mut state1: __m128i; let mut msg: __m128i; let mut tmp: __m128i; let mut msg0: __m128i; let mut msg1: __m128i; let mut msg2: __m128i; let mut msg3: __m128i; let mut abef_save: __m128i; let mut cdgh_save: __m128i; #[allow(non_snake_case)] let MASK: __m128i = _mm_set_epi64x( 0x0c0d_0e0f_0809_0a0bu64 as i64, 0x0405_0607_0001_0203u64 as i64, ); // Load initial values tmp = _mm_loadu_si128(state.as_ptr().add(0) as *const __m128i); state1 = _mm_loadu_si128(state.as_ptr().add(4) as *const __m128i); tmp = _mm_shuffle_epi32(tmp, 0xB1); // CDAB state1 = _mm_shuffle_epi32(state1, 0x1B); // EFGH state0 = _mm_alignr_epi8(tmp, state1, 8); // ABEF state1 = _mm_blend_epi16(state1, tmp, 0xF0); // CDGH for i in (0..blocks.len()).step_by(2) { // Save current state abef_save = state0; cdgh_save = state1; // Rounds 0-3 msg = _mm_loadu_si128(blocks[i].as_ptr().add(0) as *const __m128i); msg0 = _mm_shuffle_epi8(msg, MASK); msg = _mm_add_epi32( msg0, _mm_set_epi64x(0xE9B5DBA5B5C0FBCFu64 as i64, 0x71374491428A2F98u64 as i64), ); state1 = _mm_sha256rnds2_epu32(state1, state0, msg); msg = _mm_shuffle_epi32(msg, 0x0E); state0 = _mm_sha256rnds2_epu32(state0, state1, msg); // Rounds 4-7 msg1 = _mm_loadu_si128(blocks[i].as_ptr().add(16) as *const __m128i); msg1 = _mm_shuffle_epi8(msg1, MASK); msg = _mm_add_epi32( msg1, _mm_set_epi64x(0xAB1C5ED5923F82A4u64 as i64, 0x59F111F13956C25Bu64 as i64), ); state1 = _mm_sha256rnds2_epu32(state1, state0, msg); msg = _mm_shuffle_epi32(msg, 0x0E); state0 = _mm_sha256rnds2_epu32(state0, state1, msg); msg0 = _mm_sha256msg1_epu32(msg0, msg1); // Rounds 8-11 msg2 = _mm_loadu_si128(blocks[i + 1].as_ptr().add(0) as *const __m128i); msg2 = _mm_shuffle_epi8(msg2, MASK); msg = _mm_add_epi32( msg2, _mm_set_epi64x(0x550C7DC3243185BEu64 as i64, 0x12835B01D807AA98u64 as i64), ); state1 = _mm_sha256rnds2_epu32(state1, state0, msg); msg = _mm_shuffle_epi32(msg, 0x0E); state0 = _mm_sha256rnds2_epu32(state0, state1, msg); msg1 = _mm_sha256msg1_epu32(msg1, msg2); // Rounds 12-15 msg3 = _mm_loadu_si128(blocks[i + 1].as_ptr().add(16) as *const __m128i); msg3 = _mm_shuffle_epi8(msg3, MASK); msg = _mm_add_epi32( msg3, _mm_set_epi64x(0xC19BF1749BDC06A7u64 as i64, 0x80DEB1FE72BE5D74u64 as i64), ); state1 = _mm_sha256rnds2_epu32(state1, state0, msg); tmp = _mm_alignr_epi8(msg3, msg2, 4); msg0 = _mm_add_epi32(msg0, tmp); msg0 = _mm_sha256msg2_epu32(msg0, msg3); msg = _mm_shuffle_epi32(msg, 0x0E); state0 = _mm_sha256rnds2_epu32(state0, state1, msg); msg2 = _mm_sha256msg1_epu32(msg2, msg3); // Rounds 16-19 msg = _mm_add_epi32( msg0, _mm_set_epi64x(0x240CA1CC0FC19DC6u64 as i64, 0xEFBE4786E49B69C1u64 as i64), ); state1 = _mm_sha256rnds2_epu32(state1, state0, msg); tmp = _mm_alignr_epi8(msg0, msg3, 4); msg1 = _mm_add_epi32(msg1, tmp); msg1 = _mm_sha256msg2_epu32(msg1, msg0); msg = _mm_shuffle_epi32(msg, 0x0E); state0 = _mm_sha256rnds2_epu32(state0, state1, msg); msg3 = _mm_sha256msg1_epu32(msg3, msg0); // Rounds 20-23 msg = _mm_add_epi32( msg1, _mm_set_epi64x(0x76F988DA5CB0A9DCu64 as i64, 0x4A7484AA2DE92C6Fu64 as i64), ); state1 = _mm_sha256rnds2_epu32(state1, state0, msg); tmp = _mm_alignr_epi8(msg1, msg0, 4); msg2 = _mm_add_epi32(msg2, tmp); msg2 = _mm_sha256msg2_epu32(msg2, msg1); msg = _mm_shuffle_epi32(msg, 0x0E); state0 = _mm_sha256rnds2_epu32(state0, state1, msg); msg0 = _mm_sha256msg1_epu32(msg0, msg1); // Rounds 24-27 msg = _mm_add_epi32( msg2, _mm_set_epi64x(0xBF597FC7B00327C8u64 as i64, 0xA831C66D983E5152u64 as i64), ); state1 = _mm_sha256rnds2_epu32(state1, state0, msg); tmp = _mm_alignr_epi8(msg2, msg1, 4); msg3 = _mm_add_epi32(msg3, tmp); msg3 = _mm_sha256msg2_epu32(msg3, msg2); msg = _mm_shuffle_epi32(msg, 0x0E); state0 = _mm_sha256rnds2_epu32(state0, state1, msg); msg1 = _mm_sha256msg1_epu32(msg1, msg2); // Rounds 28-31 msg = _mm_add_epi32( msg3, _mm_set_epi64x(0x1429296706CA6351u64 as i64, 0xD5A79147C6E00BF3u64 as i64), ); state1 = _mm_sha256rnds2_epu32(state1, state0, msg); tmp = _mm_alignr_epi8(msg3, msg2, 4); msg0 = _mm_add_epi32(msg0, tmp); msg0 = _mm_sha256msg2_epu32(msg0, msg3); msg = _mm_shuffle_epi32(msg, 0x0E); state0 = _mm_sha256rnds2_epu32(state0, state1, msg); msg2 = _mm_sha256msg1_epu32(msg2, msg3); // Rounds 32-35 msg = _mm_add_epi32( msg0, _mm_set_epi64x(0x53380D134D2C6DFCu64 as i64, 0x2E1B213827B70A85u64 as i64), ); state1 = _mm_sha256rnds2_epu32(state1, state0, msg); tmp = _mm_alignr_epi8(msg0, msg3, 4); msg1 = _mm_add_epi32(msg1, tmp); msg1 = _mm_sha256msg2_epu32(msg1, msg0); msg = _mm_shuffle_epi32(msg, 0x0E); state0 = _mm_sha256rnds2_epu32(state0, state1, msg); msg3 = _mm_sha256msg1_epu32(msg3, msg0); // Rounds 36-39 msg = _mm_add_epi32( msg1, _mm_set_epi64x(0x92722C8581C2C92Eu64 as i64, 0x766A0ABB650A7354u64 as i64), ); state1 = _mm_sha256rnds2_epu32(state1, state0, msg); tmp = _mm_alignr_epi8(msg1, msg0, 4); msg2 = _mm_add_epi32(msg2, tmp); msg2 = _mm_sha256msg2_epu32(msg2, msg1); msg = _mm_shuffle_epi32(msg, 0x0E); state0 = _mm_sha256rnds2_epu32(state0, state1, msg); msg0 = _mm_sha256msg1_epu32(msg0, msg1); // Rounds 40-43 msg = _mm_add_epi32( msg2, _mm_set_epi64x(0xC76C51A3C24B8B70u64 as i64, 0xA81A664BA2BFE8A1u64 as i64), ); state1 = _mm_sha256rnds2_epu32(state1, state0, msg); tmp = _mm_alignr_epi8(msg2, msg1, 4); msg3 = _mm_add_epi32(msg3, tmp); msg3 = _mm_sha256msg2_epu32(msg3, msg2); msg = _mm_shuffle_epi32(msg, 0x0E); state0 = _mm_sha256rnds2_epu32(state0, state1, msg); msg1 = _mm_sha256msg1_epu32(msg1, msg2); // Rounds 44-47 msg = _mm_add_epi32( msg3, _mm_set_epi64x(0x106AA070F40E3585u64 as i64, 0xD6990624D192E819u64 as i64), ); state1 = _mm_sha256rnds2_epu32(state1, state0, msg); tmp = _mm_alignr_epi8(msg3, msg2, 4); msg0 = _mm_add_epi32(msg0, tmp); msg0 = _mm_sha256msg2_epu32(msg0, msg3); msg = _mm_shuffle_epi32(msg, 0x0E); state0 = _mm_sha256rnds2_epu32(state0, state1, msg); msg2 = _mm_sha256msg1_epu32(msg2, msg3); // Rounds 48-51 msg = _mm_add_epi32( msg0, _mm_set_epi64x(0x34B0BCB52748774Cu64 as i64, 0x1E376C0819A4C116u64 as i64), ); state1 = _mm_sha256rnds2_epu32(state1, state0, msg); tmp = _mm_alignr_epi8(msg0, msg3, 4); msg1 = _mm_add_epi32(msg1, tmp); msg1 = _mm_sha256msg2_epu32(msg1, msg0); msg = _mm_shuffle_epi32(msg, 0x0E); state0 = _mm_sha256rnds2_epu32(state0, state1, msg); msg3 = _mm_sha256msg1_epu32(msg3, msg0); // Rounds 52-55 msg = _mm_add_epi32( msg1, _mm_set_epi64x(0x682E6FF35B9CCA4Fu64 as i64, 0x4ED8AA4A391C0CB3u64 as i64), ); state1 = _mm_sha256rnds2_epu32(state1, state0, msg); tmp = _mm_alignr_epi8(msg1, msg0, 4); msg2 = _mm_add_epi32(msg2, tmp); msg2 = _mm_sha256msg2_epu32(msg2, msg1); msg = _mm_shuffle_epi32(msg, 0x0E); state0 = _mm_sha256rnds2_epu32(state0, state1, msg); // Rounds 56-59 msg = _mm_add_epi32( msg2, _mm_set_epi64x(0x8CC7020884C87814u64 as i64, 0x78A5636F748F82EEu64 as i64), ); state1 = _mm_sha256rnds2_epu32(state1, state0, msg); tmp = _mm_alignr_epi8(msg2, msg1, 4); msg3 = _mm_add_epi32(msg3, tmp); msg3 = _mm_sha256msg2_epu32(msg3, msg2); msg = _mm_shuffle_epi32(msg, 0x0E); state0 = _mm_sha256rnds2_epu32(state0, state1, msg); // Rounds 60-63 msg = _mm_add_epi32( msg3, _mm_set_epi64x(0xC67178F2BEF9A3F7u64 as i64, 0xA4506CEB90BEFFFAu64 as i64), ); state1 = _mm_sha256rnds2_epu32(state1, state0, msg); msg = _mm_shuffle_epi32(msg, 0x0E); state0 = _mm_sha256rnds2_epu32(state0, state1, msg); // Combine state state0 = _mm_add_epi32(state0, abef_save); state1 = _mm_add_epi32(state1, cdgh_save); } tmp = _mm_shuffle_epi32(state0, 0x1B); // FEBA state1 = _mm_shuffle_epi32(state1, 0xB1); // DCHG state0 = _mm_blend_epi16(tmp, state1, 0xF0); // DCBA state1 = _mm_alignr_epi8(state1, tmp, 8); // ABEF // Save state _mm_storeu_si128(state.as_ptr().add(0) as *mut __m128i, state0); _mm_storeu_si128(state.as_ptr().add(4) as *mut __m128i, state1); }
38.414449
128
0.625062
675f0635bbfcb1267c746ab781953a68010fcd70
28,834
//! The root of each single-threaded worker. use std::rc::Rc; use std::cell::{RefCell, RefMut}; use std::any::Any; use std::str::FromStr; use std::time::{Instant, Duration}; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::sync::Arc; use crate::communication::{Allocate, Data, Push, Pull}; use crate::communication::allocator::thread::{ThreadPusher, ThreadPuller}; use crate::scheduling::{Schedule, Scheduler, Activations}; use crate::progress::timestamp::{Refines}; use crate::progress::SubgraphBuilder; use crate::progress::operate::Operate; use crate::dataflow::scopes::Child; use crate::logging::TimelyLogger; /// Different ways in which timely's progress tracking can work. /// /// These options drive some buffering and accumulation that timely /// can do to try and trade volume of progress traffic against latency. /// By accumulating updates longer, a smaller total volume of messages /// are sent. /// /// The `ProgressMode::Demand` variant is the most robust, and least /// likely to lead to catastrophic performance. The `Eager` variant /// is useful for getting the smallest latencies on systems with few /// workers, but does risk saturating the system with progress messages /// and should be used with care, or not at all. /// /// If you are not certain which option to use, prefer `Demand`, and /// perhaps monitor the progress messages through timely's logging /// infrastructure to see if their volume is surprisingly high. #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum ProgressMode { /// Eagerly transmit all progress updates produced by a worker. /// /// Progress messages are transmitted without consideration for the /// possibility that they may unblock other workers. This can result /// in a substantial volume of messages that do not result in a /// change to the lower bound of outstanding work. Eager, /// Delay transmission of progress updates until any could advance /// the global frontier of timestamps. /// /// As timely executes, the progress messages inform each worker of /// the outstanding work remaining in the system. As workers work, /// they produce changes to this outstanding work. This option /// delays the communication of those changes until they might /// possibly cause a change in the lower bound of all outstanding /// work. /// /// The most common case this remedies is when one worker transmits /// messages to other workers, that worker holds a capability for the /// operator and timestamp. Other workers will receive messages, and /// with this option will not immediately acknowledge receiving the /// messages, because the held capability is strictly prior to what /// the messages can affect. Once the capability is released, the /// progress messages are unblocked and transmitted, in accumulated /// form. Demand, } impl Default for ProgressMode { fn default() -> ProgressMode { ProgressMode::Demand } } impl FromStr for ProgressMode { type Err = String; fn from_str(s: &str) -> Result<ProgressMode, String> { match s { "eager" => Ok(ProgressMode::Eager), "demand" => Ok(ProgressMode::Demand), _ => Err(format!("unknown progress mode: {}", s)), } } } /// Worker configuration. #[derive(Debug, Default, Clone)] pub struct Config { /// The progress mode to use. pub(crate) progress_mode: ProgressMode, /// A map from parameter name to typed parameter values. registry: HashMap<String, Arc<dyn Any + Send + Sync>>, } impl Config { /// Installs options into a [getopts_dep::Options] struct that correspond /// to the parameters in the configuration. /// /// It is the caller's responsibility to ensure that the installed options /// do not conflict with any other options that may exist in `opts`, or /// that may be installed into `opts` in the future. /// /// This method is only available if the `getopts` feature is enabled, which /// it is by default. #[cfg(feature = "getopts")] pub fn install_options(opts: &mut getopts_dep::Options) { opts.optopt("", "progress-mode", "progress tracking mode (eager or demand)", "MODE"); } /// Instantiates a configuration based upon the parsed options in `matches`. /// /// The `matches` object must have been constructed from a /// [getopts_dep::Options] which contained at least the options installed by /// [Self::install_options]. /// /// This method is only available if the `getopts` feature is enabled, which /// it is by default. #[cfg(feature = "getopts")] pub fn from_matches(matches: &getopts_dep::Matches) -> Result<Config, String> { let progress_mode = matches .opt_get_default("progress-mode", ProgressMode::Eager)?; Ok(Config::default().progress_mode(progress_mode)) } /// Sets the progress mode to `progress_mode`. pub fn progress_mode(mut self, progress_mode: ProgressMode) -> Self { self.progress_mode = progress_mode; self } /// Sets a typed configuration parameter for the given `key`. /// /// It is recommended to install a single configuration struct using a key /// that uniquely identifies your project, to avoid clashes. For example, /// differential dataflow registers a configuration struct under the key /// "differential". /// /// # Examples /// ```rust /// let mut config = timely::Config::process(3); /// config.worker.set("example".to_string(), 7u64); /// timely::execute(config, |worker| { /// use crate::timely::worker::AsWorker; /// assert_eq!(worker.config().get::<u64>("example"), Some(&7)); /// }).unwrap(); /// ``` pub fn set<T>(&mut self, key: String, val: T) -> &mut Self where T: Send + Sync + 'static, { self.registry.insert(key, Arc::new(val)); self } /// Gets the value for configured parameter `key`. /// /// Returns `None` if `key` has not previously been set with /// [Config::set], or if the specified `T` does not match the `T` /// from the call to `set`. /// /// # Examples /// ```rust /// let mut config = timely::Config::process(3); /// config.worker.set("example".to_string(), 7u64); /// timely::execute(config, |worker| { /// use crate::timely::worker::AsWorker; /// assert_eq!(worker.config().get::<u64>("example"), Some(&7)); /// }).unwrap(); /// ``` pub fn get<T: 'static>(&self, key: &str) -> Option<&T> { self.registry.get(key).and_then(|val| val.downcast_ref()) } } /// Methods provided by the root Worker. /// /// These methods are often proxied by child scopes, and this trait provides access. pub trait AsWorker : Scheduler { /// Returns the worker configuration parameters. fn config(&self) -> &Config; /// Index of the worker among its peers. fn index(&self) -> usize; /// Number of peer workers. fn peers(&self) -> usize; /// Allocates a new channel from a supplied identifier and address. /// /// The identifier is used to identify the underlying channel and route /// its data. It should be distinct from other identifiers passed used /// for allocation, but can otherwise be arbitrary. /// /// The address should specify a path to an operator that should be /// scheduled in response to the receipt of records on the channel. /// Most commonly, this would be the address of the *target* of the /// channel. fn allocate<T: Data>(&mut self, identifier: usize, address: &[usize]) -> (Vec<Box<dyn Push<Message<T>>>>, Box<dyn Pull<Message<T>>>); /// Constructs a pipeline channel from the worker to itself. /// /// By default this method uses the native channel allocation mechanism, but the expectation is /// that this behavior will be overriden to be more efficient. fn pipeline<T: 'static>(&mut self, identifier: usize, address: &[usize]) -> (ThreadPusher<Message<T>>, ThreadPuller<Message<T>>); /// Allocates a new worker-unique identifier. fn new_identifier(&mut self) -> usize; /// Provides access to named logging streams. fn log_register(&self) -> ::std::cell::RefMut<crate::logging_core::Registry<crate::logging::WorkerIdentifier>>; /// Provides access to the timely logging stream. fn logging(&self) -> Option<crate::logging::TimelyLogger> { self.log_register().get("timely") } } /// A `Worker` is the entry point to a timely dataflow computation. It wraps a `Allocate`, /// and has a list of dataflows that it manages. pub struct Worker<A: Allocate> { config: Config, timer: Instant, paths: Rc<RefCell<HashMap<usize, Vec<usize>>>>, allocator: Rc<RefCell<A>>, identifiers: Rc<RefCell<usize>>, // dataflows: Rc<RefCell<Vec<Wrapper>>>, dataflows: Rc<RefCell<HashMap<usize, Wrapper>>>, dataflow_counter: Rc<RefCell<usize>>, logging: Rc<RefCell<crate::logging_core::Registry<crate::logging::WorkerIdentifier>>>, activations: Rc<RefCell<Activations>>, active_dataflows: Vec<usize>, // Temporary storage for channel identifiers during dataflow construction. // These are then associated with a dataflow once constructed. temp_channel_ids: Rc<RefCell<Vec<usize>>>, } impl<A: Allocate> AsWorker for Worker<A> { fn config(&self) -> &Config { &self.config } fn index(&self) -> usize { self.allocator.borrow().index() } fn peers(&self) -> usize { self.allocator.borrow().peers() } fn allocate<D: Data>(&mut self, identifier: usize, address: &[usize]) -> (Vec<Box<dyn Push<Message<D>>>>, Box<dyn Pull<Message<D>>>) { if address.is_empty() { panic!("Unacceptable address: Length zero"); } let mut paths = self.paths.borrow_mut(); paths.insert(identifier, address.to_vec()); self.temp_channel_ids.borrow_mut().push(identifier); self.allocator.borrow_mut().allocate(identifier) } fn pipeline<T: 'static>(&mut self, identifier: usize, address: &[usize]) -> (ThreadPusher<Message<T>>, ThreadPuller<Message<T>>) { if address.is_empty() { panic!("Unacceptable address: Length zero"); } let mut paths = self.paths.borrow_mut(); paths.insert(identifier, address.to_vec()); self.temp_channel_ids.borrow_mut().push(identifier); self.allocator.borrow_mut().pipeline(identifier) } fn new_identifier(&mut self) -> usize { self.new_identifier() } fn log_register(&self) -> RefMut<crate::logging_core::Registry<crate::logging::WorkerIdentifier>> { self.log_register() } } impl<A: Allocate> Scheduler for Worker<A> { fn activations(&self) -> Rc<RefCell<Activations>> { self.activations.clone() } } impl<A: Allocate> Worker<A> { /// Allocates a new `Worker` bound to a channel allocator. pub fn new(config: Config, c: A) -> Worker<A> { let now = Instant::now(); let index = c.index(); Worker { config, timer: now, paths: Default::default(), allocator: Rc::new(RefCell::new(c)), identifiers: Default::default(), dataflows: Default::default(), dataflow_counter: Default::default(), logging: Rc::new(RefCell::new(crate::logging_core::Registry::new(now, index))), activations: Rc::new(RefCell::new(Activations::new(now))), active_dataflows: Default::default(), temp_channel_ids: Default::default(), } } /// Performs one step of the computation. /// /// A step gives each dataflow operator a chance to run, and is the /// main way to ensure that a computation proceeds. /// /// # Examples /// /// ``` /// timely::execute_from_args(::std::env::args(), |worker| { /// /// use timely::dataflow::operators::{ToStream, Inspect}; /// /// worker.dataflow::<usize,_,_>(|scope| { /// (0 .. 10) /// .to_stream(scope) /// .inspect(|x| println!("{:?}", x)); /// }); /// /// worker.step(); /// }); /// ``` pub fn step(&mut self) -> bool { self.step_or_park(Some(Duration::from_secs(0))) } /// Performs one step of the computation. /// /// A step gives each dataflow operator a chance to run, and is the /// main way to ensure that a computation proceeds. /// /// This method takes an optional timeout and may park the thread until /// there is work to perform or until this timeout expires. A value of /// `None` allows the worker to park indefinitely, whereas a value of /// `Some(Duration::new(0, 0))` will return without parking the thread. /// /// # Examples /// /// ``` /// timely::execute_from_args(::std::env::args(), |worker| { /// /// use std::time::Duration; /// use timely::dataflow::operators::{ToStream, Inspect}; /// /// worker.dataflow::<usize,_,_>(|scope| { /// (0 .. 10) /// .to_stream(scope) /// .inspect(|x| println!("{:?}", x)); /// }); /// /// worker.step_or_park(Some(Duration::from_secs(1))); /// }); /// ``` pub fn step_or_park(&mut self, duration: Option<Duration>) -> bool { { // Process channel events. Activate responders. let mut allocator = self.allocator.borrow_mut(); allocator.receive(); let events = allocator.events().clone(); let mut borrow = events.borrow_mut(); let paths = self.paths.borrow(); for (channel, _event) in borrow.drain(..) { // TODO: Pay more attent to `_event`. // Consider tracking whether a channel // in non-empty, and only activating // on the basis of non-empty channels. // TODO: This is a sloppy way to deal // with channels that may not be alloc'd. if let Some(path) = paths.get(&channel) { self.activations .borrow_mut() .activate(&path[..]); } } } // Organize activations. self.activations .borrow_mut() .advance(); // Consider parking only if we have no pending events, some dataflows, and a non-zero duration. let empty_for = self.activations.borrow().empty_for(); // Determine the minimum park duration, where `None` are an absence of a constraint. let delay = match (duration, empty_for) { (Some(x), Some(y)) => Some(std::cmp::min(x,y)), (x, y) => x.or(y), }; if delay != Some(Duration::new(0, 0)) { // Log parking and flush log. if let Some(l) = self.logging().as_mut() { l.log(crate::logging::ParkEvent::park(delay)); l.flush(); } self.allocator .borrow() .await_events(delay); // Log return from unpark. self.logging().as_mut().map(|l| l.log(crate::logging::ParkEvent::unpark())); } else { // Schedule active dataflows. let active_dataflows = &mut self.active_dataflows; self.activations .borrow_mut() .for_extensions(&[], |index| active_dataflows.push(index)); let mut dataflows = self.dataflows.borrow_mut(); for index in active_dataflows.drain(..) { // Step dataflow if it exists, remove if not incomplete. if let Entry::Occupied(mut entry) = dataflows.entry(index) { // TODO: This is a moment at which a scheduling decision is being made. let incomplete = entry.get_mut().step(); if !incomplete { let mut paths = self.paths.borrow_mut(); for channel in entry.get_mut().channel_ids.drain(..) { paths.remove(&channel); } entry.remove_entry(); } } } } // Clean up, indicate if dataflows remain. self.logging.borrow_mut().flush(); self.allocator.borrow_mut().release(); !self.dataflows.borrow().is_empty() } /// Calls `self.step()` as long as `func` evaluates to true. /// /// This method will continually execute even if there is not work /// for the worker to perform. Consider using the similar method /// `Self::step_or_park_while(duration)` to allow the worker to yield /// control if that is appropriate. /// /// # Examples /// /// ``` /// timely::execute_from_args(::std::env::args(), |worker| { /// /// use timely::dataflow::operators::{ToStream, Inspect, Probe}; /// /// let probe = /// worker.dataflow::<usize,_,_>(|scope| { /// (0 .. 10) /// .to_stream(scope) /// .inspect(|x| println!("{:?}", x)) /// .probe() /// }); /// /// worker.step_while(|| probe.less_than(&0)); /// }); /// ``` pub fn step_while<F: FnMut()->bool>(&mut self, func: F) { self.step_or_park_while(Some(Duration::from_secs(0)), func) } /// Calls `self.step_or_park(duration)` as long as `func` evaluates to true. /// /// This method may yield whenever there is no work to perform, as performed /// by `Self::step_or_park()`. Please consult the documentation for further /// information about that method and its behavior. In particular, the method /// can park the worker indefinitely, if no new work re-awakens the worker. /// /// # Examples /// /// ``` /// timely::execute_from_args(::std::env::args(), |worker| { /// /// use timely::dataflow::operators::{ToStream, Inspect, Probe}; /// /// let probe = /// worker.dataflow::<usize,_,_>(|scope| { /// (0 .. 10) /// .to_stream(scope) /// .inspect(|x| println!("{:?}", x)) /// .probe() /// }); /// /// worker.step_or_park_while(None, || probe.less_than(&0)); /// }); /// ``` pub fn step_or_park_while<F: FnMut()->bool>(&mut self, duration: Option<Duration>, mut func: F) { while func() { self.step_or_park(duration); } } /// The index of the worker out of its peers. /// /// # Examples /// ``` /// timely::execute_from_args(::std::env::args(), |worker| { /// /// let index = worker.index(); /// let peers = worker.peers(); /// let timer = worker.timer(); /// /// println!("{:?}\tWorker {} of {}", timer.elapsed(), index, peers); /// /// }); /// ``` pub fn index(&self) -> usize { self.allocator.borrow().index() } /// The total number of peer workers. /// /// # Examples /// ``` /// timely::execute_from_args(::std::env::args(), |worker| { /// /// let index = worker.index(); /// let peers = worker.peers(); /// let timer = worker.timer(); /// /// println!("{:?}\tWorker {} of {}", timer.elapsed(), index, peers); /// /// }); /// ``` pub fn peers(&self) -> usize { self.allocator.borrow().peers() } /// A timer started at the initiation of the timely computation. /// /// # Examples /// ``` /// timely::execute_from_args(::std::env::args(), |worker| { /// /// let index = worker.index(); /// let peers = worker.peers(); /// let timer = worker.timer(); /// /// println!("{:?}\tWorker {} of {}", timer.elapsed(), index, peers); /// /// }); /// ``` pub fn timer(&self) -> Instant { self.timer } /// Allocate a new worker-unique identifier. /// /// This method is public, though it is not expected to be widely used outside /// of the timely dataflow system. pub fn new_identifier(&mut self) -> usize { *self.identifiers.borrow_mut() += 1; *self.identifiers.borrow() - 1 } /// Access to named loggers. /// /// # Examples /// /// ``` /// timely::execute_from_args(::std::env::args(), |worker| { /// /// worker.log_register() /// .insert::<timely::logging::TimelyEvent,_>("timely", |time, data| /// println!("{:?}\t{:?}", time, data) /// ); /// }); /// ``` pub fn log_register(&self) -> ::std::cell::RefMut<crate::logging_core::Registry<crate::logging::WorkerIdentifier>> { self.logging.borrow_mut() } /// Construct a new dataflow. /// /// # Examples /// ``` /// timely::execute_from_args(::std::env::args(), |worker| { /// /// // We must supply the timestamp type here, although /// // it would generally be determined by type inference. /// worker.dataflow::<usize,_,_>(|scope| { /// /// // uses of `scope` to build dataflow /// /// }); /// }); /// ``` pub fn dataflow<T, R, F>(&mut self, func: F) -> R where T: Refines<()>, F: FnOnce(&mut Child<Self, T>)->R, { let logging = self.logging.borrow_mut().get("timely"); self.dataflow_core("Dataflow", logging, Box::new(()), |_, child| func(child)) } /// Construct a new dataflow with a (purely cosmetic) name. /// /// # Examples /// ``` /// timely::execute_from_args(::std::env::args(), |worker| { /// /// // We must supply the timestamp type here, although /// // it would generally be determined by type inference. /// worker.dataflow_named::<usize,_,_>("Some Dataflow", |scope| { /// /// // uses of `scope` to build dataflow /// /// }); /// }); /// ``` pub fn dataflow_named<T, R, F>(&mut self, name: &str, func: F) -> R where T: Refines<()>, F: FnOnce(&mut Child<Self, T>)->R, { let logging = self.logging.borrow_mut().get("timely"); self.dataflow_core(name, logging, Box::new(()), |_, child| func(child)) } /// Construct a new dataflow with specific configurations. /// /// This method constructs a new dataflow, using a name, logger, and additional /// resources specified as argument. The name is cosmetic, the logger is used to /// handle events generated by the dataflow, and the additional resources are kept /// alive for as long as the dataflow is alive (use case: shared library bindings). /// /// # Examples /// ``` /// timely::execute_from_args(::std::env::args(), |worker| { /// /// // We must supply the timestamp type here, although /// // it would generally be determined by type inference. /// worker.dataflow_core::<usize,_,_,_>( /// "dataflow X", // Dataflow name /// None, // Optional logger /// 37, // Any resources /// |resources, scope| { // Closure /// /// // uses of `resources`, `scope`to build dataflow /// /// } /// ); /// }); /// ``` pub fn dataflow_core<T, R, F, V>(&mut self, name: &str, mut logging: Option<TimelyLogger>, mut resources: V, func: F) -> R where T: Refines<()>, F: FnOnce(&mut V, &mut Child<Self, T>)->R, V: Any+'static, { let addr = vec![]; let dataflow_index = self.allocate_dataflow_index(); let identifier = self.new_identifier(); let progress_logging = self.logging.borrow_mut().get("timely/progress"); let subscope = SubgraphBuilder::new_from(dataflow_index, addr, logging.clone(), progress_logging.clone(), name); let subscope = RefCell::new(subscope); let result = { let mut builder = Child { subgraph: &subscope, parent: self.clone(), logging: logging.clone(), progress_logging, }; func(&mut resources, &mut builder) }; let mut operator = subscope.into_inner().build(self); if let Some(l) = logging.as_mut() { l.log(crate::logging::OperatesEvent { id: identifier, addr: operator.path().to_vec(), name: operator.name().to_string(), }); l.flush(); } operator.get_internal_summary(); operator.set_external_summary(); let mut temp_channel_ids = self.temp_channel_ids.borrow_mut(); let channel_ids = temp_channel_ids.drain(..).collect::<Vec<_>>(); let wrapper = Wrapper { logging, identifier, operate: Some(Box::new(operator)), resources: Some(Box::new(resources)), channel_ids, }; self.dataflows.borrow_mut().insert(dataflow_index, wrapper); result } /// Drops an identified dataflow. /// /// This method removes the identified dataflow, which will no longer be scheduled. /// Various other resources will be cleaned up, though the method is currently in /// public beta rather than expected to work. Please report all crashes and unmet /// expectations! pub fn drop_dataflow(&mut self, dataflow_identifier: usize) { if let Some(mut entry) = self.dataflows.borrow_mut().remove(&dataflow_identifier) { // Garbage collect channel_id to path information. let mut paths = self.paths.borrow_mut(); for channel in entry.channel_ids.drain(..) { paths.remove(&channel); } } } /// Returns the next index to be used for dataflow construction. /// /// This identifier will appear in the address of contained operators, and can /// be used to drop the dataflow using `self.drop_dataflow()`. pub fn next_dataflow_index(&self) -> usize { *self.dataflow_counter.borrow() } /// List the current dataflow indices. pub fn installed_dataflows(&self) -> Vec<usize> { self.dataflows.borrow().keys().cloned().collect() } // Acquire a new distinct dataflow identifier. fn allocate_dataflow_index(&mut self) -> usize { *self.dataflow_counter.borrow_mut() += 1; *self.dataflow_counter.borrow() - 1 } } use crate::communication::Message; impl<A: Allocate> Clone for Worker<A> { fn clone(&self) -> Self { Worker { config: self.config.clone(), timer: self.timer, paths: self.paths.clone(), allocator: self.allocator.clone(), identifiers: self.identifiers.clone(), dataflows: self.dataflows.clone(), dataflow_counter: self.dataflow_counter.clone(), logging: self.logging.clone(), activations: self.activations.clone(), active_dataflows: Vec::new(), temp_channel_ids: self.temp_channel_ids.clone(), } } } struct Wrapper { logging: Option<TimelyLogger>, identifier: usize, operate: Option<Box<dyn Schedule>>, resources: Option<Box<dyn Any>>, channel_ids: Vec<usize>, } impl Wrapper { /// Steps the dataflow, indicates if it remains incomplete. /// /// If the dataflow is incomplete, this call will drop it and its resources, /// dropping the dataflow first and then the resources (so that, e.g., shared /// library bindings will outlive the dataflow). fn step(&mut self) -> bool { // Perhaps log information about the start of the schedule call. if let Some(l) = self.logging.as_mut() { l.log(crate::logging::ScheduleEvent::start(self.identifier)); } let incomplete = self.operate.as_mut().map(|op| op.schedule()).unwrap_or(false); if !incomplete { self.operate = None; self.resources = None; } // Perhaps log information about the stop of the schedule call. if let Some(l) = self.logging.as_mut() { l.log(crate::logging::ScheduleEvent::stop(self.identifier)); } incomplete } } impl Drop for Wrapper { fn drop(&mut self) { if let Some(l) = self.logging.as_mut() { l.log(crate::logging::ShutdownEvent { id: self.identifier }); } // ensure drop order self.operate = None; self.resources = None; } }
37.301423
138
0.582923
3a82c91741552ef39b38b08d238e902fbe11a9f5
5,185
// Copyright 2020 The Exonum Team // // 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. //! Simplified blockchain emulation for the explorer tests. use exonum::{ blockchain::{ config::GenesisConfigBuilder, ApiSender, Blockchain, BlockchainBuilder, BlockchainMut, ConsensusConfig, }, crypto::{self, PublicKey, SecretKey}, merkledb::{ObjectHash, TemporaryDB}, messages::Verified, runtime::{AnyTx, ExecutionContext, ExecutionError, InstanceId}, }; use exonum_derive::*; use exonum_rust_runtime::{RustRuntime, Service, ServiceFactory}; use serde_derive::*; use std::collections::BTreeMap; pub const SERVICE_ID: InstanceId = 118; #[derive(Clone, Debug)] #[derive(Serialize, Deserialize)] #[derive(BinaryValue, ObjectHash)] #[binary_value(codec = "bincode")] pub struct CreateWallet { pub name: String, } impl CreateWallet { pub fn new(name: impl Into<String>) -> Self { Self { name: name.into() } } } #[derive(Clone, Debug)] #[derive(Serialize, Deserialize)] #[derive(BinaryValue, ObjectHash)] #[binary_value(codec = "bincode")] pub struct Transfer { pub to: PublicKey, pub amount: u64, } impl Transfer { pub fn new(to: PublicKey, amount: u64) -> Self { Self { to, amount } } } #[derive(Debug, ExecutionFail)] pub enum Error { /// Not allowed! NotAllowed = 0, } #[exonum_interface(auto_ids)] pub trait ExplorerTransactions<Ctx> { type Output; fn create_wallet(&self, ctx: Ctx, arg: CreateWallet) -> Self::Output; fn transfer(&self, ctx: Ctx, arg: Transfer) -> Self::Output; } #[derive(Debug, ServiceDispatcher, ServiceFactory)] #[service_factory(artifact_name = "my-service", artifact_version = "1.0.1")] #[service_dispatcher(implements("ExplorerTransactions"))] pub struct MyService; impl ExplorerTransactions<ExecutionContext<'_>> for MyService { type Output = Result<(), ExecutionError>; fn create_wallet(&self, _ctx: ExecutionContext<'_>, arg: CreateWallet) -> Self::Output { if arg.name.starts_with("Al") { Ok(()) } else { Err(Error::NotAllowed.into()) } } fn transfer(&self, _ctx: ExecutionContext<'_>, _arg: Transfer) -> Self::Output { panic!("oops"); } } impl Service for MyService {} /// Generates a keypair from a fixed passphrase. pub fn consensus_keys() -> (PublicKey, SecretKey) { const SEED_PHRASE: &[u8] = b"correct horse battery staple"; let seed = crypto::Seed::from_slice(crypto::hash(SEED_PHRASE).as_ref()).unwrap(); crypto::gen_keypair_from_seed(&seed) } /// Creates a blockchain with no blocks. pub fn create_blockchain() -> BlockchainMut { let (config, node_keys) = ConsensusConfig::for_tests(1); let blockchain = Blockchain::new( TemporaryDB::new(), ( node_keys.service.public_key(), node_keys.service.secret_key().to_owned(), ), ApiSender::closed(), ); let my_service = MyService; let my_service_artifact = my_service.artifact_id(); let genesis_config = GenesisConfigBuilder::with_consensus_config(config) .with_artifact(my_service_artifact.clone()) .with_instance(my_service_artifact.into_default_instance(SERVICE_ID, "my-service")) .build(); let rust_runtime = RustRuntime::builder() .with_factory(my_service) .build_for_tests(); BlockchainBuilder::new(blockchain, genesis_config) .with_runtime(rust_runtime) .build() } /// Simplified compared to real life / testkit, but we don't need to test *everything* /// here. pub fn create_block(blockchain: &mut BlockchainMut, transactions: Vec<Verified<AnyTx>>) { use exonum::{ crypto::Hash, helpers::{Round, ValidatorId}, messages::Precommit, }; use std::time::SystemTime; let tx_hashes: Vec<_> = transactions.iter().map(ObjectHash::object_hash).collect(); let height = blockchain.as_ref().last_block().height.next(); blockchain.add_transactions_into_pool(transactions); let mut tx_cache = BTreeMap::new(); let (block_hash, patch) = blockchain.create_patch(ValidatorId(0), height, &tx_hashes, &mut tx_cache); let (consensus_public_key, consensus_secret_key) = consensus_keys(); let precommit = Verified::from_value( Precommit::new( ValidatorId(0), height, Round::first(), Hash::zero(), block_hash, SystemTime::now().into(), ), consensus_public_key, &consensus_secret_key, ); blockchain .commit(patch, block_hash, vec![precommit], &mut tx_cache) .unwrap(); }
30.5
94
0.66866
76db9490019c574f89f2455316223d0e6505db43
2,149
#![feature(test)] #![allow(deprecated)] extern crate test; use test::{black_box, Bencher}; use ndarray::Zip; use numpy::{npyiter::NpyMultiIterBuilder, PyArray}; use pyo3::Python; fn numpy_iter(bencher: &mut Bencher, size: usize) { Python::with_gil(|py| { let x = PyArray::<f64, _>::zeros(py, size, false); let y = PyArray::<f64, _>::zeros(py, size, false); let z = PyArray::<f64, _>::zeros(py, size, false); let x = x.readonly(); let y = y.readonly(); let mut z = z.readwrite(); bencher.iter(|| { let iter = NpyMultiIterBuilder::new() .add_readonly(black_box(&x)) .add_readonly(black_box(&y)) .add_readwrite(black_box(&mut z)) .build() .unwrap(); for (x, y, z) in iter { *z = x + y; } }); }); } #[bench] fn numpy_iter_small(bencher: &mut Bencher) { numpy_iter(bencher, 2_usize.pow(5)); } #[bench] fn numpy_iter_medium(bencher: &mut Bencher) { numpy_iter(bencher, 2_usize.pow(10)); } #[bench] fn numpy_iter_large(bencher: &mut Bencher) { numpy_iter(bencher, 2_usize.pow(15)); } fn ndarray_iter(bencher: &mut Bencher, size: usize) { Python::with_gil(|py| { let x = PyArray::<f64, _>::zeros(py, size, false); let y = PyArray::<f64, _>::zeros(py, size, false); let z = PyArray::<f64, _>::zeros(py, size, false); let x = x.readonly(); let y = y.readonly(); let mut z = z.readwrite(); bencher.iter(|| { Zip::from(black_box(x.as_array())) .and(black_box(y.as_array())) .and(black_box(z.as_array_mut())) .for_each(|x, y, z| { *z = x + y; }); }); }); } #[bench] fn ndarray_iter_small(bencher: &mut Bencher) { ndarray_iter(bencher, 2_usize.pow(5)); } #[bench] fn ndarray_iter_medium(bencher: &mut Bencher) { ndarray_iter(bencher, 2_usize.pow(10)); } #[bench] fn ndarray_iter_large(bencher: &mut Bencher) { ndarray_iter(bencher, 2_usize.pow(15)); }
24.988372
58
0.544905
61d2eceb3087771d965d0dfc961eca2534925f20
107,528
/// Note: most tests relevant to this file can be found (at the time of writing) /// in src/tests/ui/pattern/usefulness. /// /// This file includes the logic for exhaustiveness and usefulness checking for /// pattern-matching. Specifically, given a list of patterns for a type, we can /// tell whether: /// (a) the patterns cover every possible constructor for the type [exhaustiveness] /// (b) each pattern is necessary [usefulness] /// /// The algorithm implemented here is a modified version of the one described in: /// http://moscova.inria.fr/~maranget/papers/warn/index.html /// However, to save future implementors from reading the original paper, we /// summarise the algorithm here to hopefully save time and be a little clearer /// (without being so rigorous). /// /// The core of the algorithm revolves about a "usefulness" check. In particular, we /// are trying to compute a predicate `U(P, p)` where `P` is a list of patterns (we refer to this as /// a matrix). `U(P, p)` represents whether, given an existing list of patterns /// `P_1 ..= P_m`, adding a new pattern `p` will be "useful" (that is, cover previously- /// uncovered values of the type). /// /// If we have this predicate, then we can easily compute both exhaustiveness of an /// entire set of patterns and the individual usefulness of each one. /// (a) the set of patterns is exhaustive iff `U(P, _)` is false (i.e., adding a wildcard /// match doesn't increase the number of values we're matching) /// (b) a pattern `P_i` is not useful if `U(P[0..=(i-1), P_i)` is false (i.e., adding a /// pattern to those that have come before it doesn't increase the number of values /// we're matching). /// /// During the course of the algorithm, the rows of the matrix won't just be individual patterns, /// but rather partially-deconstructed patterns in the form of a list of patterns. The paper /// calls those pattern-vectors, and we will call them pattern-stacks. The same holds for the /// new pattern `p`. /// /// For example, say we have the following: /// ``` /// // x: (Option<bool>, Result<()>) /// match x { /// (Some(true), _) => {} /// (None, Err(())) => {} /// (None, Err(_)) => {} /// } /// ``` /// Here, the matrix `P` starts as: /// [ /// [(Some(true), _)], /// [(None, Err(()))], /// [(None, Err(_))], /// ] /// We can tell it's not exhaustive, because `U(P, _)` is true (we're not covering /// `[(Some(false), _)]`, for instance). In addition, row 3 is not useful, because /// all the values it covers are already covered by row 2. /// /// A list of patterns can be thought of as a stack, because we are mainly interested in the top of /// the stack at any given point, and we can pop or apply constructors to get new pattern-stacks. /// To match the paper, the top of the stack is at the beginning / on the left. /// /// There are two important operations on pattern-stacks necessary to understand the algorithm: /// 1. We can pop a given constructor off the top of a stack. This operation is called /// `specialize`, and is denoted `S(c, p)` where `c` is a constructor (like `Some` or /// `None`) and `p` a pattern-stack. /// If the pattern on top of the stack can cover `c`, this removes the constructor and /// pushes its arguments onto the stack. It also expands OR-patterns into distinct patterns. /// Otherwise the pattern-stack is discarded. /// This essentially filters those pattern-stacks whose top covers the constructor `c` and /// discards the others. /// /// For example, the first pattern above initially gives a stack `[(Some(true), _)]`. If we /// pop the tuple constructor, we are left with `[Some(true), _]`, and if we then pop the /// `Some` constructor we get `[true, _]`. If we had popped `None` instead, we would get /// nothing back. /// /// This returns zero or more new pattern-stacks, as follows. We look at the pattern `p_1` /// on top of the stack, and we have four cases: /// 1.1. `p_1 = c(r_1, .., r_a)`, i.e. the top of the stack has constructor `c`. We /// push onto the stack the arguments of this constructor, and return the result: /// r_1, .., r_a, p_2, .., p_n /// 1.2. `p_1 = c'(r_1, .., r_a')` where `c ≠ c'`. We discard the current stack and /// return nothing. /// 1.3. `p_1 = _`. We push onto the stack as many wildcards as the constructor `c` has /// arguments (its arity), and return the resulting stack: /// _, .., _, p_2, .., p_n /// 1.4. `p_1 = r_1 | r_2`. We expand the OR-pattern and then recurse on each resulting /// stack: /// S(c, (r_1, p_2, .., p_n)) /// S(c, (r_2, p_2, .., p_n)) /// /// 2. We can pop a wildcard off the top of the stack. This is called `D(p)`, where `p` is /// a pattern-stack. /// This is used when we know there are missing constructor cases, but there might be /// existing wildcard patterns, so to check the usefulness of the matrix, we have to check /// all its *other* components. /// /// It is computed as follows. We look at the pattern `p_1` on top of the stack, /// and we have three cases: /// 1.1. `p_1 = c(r_1, .., r_a)`. We discard the current stack and return nothing. /// 1.2. `p_1 = _`. We return the rest of the stack: /// p_2, .., p_n /// 1.3. `p_1 = r_1 | r_2`. We expand the OR-pattern and then recurse on each resulting /// stack. /// D((r_1, p_2, .., p_n)) /// D((r_2, p_2, .., p_n)) /// /// Note that the OR-patterns are not always used directly in Rust, but are used to derive the /// exhaustive integer matching rules, so they're written here for posterity. /// /// Both those operations extend straightforwardly to a list or pattern-stacks, i.e. a matrix, by /// working row-by-row. Popping a constructor ends up keeping only the matrix rows that start with /// the given constructor, and popping a wildcard keeps those rows that start with a wildcard. /// /// /// The algorithm for computing `U` /// ------------------------------- /// The algorithm is inductive (on the number of columns: i.e., components of tuple patterns). /// That means we're going to check the components from left-to-right, so the algorithm /// operates principally on the first component of the matrix and new pattern-stack `p`. /// This algorithm is realised in the `is_useful` function. /// /// Base case. (`n = 0`, i.e., an empty tuple pattern) /// - If `P` already contains an empty pattern (i.e., if the number of patterns `m > 0`), /// then `U(P, p)` is false. /// - Otherwise, `P` must be empty, so `U(P, p)` is true. /// /// Inductive step. (`n > 0`, i.e., whether there's at least one column /// [which may then be expanded into further columns later]) /// We're going to match on the top of the new pattern-stack, `p_1`. /// - If `p_1 == c(r_1, .., r_a)`, i.e. we have a constructor pattern. /// Then, the usefulness of `p_1` can be reduced to whether it is useful when /// we ignore all the patterns in the first column of `P` that involve other constructors. /// This is where `S(c, P)` comes in: /// `U(P, p) := U(S(c, P), S(c, p))` /// This special case is handled in `is_useful_specialized`. /// /// For example, if `P` is: /// [ /// [Some(true), _], /// [None, 0], /// ] /// and `p` is [Some(false), 0], then we don't care about row 2 since we know `p` only /// matches values that row 2 doesn't. For row 1 however, we need to dig into the /// arguments of `Some` to know whether some new value is covered. So we compute /// `U([[true, _]], [false, 0])`. /// /// - If `p_1 == _`, then we look at the list of constructors that appear in the first /// component of the rows of `P`: /// + If there are some constructors that aren't present, then we might think that the /// wildcard `_` is useful, since it covers those constructors that weren't covered /// before. /// That's almost correct, but only works if there were no wildcards in those first /// components. So we need to check that `p` is useful with respect to the rows that /// start with a wildcard, if there are any. This is where `D` comes in: /// `U(P, p) := U(D(P), D(p))` /// /// For example, if `P` is: /// [ /// [_, true, _], /// [None, false, 1], /// ] /// and `p` is [_, false, _], the `Some` constructor doesn't appear in `P`. So if we /// only had row 2, we'd know that `p` is useful. However row 1 starts with a /// wildcard, so we need to check whether `U([[true, _]], [false, 1])`. /// /// + Otherwise, all possible constructors (for the relevant type) are present. In this /// case we must check whether the wildcard pattern covers any unmatched value. For /// that, we can think of the `_` pattern as a big OR-pattern that covers all /// possible constructors. For `Option`, that would mean `_ = None | Some(_)` for /// example. The wildcard pattern is useful in this case if it is useful when /// specialized to one of the possible constructors. So we compute: /// `U(P, p) := ∃(k ϵ constructors) U(S(k, P), S(k, p))` /// /// For example, if `P` is: /// [ /// [Some(true), _], /// [None, false], /// ] /// and `p` is [_, false], both `None` and `Some` constructors appear in the first /// components of `P`. We will therefore try popping both constructors in turn: we /// compute U([[true, _]], [_, false]) for the `Some` constructor, and U([[false]], /// [false]) for the `None` constructor. The first case returns true, so we know that /// `p` is useful for `P`. Indeed, it matches `[Some(false), _]` that wasn't matched /// before. /// /// - If `p_1 == r_1 | r_2`, then the usefulness depends on each `r_i` separately: /// `U(P, p) := U(P, (r_1, p_2, .., p_n)) /// || U(P, (r_2, p_2, .., p_n))` /// /// Modifications to the algorithm /// ------------------------------ /// The algorithm in the paper doesn't cover some of the special cases that arise in Rust, for /// example uninhabited types and variable-length slice patterns. These are drawn attention to /// throughout the code below. I'll make a quick note here about how exhaustive integer matching is /// accounted for, though. /// /// Exhaustive integer matching /// --------------------------- /// An integer type can be thought of as a (huge) sum type: 1 | 2 | 3 | ... /// So to support exhaustive integer matching, we can make use of the logic in the paper for /// OR-patterns. However, we obviously can't just treat ranges x..=y as individual sums, because /// they are likely gigantic. So we instead treat ranges as constructors of the integers. This means /// that we have a constructor *of* constructors (the integers themselves). We then need to work /// through all the inductive step rules above, deriving how the ranges would be treated as /// OR-patterns, and making sure that they're treated in the same way even when they're ranges. /// There are really only four special cases here: /// - When we match on a constructor that's actually a range, we have to treat it as if we would /// an OR-pattern. /// + It turns out that we can simply extend the case for single-value patterns in /// `specialize` to either be *equal* to a value constructor, or *contained within* a range /// constructor. /// + When the pattern itself is a range, you just want to tell whether any of the values in /// the pattern range coincide with values in the constructor range, which is precisely /// intersection. /// Since when encountering a range pattern for a value constructor, we also use inclusion, it /// means that whenever the constructor is a value/range and the pattern is also a value/range, /// we can simply use intersection to test usefulness. /// - When we're testing for usefulness of a pattern and the pattern's first component is a /// wildcard. /// + If all the constructors appear in the matrix, we have a slight complication. By default, /// the behaviour (i.e., a disjunction over specialised matrices for each constructor) is /// invalid, because we want a disjunction over every *integer* in each range, not just a /// disjunction over every range. This is a bit more tricky to deal with: essentially we need /// to form equivalence classes of subranges of the constructor range for which the behaviour /// of the matrix `P` and new pattern `p` are the same. This is described in more /// detail in `split_grouped_constructors`. /// + If some constructors are missing from the matrix, it turns out we don't need to do /// anything special (because we know none of the integers are actually wildcards: i.e., we /// can't span wildcards using ranges). use self::Constructor::*; use self::SliceKind::*; use self::Usefulness::*; use self::WitnessPreference::*; use rustc_data_structures::fx::FxHashMap; use rustc_index::vec::Idx; use super::{compare_const_vals, PatternFoldable, PatternFolder}; use super::{FieldPat, Pat, PatKind, PatRange}; use rustc::hir::def_id::DefId; use rustc::hir::{HirId, RangeEnd}; use rustc::ty::layout::{Integer, IntegerExt, Size, VariantIdx}; use rustc::ty::{self, Const, Ty, TyCtxt, TypeFoldable, VariantDef}; use rustc::lint; use rustc::mir::interpret::{truncate, AllocId, ConstValue, Pointer, Scalar}; use rustc::mir::Field; use rustc::util::captures::Captures; use rustc::util::common::ErrorReported; use rustc_span::{Span, DUMMY_SP}; use syntax::attr::{SignedInt, UnsignedInt}; use arena::TypedArena; use smallvec::{smallvec, SmallVec}; use std::borrow::Cow; use std::cmp::{self, max, min, Ordering}; use std::convert::TryInto; use std::fmt; use std::iter::{FromIterator, IntoIterator}; use std::ops::RangeInclusive; use std::u128; pub fn expand_pattern<'a, 'tcx>(cx: &MatchCheckCtxt<'a, 'tcx>, pat: Pat<'tcx>) -> Pat<'tcx> { LiteralExpander { tcx: cx.tcx, param_env: cx.param_env }.fold_pattern(&pat) } struct LiteralExpander<'tcx> { tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, } impl LiteralExpander<'tcx> { /// Derefs `val` and potentially unsizes the value if `crty` is an array and `rty` a slice. /// /// `crty` and `rty` can differ because you can use array constants in the presence of slice /// patterns. So the pattern may end up being a slice, but the constant is an array. We convert /// the array to a slice in that case. fn fold_const_value_deref( &mut self, val: ConstValue<'tcx>, // the pattern's pointee type rty: Ty<'tcx>, // the constant's pointee type crty: Ty<'tcx>, ) -> ConstValue<'tcx> { debug!("fold_const_value_deref {:?} {:?} {:?}", val, rty, crty); match (val, &crty.kind, &rty.kind) { // the easy case, deref a reference (ConstValue::Scalar(p), x, y) if x == y => { match p { Scalar::Ptr(p) => { let alloc = self.tcx.alloc_map.lock().unwrap_memory(p.alloc_id); ConstValue::ByRef { alloc, offset: p.offset } } Scalar::Raw { .. } => { let layout = self.tcx.layout_of(self.param_env.and(rty)).unwrap(); if layout.is_zst() { // Deref of a reference to a ZST is a nop. ConstValue::Scalar(Scalar::zst()) } else { // FIXME(oli-obk): this is reachable for `const FOO: &&&u32 = &&&42;` bug!("cannot deref {:#?}, {} -> {}", val, crty, rty); } } } } // unsize array to slice if pattern is array but match value or other patterns are slice (ConstValue::Scalar(Scalar::Ptr(p)), ty::Array(t, n), ty::Slice(u)) => { assert_eq!(t, u); ConstValue::Slice { data: self.tcx.alloc_map.lock().unwrap_memory(p.alloc_id), start: p.offset.bytes().try_into().unwrap(), end: n.eval_usize(self.tcx, ty::ParamEnv::empty()).try_into().unwrap(), } } // fat pointers stay the same (ConstValue::Slice { .. }, _, _) | (_, ty::Slice(_), ty::Slice(_)) | (_, ty::Str, ty::Str) => val, // FIXME(oli-obk): this is reachable for `const FOO: &&&u32 = &&&42;` being used _ => bug!("cannot deref {:#?}, {} -> {}", val, crty, rty), } } } impl PatternFolder<'tcx> for LiteralExpander<'tcx> { fn fold_pattern(&mut self, pat: &Pat<'tcx>) -> Pat<'tcx> { debug!("fold_pattern {:?} {:?} {:?}", pat, pat.ty.kind, pat.kind); match (&pat.ty.kind, &*pat.kind) { ( &ty::Ref(_, rty, _), &PatKind::Constant { value: Const { val: ty::ConstKind::Value(val), ty: ty::TyS { kind: ty::Ref(_, crty, _), .. }, }, }, ) => Pat { ty: pat.ty, span: pat.span, kind: box PatKind::Deref { subpattern: Pat { ty: rty, span: pat.span, kind: box PatKind::Constant { value: self.tcx.mk_const(Const { val: ty::ConstKind::Value( self.fold_const_value_deref(*val, rty, crty), ), ty: rty, }), }, }, }, }, ( &ty::Ref(_, rty, _), &PatKind::Constant { value: Const { val, ty: ty::TyS { kind: ty::Ref(_, crty, _), .. } }, }, ) => bug!("cannot deref {:#?}, {} -> {}", val, crty, rty), (_, &PatKind::Binding { subpattern: Some(ref s), .. }) => s.fold_with(self), (_, &PatKind::AscribeUserType { subpattern: ref s, .. }) => s.fold_with(self), _ => pat.super_fold_with(self), } } } impl<'tcx> Pat<'tcx> { pub(super) fn is_wildcard(&self) -> bool { match *self.kind { PatKind::Binding { subpattern: None, .. } | PatKind::Wild => true, _ => false, } } } /// A row of a matrix. Rows of len 1 are very common, which is why `SmallVec[_; 2]` /// works well. #[derive(Debug, Clone)] pub struct PatStack<'p, 'tcx>(SmallVec<[&'p Pat<'tcx>; 2]>); impl<'p, 'tcx> PatStack<'p, 'tcx> { pub fn from_pattern(pat: &'p Pat<'tcx>) -> Self { PatStack(smallvec![pat]) } fn from_vec(vec: SmallVec<[&'p Pat<'tcx>; 2]>) -> Self { PatStack(vec) } fn from_slice(s: &[&'p Pat<'tcx>]) -> Self { PatStack(SmallVec::from_slice(s)) } fn is_empty(&self) -> bool { self.0.is_empty() } fn len(&self) -> usize { self.0.len() } fn head(&self) -> &'p Pat<'tcx> { self.0[0] } fn to_tail(&self) -> Self { PatStack::from_slice(&self.0[1..]) } fn iter(&self) -> impl Iterator<Item = &Pat<'tcx>> { self.0.iter().map(|p| *p) } // If the first pattern is an or-pattern, expand this pattern. Otherwise, return `None`. fn expand_or_pat(&self) -> Option<Vec<Self>> { if self.is_empty() { None } else if let PatKind::Or { pats } = &*self.head().kind { Some( pats.iter() .map(|pat| { let mut new_patstack = PatStack::from_pattern(pat); new_patstack.0.extend_from_slice(&self.0[1..]); new_patstack }) .collect(), ) } else { None } } /// This computes `D(self)`. See top of the file for explanations. fn specialize_wildcard(&self) -> Option<Self> { if self.head().is_wildcard() { Some(self.to_tail()) } else { None } } /// This computes `S(constructor, self)`. See top of the file for explanations. fn specialize_constructor( &self, cx: &mut MatchCheckCtxt<'p, 'tcx>, constructor: &Constructor<'tcx>, ctor_wild_subpatterns: &'p [Pat<'tcx>], ) -> Option<PatStack<'p, 'tcx>> { let new_heads = specialize_one_pattern(cx, self.head(), constructor, ctor_wild_subpatterns); new_heads.map(|mut new_head| { new_head.0.extend_from_slice(&self.0[1..]); new_head }) } } impl<'p, 'tcx> Default for PatStack<'p, 'tcx> { fn default() -> Self { PatStack(smallvec![]) } } impl<'p, 'tcx> FromIterator<&'p Pat<'tcx>> for PatStack<'p, 'tcx> { fn from_iter<T>(iter: T) -> Self where T: IntoIterator<Item = &'p Pat<'tcx>>, { PatStack(iter.into_iter().collect()) } } /// A 2D matrix. #[derive(Clone)] pub struct Matrix<'p, 'tcx>(Vec<PatStack<'p, 'tcx>>); impl<'p, 'tcx> Matrix<'p, 'tcx> { pub fn empty() -> Self { Matrix(vec![]) } /// Pushes a new row to the matrix. If the row starts with an or-pattern, this expands it. pub fn push(&mut self, row: PatStack<'p, 'tcx>) { if let Some(rows) = row.expand_or_pat() { self.0.extend(rows); } else { self.0.push(row); } } /// Iterate over the first component of each row fn heads<'a>(&'a self) -> impl Iterator<Item = &'a Pat<'tcx>> + Captures<'p> { self.0.iter().map(|r| r.head()) } /// This computes `D(self)`. See top of the file for explanations. fn specialize_wildcard(&self) -> Self { self.0.iter().filter_map(|r| r.specialize_wildcard()).collect() } /// This computes `S(constructor, self)`. See top of the file for explanations. fn specialize_constructor( &self, cx: &mut MatchCheckCtxt<'p, 'tcx>, constructor: &Constructor<'tcx>, ctor_wild_subpatterns: &'p [Pat<'tcx>], ) -> Matrix<'p, 'tcx> { self.0 .iter() .filter_map(|r| r.specialize_constructor(cx, constructor, ctor_wild_subpatterns)) .collect() } } /// Pretty-printer for matrices of patterns, example: /// +++++++++++++++++++++++++++++ /// + _ + [] + /// +++++++++++++++++++++++++++++ /// + true + [First] + /// +++++++++++++++++++++++++++++ /// + true + [Second(true)] + /// +++++++++++++++++++++++++++++ /// + false + [_] + /// +++++++++++++++++++++++++++++ /// + _ + [_, _, tail @ ..] + /// +++++++++++++++++++++++++++++ impl<'p, 'tcx> fmt::Debug for Matrix<'p, 'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "\n")?; let &Matrix(ref m) = self; let pretty_printed_matrix: Vec<Vec<String>> = m.iter().map(|row| row.iter().map(|pat| format!("{:?}", pat)).collect()).collect(); let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0); assert!(m.iter().all(|row| row.len() == column_count)); let column_widths: Vec<usize> = (0..column_count) .map(|col| pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0)) .collect(); let total_width = column_widths.iter().cloned().sum::<usize>() + column_count * 3 + 1; let br = "+".repeat(total_width); write!(f, "{}\n", br)?; for row in pretty_printed_matrix { write!(f, "+")?; for (column, pat_str) in row.into_iter().enumerate() { write!(f, " ")?; write!(f, "{:1$}", pat_str, column_widths[column])?; write!(f, " +")?; } write!(f, "\n")?; write!(f, "{}\n", br)?; } Ok(()) } } impl<'p, 'tcx> FromIterator<PatStack<'p, 'tcx>> for Matrix<'p, 'tcx> { fn from_iter<T>(iter: T) -> Self where T: IntoIterator<Item = PatStack<'p, 'tcx>>, { let mut matrix = Matrix::empty(); for x in iter { // Using `push` ensures we correctly expand or-patterns. matrix.push(x); } matrix } } pub struct MatchCheckCtxt<'a, 'tcx> { pub tcx: TyCtxt<'tcx>, /// The module in which the match occurs. This is necessary for /// checking inhabited-ness of types because whether a type is (visibly) /// inhabited can depend on whether it was defined in the current module or /// not. E.g., `struct Foo { _private: ! }` cannot be seen to be empty /// outside it's module and should not be matchable with an empty match /// statement. pub module: DefId, param_env: ty::ParamEnv<'tcx>, pub pattern_arena: &'a TypedArena<Pat<'tcx>>, pub byte_array_map: FxHashMap<*const Pat<'tcx>, Vec<&'a Pat<'tcx>>>, } impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> { pub fn create_and_enter<F, R>( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, module: DefId, f: F, ) -> R where F: for<'b> FnOnce(MatchCheckCtxt<'b, 'tcx>) -> R, { let pattern_arena = TypedArena::default(); f(MatchCheckCtxt { tcx, param_env, module, pattern_arena: &pattern_arena, byte_array_map: FxHashMap::default(), }) } fn is_uninhabited(&self, ty: Ty<'tcx>) -> bool { if self.tcx.features().exhaustive_patterns { self.tcx.is_ty_uninhabited_from(self.module, ty) } else { false } } // Returns whether the given type is an enum from another crate declared `#[non_exhaustive]`. pub fn is_foreign_non_exhaustive_enum(&self, ty: Ty<'tcx>) -> bool { match ty.kind { ty::Adt(def, ..) => { def.is_enum() && def.is_variant_list_non_exhaustive() && !def.did.is_local() } _ => false, } } // Returns whether the given variant is from another crate and has its fields declared // `#[non_exhaustive]`. fn is_foreign_non_exhaustive_variant(&self, ty: Ty<'tcx>, variant: &VariantDef) -> bool { match ty.kind { ty::Adt(def, ..) => variant.is_field_list_non_exhaustive() && !def.did.is_local(), _ => false, } } } #[derive(Copy, Clone, Debug, PartialEq, Eq)] enum SliceKind { /// Patterns of length `n` (`[x, y]`). FixedLen(u64), /// Patterns using the `..` notation (`[x, .., y]`). /// Captures any array constructor of `length >= i + j`. /// In the case where `array_len` is `Some(_)`, /// this indicates that we only care about the first `i` and the last `j` values of the array, /// and everything in between is a wildcard `_`. VarLen(u64, u64), } impl SliceKind { fn arity(self) -> u64 { match self { FixedLen(length) => length, VarLen(prefix, suffix) => prefix + suffix, } } /// Whether this pattern includes patterns of length `other_len`. fn covers_length(self, other_len: u64) -> bool { match self { FixedLen(len) => len == other_len, VarLen(prefix, suffix) => prefix + suffix <= other_len, } } /// Returns a collection of slices that spans the values covered by `self`, subtracted by the /// values covered by `other`: i.e., `self \ other` (in set notation). fn subtract(self, other: Self) -> SmallVec<[Self; 1]> { // Remember, `VarLen(i, j)` covers the union of `FixedLen` from `i + j` to infinity. // Naming: we remove the "neg" constructors from the "pos" ones. match self { FixedLen(pos_len) => { if other.covers_length(pos_len) { smallvec![] } else { smallvec![self] } } VarLen(pos_prefix, pos_suffix) => { let pos_len = pos_prefix + pos_suffix; match other { FixedLen(neg_len) => { if neg_len < pos_len { smallvec![self] } else { (pos_len..neg_len) .map(FixedLen) // We know that `neg_len + 1 >= pos_len >= pos_suffix`. .chain(Some(VarLen(neg_len + 1 - pos_suffix, pos_suffix))) .collect() } } VarLen(neg_prefix, neg_suffix) => { let neg_len = neg_prefix + neg_suffix; if neg_len <= pos_len { smallvec![] } else { (pos_len..neg_len).map(FixedLen).collect() } } } } } } } /// A constructor for array and slice patterns. #[derive(Copy, Clone, Debug, PartialEq, Eq)] struct Slice { /// `None` if the matched value is a slice, `Some(n)` if it is an array of size `n`. array_len: Option<u64>, /// The kind of pattern it is: fixed-length `[x, y]` or variable length `[x, .., y]`. kind: SliceKind, } impl Slice { /// Returns what patterns this constructor covers: either fixed-length patterns or /// variable-length patterns. fn pattern_kind(self) -> SliceKind { match self { Slice { array_len: Some(len), kind: VarLen(prefix, suffix) } if prefix + suffix == len => { FixedLen(len) } _ => self.kind, } } /// Returns what values this constructor covers: either values of only one given length, or /// values of length above a given length. /// This is different from `pattern_kind()` because in some cases the pattern only takes into /// account a subset of the entries of the array, but still only captures values of a given /// length. fn value_kind(self) -> SliceKind { match self { Slice { array_len: Some(len), kind: VarLen(_, _) } => FixedLen(len), _ => self.kind, } } fn arity(self) -> u64 { self.pattern_kind().arity() } } #[derive(Clone, Debug, PartialEq)] enum Constructor<'tcx> { /// The constructor of all patterns that don't vary by constructor, /// e.g., struct patterns and fixed-length arrays. Single, /// Enum variants. Variant(DefId), /// Literal values. ConstantValue(&'tcx ty::Const<'tcx>), /// Ranges of integer literal values (`2`, `2..=5` or `2..5`). IntRange(IntRange<'tcx>), /// Ranges of floating-point literal values (`2.0..=5.2`). FloatRange(&'tcx ty::Const<'tcx>, &'tcx ty::Const<'tcx>, RangeEnd), /// Array and slice patterns. Slice(Slice), /// Fake extra constructor for enums that aren't allowed to be matched exhaustively. NonExhaustive, } impl<'tcx> Constructor<'tcx> { fn is_slice(&self) -> bool { match self { Slice(_) => true, _ => false, } } fn variant_index_for_adt<'a>( &self, cx: &MatchCheckCtxt<'a, 'tcx>, adt: &'tcx ty::AdtDef, ) -> VariantIdx { match self { Variant(id) => adt.variant_index_with_id(*id), Single => { assert!(!adt.is_enum()); VariantIdx::new(0) } ConstantValue(c) => crate::const_eval::const_variant_index(cx.tcx, cx.param_env, c), _ => bug!("bad constructor {:?} for adt {:?}", self, adt), } } // Returns the set of constructors covered by `self` but not by // anything in `other_ctors`. fn subtract_ctors(&self, other_ctors: &Vec<Constructor<'tcx>>) -> Vec<Constructor<'tcx>> { if other_ctors.is_empty() { return vec![self.clone()]; } match self { // Those constructors can only match themselves. Single | Variant(_) | ConstantValue(..) | FloatRange(..) => { if other_ctors.iter().any(|c| c == self) { vec![] } else { vec![self.clone()] } } &Slice(slice) => { let mut other_slices = other_ctors .iter() .filter_map(|c: &Constructor<'_>| match c { Slice(slice) => Some(*slice), // FIXME(oli-obk): implement `deref` for `ConstValue` ConstantValue(..) => None, _ => bug!("bad slice pattern constructor {:?}", c), }) .map(Slice::value_kind); match slice.value_kind() { FixedLen(self_len) => { if other_slices.any(|other_slice| other_slice.covers_length(self_len)) { vec![] } else { vec![Slice(slice)] } } kind @ VarLen(..) => { let mut remaining_slices = vec![kind]; // For each used slice, subtract from the current set of slices. for other_slice in other_slices { remaining_slices = remaining_slices .into_iter() .flat_map(|remaining_slice| remaining_slice.subtract(other_slice)) .collect(); // If the constructors that have been considered so far already cover // the entire range of `self`, no need to look at more constructors. if remaining_slices.is_empty() { break; } } remaining_slices .into_iter() .map(|kind| Slice { array_len: slice.array_len, kind }) .map(Slice) .collect() } } } IntRange(self_range) => { let mut remaining_ranges = vec![self_range.clone()]; for other_ctor in other_ctors { if let IntRange(other_range) = other_ctor { if other_range == self_range { // If the `self` range appears directly in a `match` arm, we can // eliminate it straight away. remaining_ranges = vec![]; } else { // Otherwise explicitely compute the remaining ranges. remaining_ranges = other_range.subtract_from(remaining_ranges); } // If the ranges that have been considered so far already cover the entire // range of values, we can return early. if remaining_ranges.is_empty() { break; } } } // Convert the ranges back into constructors. remaining_ranges.into_iter().map(IntRange).collect() } // This constructor is never covered by anything else NonExhaustive => vec![NonExhaustive], } } /// This returns one wildcard pattern for each argument to this constructor. /// /// This must be consistent with `apply`, `specialize_one_pattern`, and `arity`. fn wildcard_subpatterns<'a>( &self, cx: &MatchCheckCtxt<'a, 'tcx>, ty: Ty<'tcx>, ) -> Vec<Pat<'tcx>> { debug!("wildcard_subpatterns({:#?}, {:?})", self, ty); match self { Single | Variant(_) => match ty.kind { ty::Tuple(ref fs) => { fs.into_iter().map(|t| t.expect_ty()).map(Pat::wildcard_from_ty).collect() } ty::Ref(_, rty, _) => vec![Pat::wildcard_from_ty(rty)], ty::Adt(adt, substs) => { if adt.is_box() { // Use T as the sub pattern type of Box<T>. vec![Pat::wildcard_from_ty(substs.type_at(0))] } else { let variant = &adt.variants[self.variant_index_for_adt(cx, adt)]; let is_non_exhaustive = cx.is_foreign_non_exhaustive_variant(ty, variant); variant .fields .iter() .map(|field| { let is_visible = adt.is_enum() || field.vis.is_accessible_from(cx.module, cx.tcx); let is_uninhabited = cx.is_uninhabited(field.ty(cx.tcx, substs)); match (is_visible, is_non_exhaustive, is_uninhabited) { // Treat all uninhabited types in non-exhaustive variants as // `TyErr`. (_, true, true) => cx.tcx.types.err, // Treat all non-visible fields as `TyErr`. They can't appear // in any other pattern from this match (because they are // private), so their type does not matter - but we don't want // to know they are uninhabited. (false, ..) => cx.tcx.types.err, (true, ..) => { let ty = field.ty(cx.tcx, substs); match ty.kind { // If the field type returned is an array of an unknown // size return an TyErr. ty::Array(_, len) if len .try_eval_usize(cx.tcx, cx.param_env) .is_none() => { cx.tcx.types.err } _ => ty, } } } }) .map(Pat::wildcard_from_ty) .collect() } } _ => vec![], }, Slice(_) => match ty.kind { ty::Slice(ty) | ty::Array(ty, _) => { let arity = self.arity(cx, ty); (0..arity).map(|_| Pat::wildcard_from_ty(ty)).collect() } _ => bug!("bad slice pattern {:?} {:?}", self, ty), }, ConstantValue(..) | FloatRange(..) | IntRange(..) | NonExhaustive => vec![], } } /// This computes the arity of a constructor. The arity of a constructor /// is how many subpattern patterns of that constructor should be expanded to. /// /// For instance, a tuple pattern `(_, 42, Some([]))` has the arity of 3. /// A struct pattern's arity is the number of fields it contains, etc. /// /// This must be consistent with `wildcard_subpatterns`, `specialize_one_pattern`, and `apply`. fn arity<'a>(&self, cx: &MatchCheckCtxt<'a, 'tcx>, ty: Ty<'tcx>) -> u64 { debug!("Constructor::arity({:#?}, {:?})", self, ty); match self { Single | Variant(_) => match ty.kind { ty::Tuple(ref fs) => fs.len() as u64, ty::Slice(..) | ty::Array(..) => bug!("bad slice pattern {:?} {:?}", self, ty), ty::Ref(..) => 1, ty::Adt(adt, _) => { adt.variants[self.variant_index_for_adt(cx, adt)].fields.len() as u64 } _ => 0, }, Slice(slice) => slice.arity(), ConstantValue(..) | FloatRange(..) | IntRange(..) | NonExhaustive => 0, } } /// Apply a constructor to a list of patterns, yielding a new pattern. `pats` /// must have as many elements as this constructor's arity. /// /// This must be consistent with `wildcard_subpatterns`, `specialize_one_pattern`, and `arity`. /// /// Examples: /// `self`: `Constructor::Single` /// `ty`: `(u32, u32, u32)` /// `pats`: `[10, 20, _]` /// returns `(10, 20, _)` /// /// `self`: `Constructor::Variant(Option::Some)` /// `ty`: `Option<bool>` /// `pats`: `[false]` /// returns `Some(false)` fn apply<'a>( &self, cx: &MatchCheckCtxt<'a, 'tcx>, ty: Ty<'tcx>, pats: impl IntoIterator<Item = Pat<'tcx>>, ) -> Pat<'tcx> { let mut subpatterns = pats.into_iter(); let pat = match self { Single | Variant(_) => match ty.kind { ty::Adt(..) | ty::Tuple(..) => { let subpatterns = subpatterns .enumerate() .map(|(i, p)| FieldPat { field: Field::new(i), pattern: p }) .collect(); if let ty::Adt(adt, substs) = ty.kind { if adt.is_enum() { PatKind::Variant { adt_def: adt, substs, variant_index: self.variant_index_for_adt(cx, adt), subpatterns, } } else { PatKind::Leaf { subpatterns } } } else { PatKind::Leaf { subpatterns } } } ty::Ref(..) => PatKind::Deref { subpattern: subpatterns.nth(0).unwrap() }, ty::Slice(_) | ty::Array(..) => bug!("bad slice pattern {:?} {:?}", self, ty), _ => PatKind::Wild, }, Slice(slice) => match slice.pattern_kind() { FixedLen(_) => { PatKind::Slice { prefix: subpatterns.collect(), slice: None, suffix: vec![] } } VarLen(prefix, _) => { let mut prefix: Vec<_> = subpatterns.by_ref().take(prefix as usize).collect(); if slice.array_len.is_some() { // Improves diagnostics a bit: if the type is a known-size array, instead // of reporting `[x, _, .., _, y]`, we prefer to report `[x, .., y]`. // This is incorrect if the size is not known, since `[_, ..]` captures // arrays of lengths `>= 1` whereas `[..]` captures any length. while !prefix.is_empty() && prefix.last().unwrap().is_wildcard() { prefix.pop(); } } let suffix: Vec<_> = if slice.array_len.is_some() { // Same as above. subpatterns.skip_while(Pat::is_wildcard).collect() } else { subpatterns.collect() }; let wild = Pat::wildcard_from_ty(ty); PatKind::Slice { prefix, slice: Some(wild), suffix } } }, &ConstantValue(value) => PatKind::Constant { value }, &FloatRange(lo, hi, end) => PatKind::Range(PatRange { lo, hi, end }), IntRange(range) => return range.to_pat(cx.tcx), NonExhaustive => PatKind::Wild, }; Pat { ty, span: DUMMY_SP, kind: Box::new(pat) } } /// Like `apply`, but where all the subpatterns are wildcards `_`. fn apply_wildcards<'a>(&self, cx: &MatchCheckCtxt<'a, 'tcx>, ty: Ty<'tcx>) -> Pat<'tcx> { let subpatterns = self.wildcard_subpatterns(cx, ty).into_iter().rev(); self.apply(cx, ty, subpatterns) } } #[derive(Clone, Debug)] pub enum Usefulness<'tcx, 'p> { /// Carries a list of unreachable subpatterns. Used only in the presence of or-patterns. Useful(Vec<&'p Pat<'tcx>>), /// Carries a list of witnesses of non-exhaustiveness. UsefulWithWitness(Vec<Witness<'tcx>>), NotUseful, } impl<'tcx, 'p> Usefulness<'tcx, 'p> { fn new_useful(preference: WitnessPreference) -> Self { match preference { ConstructWitness => UsefulWithWitness(vec![Witness(vec![])]), LeaveOutWitness => Useful(vec![]), } } fn is_useful(&self) -> bool { match *self { NotUseful => false, _ => true, } } fn apply_constructor( self, cx: &MatchCheckCtxt<'_, 'tcx>, ctor: &Constructor<'tcx>, ty: Ty<'tcx>, ) -> Self { match self { UsefulWithWitness(witnesses) => UsefulWithWitness( witnesses .into_iter() .map(|witness| witness.apply_constructor(cx, &ctor, ty)) .collect(), ), x => x, } } fn apply_wildcard(self, ty: Ty<'tcx>) -> Self { match self { UsefulWithWitness(witnesses) => { let wild = Pat::wildcard_from_ty(ty); UsefulWithWitness( witnesses .into_iter() .map(|mut witness| { witness.0.push(wild.clone()); witness }) .collect(), ) } x => x, } } fn apply_missing_ctors( self, cx: &MatchCheckCtxt<'_, 'tcx>, ty: Ty<'tcx>, missing_ctors: &MissingConstructors<'tcx>, ) -> Self { match self { UsefulWithWitness(witnesses) => { let new_patterns: Vec<_> = missing_ctors.iter().map(|ctor| ctor.apply_wildcards(cx, ty)).collect(); // Add the new patterns to each witness UsefulWithWitness( witnesses .into_iter() .flat_map(|witness| { new_patterns.iter().map(move |pat| { let mut witness = witness.clone(); witness.0.push(pat.clone()); witness }) }) .collect(), ) } x => x, } } } #[derive(Copy, Clone, Debug)] pub enum WitnessPreference { ConstructWitness, LeaveOutWitness, } #[derive(Copy, Clone, Debug)] struct PatCtxt<'tcx> { ty: Ty<'tcx>, span: Span, } /// A witness of non-exhaustiveness for error reporting, represented /// as a list of patterns (in reverse order of construction) with /// wildcards inside to represent elements that can take any inhabitant /// of the type as a value. /// /// A witness against a list of patterns should have the same types /// and length as the pattern matched against. Because Rust `match` /// is always against a single pattern, at the end the witness will /// have length 1, but in the middle of the algorithm, it can contain /// multiple patterns. /// /// For example, if we are constructing a witness for the match against /// ``` /// struct Pair(Option<(u32, u32)>, bool); /// /// match (p: Pair) { /// Pair(None, _) => {} /// Pair(_, false) => {} /// } /// ``` /// /// We'll perform the following steps: /// 1. Start with an empty witness /// `Witness(vec![])` /// 2. Push a witness `Some(_)` against the `None` /// `Witness(vec![Some(_)])` /// 3. Push a witness `true` against the `false` /// `Witness(vec![Some(_), true])` /// 4. Apply the `Pair` constructor to the witnesses /// `Witness(vec![Pair(Some(_), true)])` /// /// The final `Pair(Some(_), true)` is then the resulting witness. #[derive(Clone, Debug)] pub struct Witness<'tcx>(Vec<Pat<'tcx>>); impl<'tcx> Witness<'tcx> { pub fn single_pattern(self) -> Pat<'tcx> { assert_eq!(self.0.len(), 1); self.0.into_iter().next().unwrap() } /// Constructs a partial witness for a pattern given a list of /// patterns expanded by the specialization step. /// /// When a pattern P is discovered to be useful, this function is used bottom-up /// to reconstruct a complete witness, e.g., a pattern P' that covers a subset /// of values, V, where each value in that set is not covered by any previously /// used patterns and is covered by the pattern P'. Examples: /// /// left_ty: tuple of 3 elements /// pats: [10, 20, _] => (10, 20, _) /// /// left_ty: struct X { a: (bool, &'static str), b: usize} /// pats: [(false, "foo"), 42] => X { a: (false, "foo"), b: 42 } fn apply_constructor<'a>( mut self, cx: &MatchCheckCtxt<'a, 'tcx>, ctor: &Constructor<'tcx>, ty: Ty<'tcx>, ) -> Self { let arity = ctor.arity(cx, ty); let pat = { let len = self.0.len() as u64; let pats = self.0.drain((len - arity) as usize..).rev(); ctor.apply(cx, ty, pats) }; self.0.push(pat); self } } /// This determines the set of all possible constructors of a pattern matching /// values of type `left_ty`. For vectors, this would normally be an infinite set /// but is instead bounded by the maximum fixed length of slice patterns in /// the column of patterns being analyzed. /// /// We make sure to omit constructors that are statically impossible. E.g., for /// `Option<!>`, we do not include `Some(_)` in the returned list of constructors. /// Invariant: this returns an empty `Vec` if and only if the type is uninhabited (as determined by /// `cx.is_uninhabited()`). fn all_constructors<'a, 'tcx>( cx: &mut MatchCheckCtxt<'a, 'tcx>, pcx: PatCtxt<'tcx>, ) -> Vec<Constructor<'tcx>> { debug!("all_constructors({:?})", pcx.ty); let make_range = |start, end| { IntRange( // `unwrap()` is ok because we know the type is an integer. IntRange::from_range(cx.tcx, start, end, pcx.ty, &RangeEnd::Included, pcx.span) .unwrap(), ) }; match pcx.ty.kind { ty::Bool => { [true, false].iter().map(|&b| ConstantValue(ty::Const::from_bool(cx.tcx, b))).collect() } ty::Array(ref sub_ty, len) if len.try_eval_usize(cx.tcx, cx.param_env).is_some() => { let len = len.eval_usize(cx.tcx, cx.param_env); if len != 0 && cx.is_uninhabited(sub_ty) { vec![] } else { vec![Slice(Slice { array_len: Some(len), kind: VarLen(0, 0) })] } } // Treat arrays of a constant but unknown length like slices. ty::Array(ref sub_ty, _) | ty::Slice(ref sub_ty) => { let kind = if cx.is_uninhabited(sub_ty) { FixedLen(0) } else { VarLen(0, 0) }; vec![Slice(Slice { array_len: None, kind })] } ty::Adt(def, substs) if def.is_enum() => { let ctors: Vec<_> = if cx.tcx.features().exhaustive_patterns { // If `exhaustive_patterns` is enabled, we exclude variants known to be // uninhabited. def.variants .iter() .filter(|v| { !v.uninhabited_from(cx.tcx, substs, def.adt_kind()) .contains(cx.tcx, cx.module) }) .map(|v| Variant(v.def_id)) .collect() } else { def.variants.iter().map(|v| Variant(v.def_id)).collect() }; // If the enum is declared as `#[non_exhaustive]`, we treat it as if it had an // additional "unknown" constructor. // There is no point in enumerating all possible variants, because the user can't // actually match against them all themselves. So we always return only the fictitious // constructor. // E.g., in an example like: // ``` // let err: io::ErrorKind = ...; // match err { // io::ErrorKind::NotFound => {}, // } // ``` // we don't want to show every possible IO error, but instead have only `_` as the // witness. let is_declared_nonexhaustive = cx.is_foreign_non_exhaustive_enum(pcx.ty); // If `exhaustive_patterns` is disabled and our scrutinee is an empty enum, we treat it // as though it had an "unknown" constructor to avoid exposing its emptyness. Note that // an empty match will still be considered exhaustive because that case is handled // separately in `check_match`. let is_secretly_empty = def.variants.is_empty() && !cx.tcx.features().exhaustive_patterns; if is_secretly_empty || is_declared_nonexhaustive { vec![NonExhaustive] } else { ctors } } ty::Char => { vec![ // The valid Unicode Scalar Value ranges. make_range('\u{0000}' as u128, '\u{D7FF}' as u128), make_range('\u{E000}' as u128, '\u{10FFFF}' as u128), ] } ty::Int(_) | ty::Uint(_) if pcx.ty.is_ptr_sized_integral() && !cx.tcx.features().precise_pointer_size_matching => { // `usize`/`isize` are not allowed to be matched exhaustively unless the // `precise_pointer_size_matching` feature is enabled. So we treat those types like // `#[non_exhaustive]` enums by returning a special unmatcheable constructor. vec![NonExhaustive] } ty::Int(ity) => { let bits = Integer::from_attr(&cx.tcx, SignedInt(ity)).size().bits() as u128; let min = 1u128 << (bits - 1); let max = min - 1; vec![make_range(min, max)] } ty::Uint(uty) => { let size = Integer::from_attr(&cx.tcx, UnsignedInt(uty)).size(); let max = truncate(u128::max_value(), size); vec![make_range(0, max)] } _ => { if cx.is_uninhabited(pcx.ty) { vec![] } else { vec![Single] } } } } /// An inclusive interval, used for precise integer exhaustiveness checking. /// `IntRange`s always store a contiguous range. This means that values are /// encoded such that `0` encodes the minimum value for the integer, /// regardless of the signedness. /// For example, the pattern `-128..=127i8` is encoded as `0..=255`. /// This makes comparisons and arithmetic on interval endpoints much more /// straightforward. See `signed_bias` for details. /// /// `IntRange` is never used to encode an empty range or a "range" that wraps /// around the (offset) space: i.e., `range.lo <= range.hi`. #[derive(Clone, Debug)] struct IntRange<'tcx> { pub range: RangeInclusive<u128>, pub ty: Ty<'tcx>, pub span: Span, } impl<'tcx> IntRange<'tcx> { #[inline] fn is_integral(ty: Ty<'_>) -> bool { match ty.kind { ty::Char | ty::Int(_) | ty::Uint(_) => true, _ => false, } } fn is_singleton(&self) -> bool { self.range.start() == self.range.end() } fn boundaries(&self) -> (u128, u128) { (*self.range.start(), *self.range.end()) } /// Don't treat `usize`/`isize` exhaustively unless the `precise_pointer_size_matching` feature /// is enabled. fn treat_exhaustively(&self, tcx: TyCtxt<'tcx>) -> bool { !self.ty.is_ptr_sized_integral() || tcx.features().precise_pointer_size_matching } #[inline] fn integral_size_and_signed_bias(tcx: TyCtxt<'tcx>, ty: Ty<'_>) -> Option<(Size, u128)> { match ty.kind { ty::Char => Some((Size::from_bytes(4), 0)), ty::Int(ity) => { let size = Integer::from_attr(&tcx, SignedInt(ity)).size(); Some((size, 1u128 << (size.bits() as u128 - 1))) } ty::Uint(uty) => Some((Integer::from_attr(&tcx, UnsignedInt(uty)).size(), 0)), _ => None, } } #[inline] fn from_const( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, value: &Const<'tcx>, span: Span, ) -> Option<IntRange<'tcx>> { if let Some((target_size, bias)) = Self::integral_size_and_signed_bias(tcx, value.ty) { let ty = value.ty; let val = if let ty::ConstKind::Value(ConstValue::Scalar(Scalar::Raw { data, size })) = value.val { // For this specific pattern we can skip a lot of effort and go // straight to the result, after doing a bit of checking. (We // could remove this branch and just use the next branch, which // is more general but much slower.) Scalar::<()>::check_raw(data, size, target_size); data } else if let Some(val) = value.try_eval_bits(tcx, param_env, ty) { // This is a more general form of the previous branch. val } else { return None; }; let val = val ^ bias; Some(IntRange { range: val..=val, ty, span }) } else { None } } #[inline] fn from_range( tcx: TyCtxt<'tcx>, lo: u128, hi: u128, ty: Ty<'tcx>, end: &RangeEnd, span: Span, ) -> Option<IntRange<'tcx>> { if Self::is_integral(ty) { // Perform a shift if the underlying types are signed, // which makes the interval arithmetic simpler. let bias = IntRange::signed_bias(tcx, ty); let (lo, hi) = (lo ^ bias, hi ^ bias); let offset = (*end == RangeEnd::Excluded) as u128; if lo > hi || (lo == hi && *end == RangeEnd::Excluded) { // This should have been caught earlier by E0030. bug!("malformed range pattern: {}..={}", lo, (hi - offset)); } Some(IntRange { range: lo..=(hi - offset), ty, span }) } else { None } } fn from_pat( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, pat: &Pat<'tcx>, ) -> Option<IntRange<'tcx>> { match pat_constructor(tcx, param_env, pat)? { IntRange(range) => Some(range), _ => None, } } // The return value of `signed_bias` should be XORed with an endpoint to encode/decode it. fn signed_bias(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> u128 { match ty.kind { ty::Int(ity) => { let bits = Integer::from_attr(&tcx, SignedInt(ity)).size().bits() as u128; 1u128 << (bits - 1) } _ => 0, } } /// Returns a collection of ranges that spans the values covered by `ranges`, subtracted /// by the values covered by `self`: i.e., `ranges \ self` (in set notation). fn subtract_from(&self, ranges: Vec<IntRange<'tcx>>) -> Vec<IntRange<'tcx>> { let mut remaining_ranges = vec![]; let ty = self.ty; let span = self.span; let (lo, hi) = self.boundaries(); for subrange in ranges { let (subrange_lo, subrange_hi) = subrange.range.into_inner(); if lo > subrange_hi || subrange_lo > hi { // The pattern doesn't intersect with the subrange at all, // so the subrange remains untouched. remaining_ranges.push(IntRange { range: subrange_lo..=subrange_hi, ty, span }); } else { if lo > subrange_lo { // The pattern intersects an upper section of the // subrange, so a lower section will remain. remaining_ranges.push(IntRange { range: subrange_lo..=(lo - 1), ty, span }); } if hi < subrange_hi { // The pattern intersects a lower section of the // subrange, so an upper section will remain. remaining_ranges.push(IntRange { range: (hi + 1)..=subrange_hi, ty, span }); } } } remaining_ranges } fn is_subrange(&self, other: &Self) -> bool { other.range.start() <= self.range.start() && self.range.end() <= other.range.end() } fn intersection(&self, tcx: TyCtxt<'tcx>, other: &Self) -> Option<Self> { let ty = self.ty; let (lo, hi) = self.boundaries(); let (other_lo, other_hi) = other.boundaries(); if self.treat_exhaustively(tcx) { if lo <= other_hi && other_lo <= hi { let span = other.span; Some(IntRange { range: max(lo, other_lo)..=min(hi, other_hi), ty, span }) } else { None } } else { // If the range should not be treated exhaustively, fallback to checking for inclusion. if self.is_subrange(other) { Some(self.clone()) } else { None } } } fn suspicious_intersection(&self, other: &Self) -> bool { // `false` in the following cases: // 1 ---- // 1 ---------- // 1 ---- // 1 ---- // 2 ---------- // 2 ---- // 2 ---- // 2 ---- // // The following are currently `false`, but could be `true` in the future (#64007): // 1 --------- // 1 --------- // 2 ---------- // 2 ---------- // // `true` in the following cases: // 1 ------- // 1 ------- // 2 -------- // 2 ------- let (lo, hi) = self.boundaries(); let (other_lo, other_hi) = other.boundaries(); (lo == other_hi || hi == other_lo) } fn to_pat(&self, tcx: TyCtxt<'tcx>) -> Pat<'tcx> { let (lo, hi) = self.boundaries(); let bias = IntRange::signed_bias(tcx, self.ty); let (lo, hi) = (lo ^ bias, hi ^ bias); let ty = ty::ParamEnv::empty().and(self.ty); let lo_const = ty::Const::from_bits(tcx, lo, ty); let hi_const = ty::Const::from_bits(tcx, hi, ty); let kind = if lo == hi { PatKind::Constant { value: lo_const } } else { PatKind::Range(PatRange { lo: lo_const, hi: hi_const, end: RangeEnd::Included }) }; // This is a brand new pattern, so we don't reuse `self.span`. Pat { ty: self.ty, span: DUMMY_SP, kind: Box::new(kind) } } } /// Ignore spans when comparing, they don't carry semantic information as they are only for lints. impl<'tcx> std::cmp::PartialEq for IntRange<'tcx> { fn eq(&self, other: &Self) -> bool { self.range == other.range && self.ty == other.ty } } // A struct to compute a set of constructors equivalent to `all_ctors \ used_ctors`. struct MissingConstructors<'tcx> { all_ctors: Vec<Constructor<'tcx>>, used_ctors: Vec<Constructor<'tcx>>, } impl<'tcx> MissingConstructors<'tcx> { fn new(all_ctors: Vec<Constructor<'tcx>>, used_ctors: Vec<Constructor<'tcx>>) -> Self { MissingConstructors { all_ctors, used_ctors } } fn into_inner(self) -> (Vec<Constructor<'tcx>>, Vec<Constructor<'tcx>>) { (self.all_ctors, self.used_ctors) } fn is_empty(&self) -> bool { self.iter().next().is_none() } /// Whether this contains all the constructors for the given type or only a /// subset. fn all_ctors_are_missing(&self) -> bool { self.used_ctors.is_empty() } /// Iterate over all_ctors \ used_ctors fn iter<'a>(&'a self) -> impl Iterator<Item = Constructor<'tcx>> + Captures<'a> { self.all_ctors.iter().flat_map(move |req_ctor| req_ctor.subtract_ctors(&self.used_ctors)) } } impl<'tcx> fmt::Debug for MissingConstructors<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let ctors: Vec<_> = self.iter().collect(); write!(f, "{:?}", ctors) } } /// Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html. /// The algorithm from the paper has been modified to correctly handle empty /// types. The changes are: /// (0) We don't exit early if the pattern matrix has zero rows. We just /// continue to recurse over columns. /// (1) all_constructors will only return constructors that are statically /// possible. E.g., it will only return `Ok` for `Result<T, !>`. /// /// This finds whether a (row) vector `v` of patterns is 'useful' in relation /// to a set of such vectors `m` - this is defined as there being a set of /// inputs that will match `v` but not any of the sets in `m`. /// /// All the patterns at each column of the `matrix ++ v` matrix must /// have the same type, except that wildcard (PatKind::Wild) patterns /// with type `TyErr` are also allowed, even if the "type of the column" /// is not `TyErr`. That is used to represent private fields, as using their /// real type would assert that they are inhabited. /// /// This is used both for reachability checking (if a pattern isn't useful in /// relation to preceding patterns, it is not reachable) and exhaustiveness /// checking (if a wildcard pattern is useful in relation to a matrix, the /// matrix isn't exhaustive). pub fn is_useful<'p, 'tcx>( cx: &mut MatchCheckCtxt<'p, 'tcx>, matrix: &Matrix<'p, 'tcx>, v: &PatStack<'p, 'tcx>, witness_preference: WitnessPreference, hir_id: HirId, is_top_level: bool, ) -> Usefulness<'tcx, 'p> { let &Matrix(ref rows) = matrix; debug!("is_useful({:#?}, {:#?})", matrix, v); // The base case. We are pattern-matching on () and the return value is // based on whether our matrix has a row or not. // NOTE: This could potentially be optimized by checking rows.is_empty() // first and then, if v is non-empty, the return value is based on whether // the type of the tuple we're checking is inhabited or not. if v.is_empty() { return if rows.is_empty() { Usefulness::new_useful(witness_preference) } else { NotUseful }; }; assert!(rows.iter().all(|r| r.len() == v.len())); // If the first pattern is an or-pattern, expand it. if let Some(vs) = v.expand_or_pat() { // We need to push the already-seen patterns into the matrix in order to detect redundant // branches like `Some(_) | Some(0)`. We also keep track of the unreachable subpatterns. let mut matrix = matrix.clone(); let mut unreachable_pats = Vec::new(); let mut any_is_useful = false; for v in vs { let res = is_useful(cx, &matrix, &v, witness_preference, hir_id, false); match res { Useful(pats) => { any_is_useful = true; unreachable_pats.extend(pats); } NotUseful => unreachable_pats.push(v.head()), UsefulWithWitness(_) => { bug!("Encountered or-pat in `v` during exhaustiveness checking") } } matrix.push(v); } return if any_is_useful { Useful(unreachable_pats) } else { NotUseful }; } let (ty, span) = matrix .heads() .map(|r| (r.ty, r.span)) .find(|(ty, _)| !ty.references_error()) .unwrap_or((v.head().ty, v.head().span)); let pcx = PatCtxt { // TyErr is used to represent the type of wildcard patterns matching // against inaccessible (private) fields of structs, so that we won't // be able to observe whether the types of the struct's fields are // inhabited. // // If the field is truly inaccessible, then all the patterns // matching against it must be wildcard patterns, so its type // does not matter. // // However, if we are matching against non-wildcard patterns, we // need to know the real type of the field so we can specialize // against it. This primarily occurs through constants - they // can include contents for fields that are inaccessible at the // location of the match. In that case, the field's type is // inhabited - by the constant - so we can just use it. // // FIXME: this might lead to "unstable" behavior with macro hygiene // introducing uninhabited patterns for inaccessible fields. We // need to figure out how to model that. ty, span, }; debug!("is_useful_expand_first_col: pcx={:#?}, expanding {:#?}", pcx, v.head()); if let Some(constructor) = pat_constructor(cx.tcx, cx.param_env, v.head()) { debug!("is_useful - expanding constructor: {:#?}", constructor); split_grouped_constructors( cx.tcx, cx.param_env, pcx, vec![constructor], matrix, pcx.span, Some(hir_id), ) .into_iter() .map(|c| is_useful_specialized(cx, matrix, v, c, pcx.ty, witness_preference, hir_id)) .find(|result| result.is_useful()) .unwrap_or(NotUseful) } else { debug!("is_useful - expanding wildcard"); let used_ctors: Vec<Constructor<'_>> = matrix.heads().filter_map(|p| pat_constructor(cx.tcx, cx.param_env, p)).collect(); debug!("used_ctors = {:#?}", used_ctors); // `all_ctors` are all the constructors for the given type, which // should all be represented (or caught with the wild pattern `_`). let all_ctors = all_constructors(cx, pcx); debug!("all_ctors = {:#?}", all_ctors); // `missing_ctors` is the set of constructors from the same type as the // first column of `matrix` that are matched only by wildcard patterns // from the first column. // // Therefore, if there is some pattern that is unmatched by `matrix`, // it will still be unmatched if the first constructor is replaced by // any of the constructors in `missing_ctors` // Missing constructors are those that are not matched by any non-wildcard patterns in the // current column. We only fully construct them on-demand, because they're rarely used and // can be big. let missing_ctors = MissingConstructors::new(all_ctors, used_ctors); debug!("missing_ctors.empty()={:#?}", missing_ctors.is_empty(),); if missing_ctors.is_empty() { let (all_ctors, _) = missing_ctors.into_inner(); split_grouped_constructors(cx.tcx, cx.param_env, pcx, all_ctors, matrix, DUMMY_SP, None) .into_iter() .map(|c| { is_useful_specialized(cx, matrix, v, c, pcx.ty, witness_preference, hir_id) }) .find(|result| result.is_useful()) .unwrap_or(NotUseful) } else { let matrix = matrix.specialize_wildcard(); let v = v.to_tail(); let usefulness = is_useful(cx, &matrix, &v, witness_preference, hir_id, false); // In this case, there's at least one "free" // constructor that is only matched against by // wildcard patterns. // // There are 2 ways we can report a witness here. // Commonly, we can report all the "free" // constructors as witnesses, e.g., if we have: // // ``` // enum Direction { N, S, E, W } // let Direction::N = ...; // ``` // // we can report 3 witnesses: `S`, `E`, and `W`. // // However, there is a case where we don't want // to do this and instead report a single `_` witness: // if the user didn't actually specify a constructor // in this arm, e.g., in // ``` // let x: (Direction, Direction, bool) = ...; // let (_, _, false) = x; // ``` // we don't want to show all 16 possible witnesses // `(<direction-1>, <direction-2>, true)` - we are // satisfied with `(_, _, true)`. In this case, // `used_ctors` is empty. // The exception is: if we are at the top-level, for example in an empty match, we // sometimes prefer reporting the list of constructors instead of just `_`. let report_ctors_rather_than_wildcard = is_top_level && !IntRange::is_integral(pcx.ty); if missing_ctors.all_ctors_are_missing() && !report_ctors_rather_than_wildcard { // All constructors are unused. Add a wild pattern // rather than each individual constructor. usefulness.apply_wildcard(pcx.ty) } else { // Construct for each missing constructor a "wild" version of this // constructor, that matches everything that can be built with // it. For example, if `ctor` is a `Constructor::Variant` for // `Option::Some`, we get the pattern `Some(_)`. usefulness.apply_missing_ctors(cx, pcx.ty, &missing_ctors) } } } } /// A shorthand for the `U(S(c, P), S(c, q))` operation from the paper. I.e., `is_useful` applied /// to the specialised version of both the pattern matrix `P` and the new pattern `q`. fn is_useful_specialized<'p, 'tcx>( cx: &mut MatchCheckCtxt<'p, 'tcx>, matrix: &Matrix<'p, 'tcx>, v: &PatStack<'p, 'tcx>, ctor: Constructor<'tcx>, lty: Ty<'tcx>, witness_preference: WitnessPreference, hir_id: HirId, ) -> Usefulness<'tcx, 'p> { debug!("is_useful_specialized({:#?}, {:#?}, {:?})", v, ctor, lty); let ctor_wild_subpatterns = cx.pattern_arena.alloc_from_iter(ctor.wildcard_subpatterns(cx, lty)); let matrix = matrix.specialize_constructor(cx, &ctor, ctor_wild_subpatterns); v.specialize_constructor(cx, &ctor, ctor_wild_subpatterns) .map(|v| is_useful(cx, &matrix, &v, witness_preference, hir_id, false)) .map(|u| u.apply_constructor(cx, &ctor, lty)) .unwrap_or(NotUseful) } /// Determines the constructor that the given pattern can be specialized to. /// Returns `None` in case of a catch-all, which can't be specialized. fn pat_constructor<'tcx>( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, pat: &Pat<'tcx>, ) -> Option<Constructor<'tcx>> { match *pat.kind { PatKind::AscribeUserType { .. } => bug!(), // Handled by `expand_pattern` PatKind::Binding { .. } | PatKind::Wild => None, PatKind::Leaf { .. } | PatKind::Deref { .. } => Some(Single), PatKind::Variant { adt_def, variant_index, .. } => { Some(Variant(adt_def.variants[variant_index].def_id)) } PatKind::Constant { value } => { if let Some(int_range) = IntRange::from_const(tcx, param_env, value, pat.span) { Some(IntRange(int_range)) } else { match (value.val, &value.ty.kind) { (_, ty::Array(_, n)) => { let len = n.eval_usize(tcx, param_env); Some(Slice(Slice { array_len: Some(len), kind: FixedLen(len) })) } (ty::ConstKind::Value(ConstValue::Slice { start, end, .. }), ty::Slice(_)) => { let len = (end - start) as u64; Some(Slice(Slice { array_len: None, kind: FixedLen(len) })) } // FIXME(oli-obk): implement `deref` for `ConstValue` // (ty::ConstKind::Value(ConstValue::ByRef { .. }), ty::Slice(_)) => { ... } _ => Some(ConstantValue(value)), } } } PatKind::Range(PatRange { lo, hi, end }) => { let ty = lo.ty; if let Some(int_range) = IntRange::from_range( tcx, lo.eval_bits(tcx, param_env, lo.ty), hi.eval_bits(tcx, param_env, hi.ty), ty, &end, pat.span, ) { Some(IntRange(int_range)) } else { Some(FloatRange(lo, hi, end)) } } PatKind::Array { ref prefix, ref slice, ref suffix } | PatKind::Slice { ref prefix, ref slice, ref suffix } => { let array_len = match pat.ty.kind { ty::Array(_, length) => Some(length.eval_usize(tcx, param_env)), ty::Slice(_) => None, _ => span_bug!(pat.span, "bad ty {:?} for slice pattern", pat.ty), }; let prefix = prefix.len() as u64; let suffix = suffix.len() as u64; let kind = if slice.is_some() { VarLen(prefix, suffix) } else { FixedLen(prefix + suffix) }; Some(Slice(Slice { array_len, kind })) } PatKind::Or { .. } => bug!("Or-pattern should have been expanded earlier on."), } } // checks whether a constant is equal to a user-written slice pattern. Only supports byte slices, // meaning all other types will compare unequal and thus equal patterns often do not cause the // second pattern to lint about unreachable match arms. fn slice_pat_covered_by_const<'tcx>( tcx: TyCtxt<'tcx>, _span: Span, const_val: &'tcx ty::Const<'tcx>, prefix: &[Pat<'tcx>], slice: &Option<Pat<'tcx>>, suffix: &[Pat<'tcx>], param_env: ty::ParamEnv<'tcx>, ) -> Result<bool, ErrorReported> { let const_val_val = if let ty::ConstKind::Value(val) = const_val.val { val } else { bug!( "slice_pat_covered_by_const: {:#?}, {:#?}, {:#?}, {:#?}", const_val, prefix, slice, suffix, ) }; let data: &[u8] = match (const_val_val, &const_val.ty.kind) { (ConstValue::ByRef { offset, alloc, .. }, ty::Array(t, n)) => { assert_eq!(*t, tcx.types.u8); let n = n.eval_usize(tcx, param_env); let ptr = Pointer::new(AllocId(0), offset); alloc.get_bytes(&tcx, ptr, Size::from_bytes(n)).unwrap() } (ConstValue::Slice { data, start, end }, ty::Slice(t)) => { assert_eq!(*t, tcx.types.u8); let ptr = Pointer::new(AllocId(0), Size::from_bytes(start as u64)); data.get_bytes(&tcx, ptr, Size::from_bytes((end - start) as u64)).unwrap() } // FIXME(oli-obk): create a way to extract fat pointers from ByRef (_, ty::Slice(_)) => return Ok(false), _ => bug!( "slice_pat_covered_by_const: {:#?}, {:#?}, {:#?}, {:#?}", const_val, prefix, slice, suffix, ), }; let pat_len = prefix.len() + suffix.len(); if data.len() < pat_len || (slice.is_none() && data.len() > pat_len) { return Ok(false); } for (ch, pat) in data[..prefix.len()] .iter() .zip(prefix) .chain(data[data.len() - suffix.len()..].iter().zip(suffix)) { match pat.kind { box PatKind::Constant { value } => { let b = value.eval_bits(tcx, param_env, pat.ty); assert_eq!(b as u8 as u128, b); if b as u8 != *ch { return Ok(false); } } _ => {} } } Ok(true) } /// For exhaustive integer matching, some constructors are grouped within other constructors /// (namely integer typed values are grouped within ranges). However, when specialising these /// constructors, we want to be specialising for the underlying constructors (the integers), not /// the groups (the ranges). Thus we need to split the groups up. Splitting them up naïvely would /// mean creating a separate constructor for every single value in the range, which is clearly /// impractical. However, observe that for some ranges of integers, the specialisation will be /// identical across all values in that range (i.e., there are equivalence classes of ranges of /// constructors based on their `is_useful_specialized` outcome). These classes are grouped by /// the patterns that apply to them (in the matrix `P`). We can split the range whenever the /// patterns that apply to that range (specifically: the patterns that *intersect* with that range) /// change. /// Our solution, therefore, is to split the range constructor into subranges at every single point /// the group of intersecting patterns changes (using the method described below). /// And voilà! We're testing precisely those ranges that we need to, without any exhaustive matching /// on actual integers. The nice thing about this is that the number of subranges is linear in the /// number of rows in the matrix (i.e., the number of cases in the `match` statement), so we don't /// need to be worried about matching over gargantuan ranges. /// /// Essentially, given the first column of a matrix representing ranges, looking like the following: /// /// |------| |----------| |-------| || /// |-------| |-------| |----| || /// |---------| /// /// We split the ranges up into equivalence classes so the ranges are no longer overlapping: /// /// |--|--|||-||||--||---|||-------| |-|||| || /// /// The logic for determining how to split the ranges is fairly straightforward: we calculate /// boundaries for each interval range, sort them, then create constructors for each new interval /// between every pair of boundary points. (This essentially sums up to performing the intuitive /// merging operation depicted above.) /// /// `hir_id` is `None` when we're evaluating the wildcard pattern, do not lint for overlapping in /// ranges that case. /// /// This also splits variable-length slices into fixed-length slices. fn split_grouped_constructors<'p, 'tcx>( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, pcx: PatCtxt<'tcx>, ctors: Vec<Constructor<'tcx>>, matrix: &Matrix<'p, 'tcx>, span: Span, hir_id: Option<HirId>, ) -> Vec<Constructor<'tcx>> { let ty = pcx.ty; let mut split_ctors = Vec::with_capacity(ctors.len()); debug!("split_grouped_constructors({:#?}, {:#?})", matrix, ctors); for ctor in ctors.into_iter() { match ctor { IntRange(ctor_range) if ctor_range.treat_exhaustively(tcx) => { // Fast-track if the range is trivial. In particular, don't do the overlapping // ranges check. if ctor_range.is_singleton() { split_ctors.push(IntRange(ctor_range)); continue; } /// Represents a border between 2 integers. Because the intervals spanning borders /// must be able to cover every integer, we need to be able to represent /// 2^128 + 1 such borders. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] enum Border { JustBefore(u128), AfterMax, } // A function for extracting the borders of an integer interval. fn range_borders(r: IntRange<'_>) -> impl Iterator<Item = Border> { let (lo, hi) = r.range.into_inner(); let from = Border::JustBefore(lo); let to = match hi.checked_add(1) { Some(m) => Border::JustBefore(m), None => Border::AfterMax, }; vec![from, to].into_iter() } // Collect the span and range of all the intersecting ranges to lint on likely // incorrect range patterns. (#63987) let mut overlaps = vec![]; // `borders` is the set of borders between equivalence classes: each equivalence // class lies between 2 borders. let row_borders = matrix .0 .iter() .flat_map(|row| { IntRange::from_pat(tcx, param_env, row.head()).map(|r| (r, row.len())) }) .flat_map(|(range, row_len)| { let intersection = ctor_range.intersection(tcx, &range); let should_lint = ctor_range.suspicious_intersection(&range); if let (Some(range), 1, true) = (&intersection, row_len, should_lint) { // FIXME: for now, only check for overlapping ranges on simple range // patterns. Otherwise with the current logic the following is detected // as overlapping: // match (10u8, true) { // (0 ..= 125, false) => {} // (126 ..= 255, false) => {} // (0 ..= 255, true) => {} // } overlaps.push(range.clone()); } intersection }) .flat_map(|range| range_borders(range)); let ctor_borders = range_borders(ctor_range.clone()); let mut borders: Vec<_> = row_borders.chain(ctor_borders).collect(); borders.sort_unstable(); lint_overlapping_patterns(tcx, hir_id, ctor_range, ty, overlaps); // We're going to iterate through every adjacent pair of borders, making sure that // each represents an interval of nonnegative length, and convert each such // interval into a constructor. split_ctors.extend( borders .windows(2) .filter_map(|window| match (window[0], window[1]) { (Border::JustBefore(n), Border::JustBefore(m)) => { if n < m { Some(IntRange { range: n..=(m - 1), ty, span }) } else { None } } (Border::JustBefore(n), Border::AfterMax) => { Some(IntRange { range: n..=u128::MAX, ty, span }) } (Border::AfterMax, _) => None, }) .map(IntRange), ); } Slice(Slice { array_len, kind: VarLen(self_prefix, self_suffix) }) => { // The exhaustiveness-checking paper does not include any details on // checking variable-length slice patterns. However, they are matched // by an infinite collection of fixed-length array patterns. // // Checking the infinite set directly would take an infinite amount // of time. However, it turns out that for each finite set of // patterns `P`, all sufficiently large array lengths are equivalent: // // Each slice `s` with a "sufficiently-large" length `l ≥ L` that applies // to exactly the subset `Pₜ` of `P` can be transformed to a slice // `sₘ` for each sufficiently-large length `m` that applies to exactly // the same subset of `P`. // // Because of that, each witness for reachability-checking from one // of the sufficiently-large lengths can be transformed to an // equally-valid witness from any other length, so we only have // to check slice lengths from the "minimal sufficiently-large length" // and below. // // Note that the fact that there is a *single* `sₘ` for each `m` // not depending on the specific pattern in `P` is important: if // you look at the pair of patterns // `[true, ..]` // `[.., false]` // Then any slice of length ≥1 that matches one of these two // patterns can be trivially turned to a slice of any // other length ≥1 that matches them and vice-versa - for // but the slice from length 2 `[false, true]` that matches neither // of these patterns can't be turned to a slice from length 1 that // matches neither of these patterns, so we have to consider // slices from length 2 there. // // Now, to see that that length exists and find it, observe that slice // patterns are either "fixed-length" patterns (`[_, _, _]`) or // "variable-length" patterns (`[_, .., _]`). // // For fixed-length patterns, all slices with lengths *longer* than // the pattern's length have the same outcome (of not matching), so // as long as `L` is greater than the pattern's length we can pick // any `sₘ` from that length and get the same result. // // For variable-length patterns, the situation is more complicated, // because as seen above the precise value of `sₘ` matters. // // However, for each variable-length pattern `p` with a prefix of length // `plₚ` and suffix of length `slₚ`, only the first `plₚ` and the last // `slₚ` elements are examined. // // Therefore, as long as `L` is positive (to avoid concerns about empty // types), all elements after the maximum prefix length and before // the maximum suffix length are not examined by any variable-length // pattern, and therefore can be added/removed without affecting // them - creating equivalent patterns from any sufficiently-large // length. // // Of course, if fixed-length patterns exist, we must be sure // that our length is large enough to miss them all, so // we can pick `L = max(max(FIXED_LEN)+1, max(PREFIX_LEN) + max(SUFFIX_LEN))` // // for example, with the above pair of patterns, all elements // but the first and last can be added/removed, so any // witness of length ≥2 (say, `[false, false, true]`) can be // turned to a witness from any other length ≥2. let mut max_prefix_len = self_prefix; let mut max_suffix_len = self_suffix; let mut max_fixed_len = 0; let head_ctors = matrix.heads().filter_map(|pat| pat_constructor(tcx, param_env, pat)); for ctor in head_ctors { match ctor { Slice(slice) => match slice.pattern_kind() { FixedLen(len) => { max_fixed_len = cmp::max(max_fixed_len, len); } VarLen(prefix, suffix) => { max_prefix_len = cmp::max(max_prefix_len, prefix); max_suffix_len = cmp::max(max_suffix_len, suffix); } }, _ => {} } } // For diagnostics, we keep the prefix and suffix lengths separate, so in the case // where `max_fixed_len + 1` is the largest, we adapt `max_prefix_len` accordingly, // so that `L = max_prefix_len + max_suffix_len`. if max_fixed_len + 1 >= max_prefix_len + max_suffix_len { // The subtraction can't overflow thanks to the above check. // The new `max_prefix_len` is also guaranteed to be larger than its previous // value. max_prefix_len = max_fixed_len + 1 - max_suffix_len; } match array_len { Some(len) => { let kind = if max_prefix_len + max_suffix_len < len { VarLen(max_prefix_len, max_suffix_len) } else { FixedLen(len) }; split_ctors.push(Slice(Slice { array_len, kind })); } None => { // `ctor` originally covered the range `(self_prefix + // self_suffix..infinity)`. We now split it into two: lengths smaller than // `max_prefix_len + max_suffix_len` are treated independently as // fixed-lengths slices, and lengths above are captured by a final VarLen // constructor. split_ctors.extend( (self_prefix + self_suffix..max_prefix_len + max_suffix_len) .map(|len| Slice(Slice { array_len, kind: FixedLen(len) })), ); split_ctors.push(Slice(Slice { array_len, kind: VarLen(max_prefix_len, max_suffix_len), })); } } } // Any other constructor can be used unchanged. _ => split_ctors.push(ctor), } } debug!("split_grouped_constructors(..)={:#?}", split_ctors); split_ctors } fn lint_overlapping_patterns( tcx: TyCtxt<'tcx>, hir_id: Option<HirId>, ctor_range: IntRange<'tcx>, ty: Ty<'tcx>, overlaps: Vec<IntRange<'tcx>>, ) { if let (true, Some(hir_id)) = (!overlaps.is_empty(), hir_id) { let mut err = tcx.struct_span_lint_hir( lint::builtin::OVERLAPPING_PATTERNS, hir_id, ctor_range.span, "multiple patterns covering the same range", ); err.span_label(ctor_range.span, "overlapping patterns"); for int_range in overlaps { // Use the real type for user display of the ranges: err.span_label( int_range.span, &format!( "this range overlaps on `{}`", IntRange { range: int_range.range, ty, span: DUMMY_SP }.to_pat(tcx), ), ); } err.emit(); } } fn constructor_covered_by_range<'tcx>( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, ctor: &Constructor<'tcx>, pat: &Pat<'tcx>, ) -> Option<()> { if let Single = ctor { return Some(()); } let (pat_from, pat_to, pat_end, ty) = match *pat.kind { PatKind::Constant { value } => (value, value, RangeEnd::Included, value.ty), PatKind::Range(PatRange { lo, hi, end }) => (lo, hi, end, lo.ty), _ => bug!("`constructor_covered_by_range` called with {:?}", pat), }; let (ctor_from, ctor_to, ctor_end) = match *ctor { ConstantValue(value) => (value, value, RangeEnd::Included), FloatRange(from, to, ctor_end) => (from, to, ctor_end), _ => bug!("`constructor_covered_by_range` called with {:?}", ctor), }; trace!("constructor_covered_by_range {:#?}, {:#?}, {:#?}, {}", ctor, pat_from, pat_to, ty); let to = compare_const_vals(tcx, ctor_to, pat_to, param_env, ty)?; let from = compare_const_vals(tcx, ctor_from, pat_from, param_env, ty)?; let intersects = (from == Ordering::Greater || from == Ordering::Equal) && (to == Ordering::Less || (pat_end == ctor_end && to == Ordering::Equal)); if intersects { Some(()) } else { None } } fn patterns_for_variant<'p, 'tcx>( cx: &mut MatchCheckCtxt<'p, 'tcx>, subpatterns: &'p [FieldPat<'tcx>], ctor_wild_subpatterns: &'p [Pat<'tcx>], is_non_exhaustive: bool, ) -> PatStack<'p, 'tcx> { let mut result: SmallVec<_> = ctor_wild_subpatterns.iter().collect(); for subpat in subpatterns { if !is_non_exhaustive || !cx.is_uninhabited(subpat.pattern.ty) { result[subpat.field.index()] = &subpat.pattern; } } debug!( "patterns_for_variant({:#?}, {:#?}) = {:#?}", subpatterns, ctor_wild_subpatterns, result ); PatStack::from_vec(result) } /// This is the main specialization step. It expands the pattern /// into `arity` patterns based on the constructor. For most patterns, the step is trivial, /// for instance tuple patterns are flattened and box patterns expand into their inner pattern. /// Returns `None` if the pattern does not have the given constructor. /// /// OTOH, slice patterns with a subslice pattern (tail @ ..) can be expanded into multiple /// different patterns. /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing /// fields filled with wild patterns. fn specialize_one_pattern<'p, 'tcx>( cx: &mut MatchCheckCtxt<'p, 'tcx>, pat: &'p Pat<'tcx>, constructor: &Constructor<'tcx>, ctor_wild_subpatterns: &'p [Pat<'tcx>], ) -> Option<PatStack<'p, 'tcx>> { if let NonExhaustive = constructor { // Only a wildcard pattern can match the special extra constructor return if pat.is_wildcard() { Some(PatStack::default()) } else { None }; } let result = match *pat.kind { PatKind::AscribeUserType { .. } => bug!(), // Handled by `expand_pattern` PatKind::Binding { .. } | PatKind::Wild => Some(ctor_wild_subpatterns.iter().collect()), PatKind::Variant { adt_def, variant_index, ref subpatterns, .. } => { let ref variant = adt_def.variants[variant_index]; let is_non_exhaustive = cx.is_foreign_non_exhaustive_variant(pat.ty, variant); Some(Variant(variant.def_id)) .filter(|variant_constructor| variant_constructor == constructor) .map(|_| { patterns_for_variant(cx, subpatterns, ctor_wild_subpatterns, is_non_exhaustive) }) } PatKind::Leaf { ref subpatterns } => { Some(patterns_for_variant(cx, subpatterns, ctor_wild_subpatterns, false)) } PatKind::Deref { ref subpattern } => Some(PatStack::from_pattern(subpattern)), PatKind::Constant { value } if constructor.is_slice() => { // We extract an `Option` for the pointer because slices of zero // elements don't necessarily point to memory, they are usually // just integers. The only time they should be pointing to memory // is when they are subslices of nonzero slices. let (alloc, offset, n, ty) = match value.ty.kind { ty::Array(t, n) => { let n = n.eval_usize(cx.tcx, cx.param_env); // Shortcut for `n == 0` where no matter what `alloc` and `offset` we produce, // the result would be exactly what we early return here. if n == 0 { if ctor_wild_subpatterns.len() as u64 == 0 { return Some(PatStack::from_slice(&[])); } else { return None; } } match value.val { ty::ConstKind::Value(ConstValue::ByRef { offset, alloc, .. }) => { (Cow::Borrowed(alloc), offset, n, t) } _ => span_bug!(pat.span, "array pattern is {:?}", value,), } } ty::Slice(t) => { match value.val { ty::ConstKind::Value(ConstValue::Slice { data, start, end }) => { let offset = Size::from_bytes(start as u64); let n = (end - start) as u64; (Cow::Borrowed(data), offset, n, t) } ty::ConstKind::Value(ConstValue::ByRef { .. }) => { // FIXME(oli-obk): implement `deref` for `ConstValue` return None; } _ => span_bug!( pat.span, "slice pattern constant must be scalar pair but is {:?}", value, ), } } _ => span_bug!( pat.span, "unexpected const-val {:?} with ctor {:?}", value, constructor, ), }; if ctor_wild_subpatterns.len() as u64 == n { // convert a constant slice/array pattern to a list of patterns. let layout = cx.tcx.layout_of(cx.param_env.and(ty)).ok()?; let ptr = Pointer::new(AllocId(0), offset); (0..n) .map(|i| { let ptr = ptr.offset(layout.size * i, &cx.tcx).ok()?; let scalar = alloc.read_scalar(&cx.tcx, ptr, layout.size).ok()?; let scalar = scalar.not_undef().ok()?; let value = ty::Const::from_scalar(cx.tcx, scalar, ty); let pattern = Pat { ty, span: pat.span, kind: box PatKind::Constant { value } }; Some(&*cx.pattern_arena.alloc(pattern)) }) .collect() } else { None } } PatKind::Constant { .. } | PatKind::Range { .. } => { // If the constructor is a: // - Single value: add a row if the pattern contains the constructor. // - Range: add a row if the constructor intersects the pattern. if let IntRange(ctor) = constructor { match IntRange::from_pat(cx.tcx, cx.param_env, pat) { Some(pat) => ctor.intersection(cx.tcx, &pat).map(|_| { // Constructor splitting should ensure that all intersections we encounter // are actually inclusions. assert!(ctor.is_subrange(&pat)); PatStack::default() }), _ => None, } } else { // Fallback for non-ranges and ranges that involve // floating-point numbers, which are not conveniently handled // by `IntRange`. For these cases, the constructor may not be a // range so intersection actually devolves into being covered // by the pattern. constructor_covered_by_range(cx.tcx, cx.param_env, constructor, pat) .map(|()| PatStack::default()) } } PatKind::Array { ref prefix, ref slice, ref suffix } | PatKind::Slice { ref prefix, ref slice, ref suffix } => match *constructor { Slice(_) => { let pat_len = prefix.len() + suffix.len(); if let Some(slice_count) = ctor_wild_subpatterns.len().checked_sub(pat_len) { if slice_count == 0 || slice.is_some() { Some( prefix .iter() .chain( ctor_wild_subpatterns .iter() .skip(prefix.len()) .take(slice_count) .chain(suffix.iter()), ) .collect(), ) } else { None } } else { None } } ConstantValue(cv) => { match slice_pat_covered_by_const( cx.tcx, pat.span, cv, prefix, slice, suffix, cx.param_env, ) { Ok(true) => Some(PatStack::default()), Ok(false) => None, Err(ErrorReported) => None, } } _ => span_bug!(pat.span, "unexpected ctor {:?} for slice pat", constructor), }, PatKind::Or { .. } => bug!("Or-pattern should have been expanded earlier on."), }; debug!("specialize({:#?}, {:#?}) = {:#?}", pat, ctor_wild_subpatterns, result); result }
42.942492
100
0.519241
7280ebfed3b247c06938cc763f3a34e566cab80e
52,361
#![doc = "generated by AutoRust"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] #![allow(clippy::redundant_clone)] use super::models; #[derive(Clone)] pub struct Client { endpoint: String, credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>, scopes: Vec<String>, pipeline: azure_core::Pipeline, } #[derive(Clone)] pub struct ClientBuilder { credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>, endpoint: Option<String>, scopes: Option<Vec<String>>, } pub const DEFAULT_ENDPOINT: &str = azure_core::resource_manager_endpoint::AZURE_PUBLIC_CLOUD; impl ClientBuilder { pub fn new(credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>) -> Self { Self { credential, endpoint: None, scopes: None, } } pub fn endpoint(mut self, endpoint: impl Into<String>) -> Self { self.endpoint = Some(endpoint.into()); self } pub fn scopes(mut self, scopes: &[&str]) -> Self { self.scopes = Some(scopes.iter().map(|scope| (*scope).to_owned()).collect()); self } pub fn build(self) -> Client { let endpoint = self.endpoint.unwrap_or_else(|| DEFAULT_ENDPOINT.to_owned()); let scopes = self.scopes.unwrap_or_else(|| vec![format!("{}/", endpoint)]); Client::new(endpoint, self.credential, scopes) } } impl Client { pub(crate) fn endpoint(&self) -> &str { self.endpoint.as_str() } pub(crate) fn token_credential(&self) -> &dyn azure_core::auth::TokenCredential { self.credential.as_ref() } pub(crate) fn scopes(&self) -> Vec<&str> { self.scopes.iter().map(String::as_str).collect() } pub(crate) async fn send(&self, request: impl Into<azure_core::Request>) -> azure_core::error::Result<azure_core::Response> { let mut context = azure_core::Context::default(); let mut request = request.into(); self.pipeline.send(&mut context, &mut request).await } pub fn new( endpoint: impl Into<String>, credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>, scopes: Vec<String>, ) -> Self { let endpoint = endpoint.into(); let pipeline = azure_core::Pipeline::new( option_env!("CARGO_PKG_NAME"), option_env!("CARGO_PKG_VERSION"), azure_core::ClientOptions::default(), Vec::new(), Vec::new(), ); Self { endpoint, credential, scopes, pipeline, } } pub fn attestation_providers(&self) -> attestation_providers::Client { attestation_providers::Client(self.clone()) } pub fn operations(&self) -> operations::Client { operations::Client(self.clone()) } pub fn private_endpoint_connections(&self) -> private_endpoint_connections::Client { private_endpoint_connections::Client(self.clone()) } } pub mod operations { use super::models; pub struct Client(pub(crate) super::Client); impl Client { pub fn list(&self) -> list::Builder { list::Builder { client: self.0.clone() } } } pub mod list { use super::models; use azure_core::error::ResultExt; type Response = models::OperationList; #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, azure_core::error::Result<Response>> { Box::pin({ let this = self.clone(); async move { let url_str = &format!("{}/providers/Microsoft.Attestation/operations", this.client.endpoint(),); let mut url = url::Url::parse(url_str).context(azure_core::error::ErrorKind::DataConversion, "parse url")?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = this.client.token_credential(); let token_response = credential .get_token(&this.client.scopes().join(" ")) .await .context(azure_core::error::ErrorKind::Other, "get bearer token")?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", "2020-10-01"); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .context(azure_core::error::ErrorKind::Other, "build request")?; let rsp = this .client .send(req) .await .context(azure_core::error::ErrorKind::Io, "execute request")?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await?; let rsp_value: models::OperationList = serde_json::from_slice(&rsp_body)?; Ok(rsp_value) } status_code => Err(azure_core::error::Error::from(azure_core::error::ErrorKind::HttpResponse { status: status_code.as_u16(), error_code: None, })), } } }) } } } } pub mod attestation_providers { use super::models; pub struct Client(pub(crate) super::Client); impl Client { pub fn get( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, provider_name: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), provider_name: provider_name.into(), } } pub fn create( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, provider_name: impl Into<String>, creation_params: impl Into<models::AttestationServiceCreationParams>, ) -> create::Builder { create::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), provider_name: provider_name.into(), creation_params: creation_params.into(), } } pub fn update( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, provider_name: impl Into<String>, update_params: impl Into<models::AttestationServicePatchParams>, ) -> update::Builder { update::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), provider_name: provider_name.into(), update_params: update_params.into(), } } pub fn delete( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, provider_name: impl Into<String>, ) -> delete::Builder { delete::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), provider_name: provider_name.into(), } } pub fn list(&self, subscription_id: impl Into<String>) -> list::Builder { list::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), } } pub fn list_by_resource_group( &self, resource_group_name: impl Into<String>, subscription_id: impl Into<String>, ) -> list_by_resource_group::Builder { list_by_resource_group::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), subscription_id: subscription_id.into(), } } pub fn list_default(&self, subscription_id: impl Into<String>) -> list_default::Builder { list_default::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), } } pub fn get_default_by_location( &self, location: impl Into<String>, subscription_id: impl Into<String>, ) -> get_default_by_location::Builder { get_default_by_location::Builder { client: self.0.clone(), location: location.into(), subscription_id: subscription_id.into(), } } } pub mod get { use super::models; use azure_core::error::ResultExt; type Response = models::AttestationProvider; #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, pub(crate) provider_name: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, azure_core::error::Result<Response>> { Box::pin({ let this = self.clone(); async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Attestation/attestationProviders/{}", this.client.endpoint(), &this.subscription_id, &this.resource_group_name, &this.provider_name ); let mut url = url::Url::parse(url_str).context(azure_core::error::ErrorKind::DataConversion, "parse url")?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = this.client.token_credential(); let token_response = credential .get_token(&this.client.scopes().join(" ")) .await .context(azure_core::error::ErrorKind::Other, "get bearer token")?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", "2020-10-01"); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .context(azure_core::error::ErrorKind::Other, "build request")?; let rsp = this .client .send(req) .await .context(azure_core::error::ErrorKind::Io, "execute request")?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await?; let rsp_value: models::AttestationProvider = serde_json::from_slice(&rsp_body)?; Ok(rsp_value) } status_code => Err(azure_core::error::Error::from(azure_core::error::ErrorKind::HttpResponse { status: status_code.as_u16(), error_code: None, })), } } }) } } } pub mod create { use super::models; use azure_core::error::ResultExt; #[derive(Debug)] pub enum Response { Ok200(models::AttestationProvider), Created201(models::AttestationProvider), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, pub(crate) provider_name: String, pub(crate) creation_params: models::AttestationServiceCreationParams, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, azure_core::error::Result<Response>> { Box::pin({ let this = self.clone(); async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Attestation/attestationProviders/{}", this.client.endpoint(), &this.subscription_id, &this.resource_group_name, &this.provider_name ); let mut url = url::Url::parse(url_str).context(azure_core::error::ErrorKind::DataConversion, "parse url")?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); let credential = this.client.token_credential(); let token_response = credential .get_token(&this.client.scopes().join(" ")) .await .context(azure_core::error::ErrorKind::Other, "get bearer token")?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", "2020-10-01"); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&this.creation_params)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .context(azure_core::error::ErrorKind::Other, "build request")?; let rsp = this .client .send(req) .await .context(azure_core::error::ErrorKind::Io, "execute request")?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await?; let rsp_value: models::AttestationProvider = serde_json::from_slice(&rsp_body)?; Ok(Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await?; let rsp_value: models::AttestationProvider = serde_json::from_slice(&rsp_body)?; Ok(Response::Created201(rsp_value)) } status_code => Err(azure_core::error::Error::from(azure_core::error::ErrorKind::HttpResponse { status: status_code.as_u16(), error_code: None, })), } } }) } } } pub mod update { use super::models; use azure_core::error::ResultExt; type Response = models::AttestationProvider; #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, pub(crate) provider_name: String, pub(crate) update_params: models::AttestationServicePatchParams, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, azure_core::error::Result<Response>> { Box::pin({ let this = self.clone(); async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Attestation/attestationProviders/{}", this.client.endpoint(), &this.subscription_id, &this.resource_group_name, &this.provider_name ); let mut url = url::Url::parse(url_str).context(azure_core::error::ErrorKind::DataConversion, "parse url")?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PATCH); let credential = this.client.token_credential(); let token_response = credential .get_token(&this.client.scopes().join(" ")) .await .context(azure_core::error::ErrorKind::Other, "get bearer token")?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", "2020-10-01"); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&this.update_params)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .context(azure_core::error::ErrorKind::Other, "build request")?; let rsp = this .client .send(req) .await .context(azure_core::error::ErrorKind::Io, "execute request")?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await?; let rsp_value: models::AttestationProvider = serde_json::from_slice(&rsp_body)?; Ok(rsp_value) } status_code => Err(azure_core::error::Error::from(azure_core::error::ErrorKind::HttpResponse { status: status_code.as_u16(), error_code: None, })), } } }) } } } pub mod delete { use super::models; use azure_core::error::ResultExt; #[derive(Debug)] pub enum Response { Ok200, Accepted202, NoContent204, } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, pub(crate) provider_name: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, azure_core::error::Result<Response>> { Box::pin({ let this = self.clone(); async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Attestation/attestationProviders/{}", this.client.endpoint(), &this.subscription_id, &this.resource_group_name, &this.provider_name ); let mut url = url::Url::parse(url_str).context(azure_core::error::ErrorKind::DataConversion, "parse url")?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); let credential = this.client.token_credential(); let token_response = credential .get_token(&this.client.scopes().join(" ")) .await .context(azure_core::error::ErrorKind::Other, "get bearer token")?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", "2020-10-01"); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .context(azure_core::error::ErrorKind::Other, "build request")?; let rsp = this .client .send(req) .await .context(azure_core::error::ErrorKind::Io, "execute request")?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => Ok(Response::Ok200), http::StatusCode::ACCEPTED => Ok(Response::Accepted202), http::StatusCode::NO_CONTENT => Ok(Response::NoContent204), status_code => Err(azure_core::error::Error::from(azure_core::error::ErrorKind::HttpResponse { status: status_code.as_u16(), error_code: None, })), } } }) } } } pub mod list { use super::models; use azure_core::error::ResultExt; type Response = models::AttestationProviderListResult; #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, azure_core::error::Result<Response>> { Box::pin({ let this = self.clone(); async move { let url_str = &format!( "{}/subscriptions/{}/providers/Microsoft.Attestation/attestationProviders", this.client.endpoint(), &this.subscription_id ); let mut url = url::Url::parse(url_str).context(azure_core::error::ErrorKind::DataConversion, "parse url")?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = this.client.token_credential(); let token_response = credential .get_token(&this.client.scopes().join(" ")) .await .context(azure_core::error::ErrorKind::Other, "get bearer token")?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", "2020-10-01"); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .context(azure_core::error::ErrorKind::Other, "build request")?; let rsp = this .client .send(req) .await .context(azure_core::error::ErrorKind::Io, "execute request")?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await?; let rsp_value: models::AttestationProviderListResult = serde_json::from_slice(&rsp_body)?; Ok(rsp_value) } status_code => Err(azure_core::error::Error::from(azure_core::error::ErrorKind::HttpResponse { status: status_code.as_u16(), error_code: None, })), } } }) } } } pub mod list_by_resource_group { use super::models; use azure_core::error::ResultExt; type Response = models::AttestationProviderListResult; #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, azure_core::error::Result<Response>> { Box::pin({ let this = self.clone(); async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Attestation/attestationProviders", this.client.endpoint(), &this.subscription_id, &this.resource_group_name ); let mut url = url::Url::parse(url_str).context(azure_core::error::ErrorKind::DataConversion, "parse url")?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = this.client.token_credential(); let token_response = credential .get_token(&this.client.scopes().join(" ")) .await .context(azure_core::error::ErrorKind::Other, "get bearer token")?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", "2020-10-01"); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .context(azure_core::error::ErrorKind::Other, "build request")?; let rsp = this .client .send(req) .await .context(azure_core::error::ErrorKind::Io, "execute request")?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await?; let rsp_value: models::AttestationProviderListResult = serde_json::from_slice(&rsp_body)?; Ok(rsp_value) } status_code => Err(azure_core::error::Error::from(azure_core::error::ErrorKind::HttpResponse { status: status_code.as_u16(), error_code: None, })), } } }) } } } pub mod list_default { use super::models; use azure_core::error::ResultExt; type Response = models::AttestationProviderListResult; #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, azure_core::error::Result<Response>> { Box::pin({ let this = self.clone(); async move { let url_str = &format!( "{}/subscriptions/{}/providers/Microsoft.Attestation/defaultProviders", this.client.endpoint(), &this.subscription_id ); let mut url = url::Url::parse(url_str).context(azure_core::error::ErrorKind::DataConversion, "parse url")?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = this.client.token_credential(); let token_response = credential .get_token(&this.client.scopes().join(" ")) .await .context(azure_core::error::ErrorKind::Other, "get bearer token")?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", "2020-10-01"); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .context(azure_core::error::ErrorKind::Other, "build request")?; let rsp = this .client .send(req) .await .context(azure_core::error::ErrorKind::Io, "execute request")?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await?; let rsp_value: models::AttestationProviderListResult = serde_json::from_slice(&rsp_body)?; Ok(rsp_value) } status_code => Err(azure_core::error::Error::from(azure_core::error::ErrorKind::HttpResponse { status: status_code.as_u16(), error_code: None, })), } } }) } } } pub mod get_default_by_location { use super::models; use azure_core::error::ResultExt; type Response = models::AttestationProvider; #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) location: String, pub(crate) subscription_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, azure_core::error::Result<Response>> { Box::pin({ let this = self.clone(); async move { let url_str = &format!( "{}/subscriptions/{}/providers/Microsoft.Attestation/locations/{}/defaultProvider", this.client.endpoint(), &this.subscription_id, &this.location ); let mut url = url::Url::parse(url_str).context(azure_core::error::ErrorKind::DataConversion, "parse url")?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = this.client.token_credential(); let token_response = credential .get_token(&this.client.scopes().join(" ")) .await .context(azure_core::error::ErrorKind::Other, "get bearer token")?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", "2020-10-01"); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .context(azure_core::error::ErrorKind::Other, "build request")?; let rsp = this .client .send(req) .await .context(azure_core::error::ErrorKind::Io, "execute request")?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await?; let rsp_value: models::AttestationProvider = serde_json::from_slice(&rsp_body)?; Ok(rsp_value) } status_code => Err(azure_core::error::Error::from(azure_core::error::ErrorKind::HttpResponse { status: status_code.as_u16(), error_code: None, })), } } }) } } } } pub mod private_endpoint_connections { use super::models; pub struct Client(pub(crate) super::Client); impl Client { pub fn list( &self, resource_group_name: impl Into<String>, provider_name: impl Into<String>, subscription_id: impl Into<String>, ) -> list::Builder { list::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), provider_name: provider_name.into(), subscription_id: subscription_id.into(), } } pub fn get( &self, resource_group_name: impl Into<String>, provider_name: impl Into<String>, subscription_id: impl Into<String>, private_endpoint_connection_name: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), provider_name: provider_name.into(), subscription_id: subscription_id.into(), private_endpoint_connection_name: private_endpoint_connection_name.into(), } } pub fn create( &self, resource_group_name: impl Into<String>, provider_name: impl Into<String>, subscription_id: impl Into<String>, private_endpoint_connection_name: impl Into<String>, properties: impl Into<models::PrivateEndpointConnection>, ) -> create::Builder { create::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), provider_name: provider_name.into(), subscription_id: subscription_id.into(), private_endpoint_connection_name: private_endpoint_connection_name.into(), properties: properties.into(), } } pub fn delete( &self, resource_group_name: impl Into<String>, provider_name: impl Into<String>, subscription_id: impl Into<String>, private_endpoint_connection_name: impl Into<String>, ) -> delete::Builder { delete::Builder { client: self.0.clone(), resource_group_name: resource_group_name.into(), provider_name: provider_name.into(), subscription_id: subscription_id.into(), private_endpoint_connection_name: private_endpoint_connection_name.into(), } } } pub mod list { use super::models; use azure_core::error::ResultExt; type Response = models::PrivateEndpointConnectionListResult; #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) provider_name: String, pub(crate) subscription_id: String, } impl Builder { #[doc = "only the first response will be fetched as the continuation token is not part of the response schema"] pub fn into_future(self) -> futures::future::BoxFuture<'static, azure_core::error::Result<Response>> { Box::pin({ let this = self.clone(); async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Attestation/attestationProviders/{}/privateEndpointConnections" , this . client . endpoint () , & this . subscription_id , & this . resource_group_name , & this . provider_name) ; let mut url = url::Url::parse(url_str).context(azure_core::error::ErrorKind::DataConversion, "parse url")?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = this.client.token_credential(); let token_response = credential .get_token(&this.client.scopes().join(" ")) .await .context(azure_core::error::ErrorKind::Other, "get bearer token")?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", "2020-10-01"); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .context(azure_core::error::ErrorKind::Other, "build request")?; let rsp = this .client .send(req) .await .context(azure_core::error::ErrorKind::Io, "execute request")?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await?; let rsp_value: models::PrivateEndpointConnectionListResult = serde_json::from_slice(&rsp_body)?; Ok(rsp_value) } status_code => Err(azure_core::error::Error::from(azure_core::error::ErrorKind::HttpResponse { status: status_code.as_u16(), error_code: None, })), } } }) } } } pub mod get { use super::models; use azure_core::error::ResultExt; type Response = models::PrivateEndpointConnection; #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) provider_name: String, pub(crate) subscription_id: String, pub(crate) private_endpoint_connection_name: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, azure_core::error::Result<Response>> { Box::pin({ let this = self.clone(); async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Attestation/attestationProviders/{}/privateEndpointConnections/{}" , this . client . endpoint () , & this . subscription_id , & this . resource_group_name , & this . provider_name , & this . private_endpoint_connection_name) ; let mut url = url::Url::parse(url_str).context(azure_core::error::ErrorKind::DataConversion, "parse url")?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = this.client.token_credential(); let token_response = credential .get_token(&this.client.scopes().join(" ")) .await .context(azure_core::error::ErrorKind::Other, "get bearer token")?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", "2020-10-01"); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .context(azure_core::error::ErrorKind::Other, "build request")?; let rsp = this .client .send(req) .await .context(azure_core::error::ErrorKind::Io, "execute request")?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await?; let rsp_value: models::PrivateEndpointConnection = serde_json::from_slice(&rsp_body)?; Ok(rsp_value) } status_code => Err(azure_core::error::Error::from(azure_core::error::ErrorKind::HttpResponse { status: status_code.as_u16(), error_code: None, })), } } }) } } } pub mod create { use super::models; use azure_core::error::ResultExt; type Response = models::PrivateEndpointConnection; #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) provider_name: String, pub(crate) subscription_id: String, pub(crate) private_endpoint_connection_name: String, pub(crate) properties: models::PrivateEndpointConnection, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, azure_core::error::Result<Response>> { Box::pin({ let this = self.clone(); async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Attestation/attestationProviders/{}/privateEndpointConnections/{}" , this . client . endpoint () , & this . subscription_id , & this . resource_group_name , & this . provider_name , & this . private_endpoint_connection_name) ; let mut url = url::Url::parse(url_str).context(azure_core::error::ErrorKind::DataConversion, "parse url")?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); let credential = this.client.token_credential(); let token_response = credential .get_token(&this.client.scopes().join(" ")) .await .context(azure_core::error::ErrorKind::Other, "get bearer token")?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", "2020-10-01"); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&this.properties)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .context(azure_core::error::ErrorKind::Other, "build request")?; let rsp = this .client .send(req) .await .context(azure_core::error::ErrorKind::Io, "execute request")?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await?; let rsp_value: models::PrivateEndpointConnection = serde_json::from_slice(&rsp_body)?; Ok(rsp_value) } status_code => Err(azure_core::error::Error::from(azure_core::error::ErrorKind::HttpResponse { status: status_code.as_u16(), error_code: None, })), } } }) } } } pub mod delete { use super::models; use azure_core::error::ResultExt; #[derive(Debug)] pub enum Response { Ok200, NoContent204, } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) resource_group_name: String, pub(crate) provider_name: String, pub(crate) subscription_id: String, pub(crate) private_endpoint_connection_name: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, azure_core::error::Result<Response>> { Box::pin({ let this = self.clone(); async move { let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Attestation/attestationProviders/{}/privateEndpointConnections/{}" , this . client . endpoint () , & this . subscription_id , & this . resource_group_name , & this . provider_name , & this . private_endpoint_connection_name) ; let mut url = url::Url::parse(url_str).context(azure_core::error::ErrorKind::DataConversion, "parse url")?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); let credential = this.client.token_credential(); let token_response = credential .get_token(&this.client.scopes().join(" ")) .await .context(azure_core::error::ErrorKind::Other, "get bearer token")?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", "2020-10-01"); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .context(azure_core::error::ErrorKind::Other, "build request")?; let rsp = this .client .send(req) .await .context(azure_core::error::ErrorKind::Io, "execute request")?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => Ok(Response::Ok200), http::StatusCode::NO_CONTENT => Ok(Response::NoContent204), status_code => Err(azure_core::error::Error::from(azure_core::error::ErrorKind::HttpResponse { status: status_code.as_u16(), error_code: None, })), } } }) } } } }
51.485742
335
0.489315
3a1f8fb5ca060dfd9061a6c4ab5fc6e5daf8b58a
57,203
//! Delta Table read and write implementation // Reference: https://github.com/delta-io/delta/blob/master/PROTOCOL.md // use arrow::error::ArrowError; use chrono::{DateTime, FixedOffset, Utc}; use futures::StreamExt; use lazy_static::lazy_static; use log::*; use parquet::errors::ParquetError; use parquet::file::{ reader::{FileReader, SerializedFileReader}, serialized_reader::SliceableCursor, }; use regex::Regex; use serde::{Deserialize, Serialize}; use serde_json::Value; use std::collections::HashMap; use std::convert::TryFrom; use std::fmt; use std::io::{BufRead, BufReader, Cursor}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use std::{cmp::Ordering, collections::HashSet}; use uuid::Uuid; use crate::action::Stats; use super::action; use super::action::{Action, DeltaOperation}; use super::partitions::{DeltaTablePartition, PartitionFilter}; use super::schema::*; use super::storage; use super::storage::{parse_uri, StorageBackend, StorageError, UriError}; /// Metadata for a checkpoint file #[derive(Serialize, Deserialize, Debug, Default, Clone, Copy)] pub struct CheckPoint { /// Delta table version version: DeltaDataTypeVersion, // 20 digits decimals size: DeltaDataTypeLong, parts: Option<u32>, // 10 digits decimals } impl CheckPoint { /// Creates a new checkpoint from the given parameters. pub(crate) fn new( version: DeltaDataTypeVersion, size: DeltaDataTypeLong, parts: Option<u32>, ) -> Self { Self { version, size, parts, } } } impl PartialEq for CheckPoint { fn eq(&self, other: &Self) -> bool { self.version == other.version } } impl Eq for CheckPoint {} /// Delta Table specific error #[derive(thiserror::Error, Debug)] pub enum DeltaTableError { /// Error returned when applying transaction log failed. #[error("Failed to apply transaction log: {}", .source)] ApplyLog { /// Apply error details returned when applying transaction log failed. #[from] source: ApplyLogError, }, /// Error returned when loading checkpoint failed. #[error("Failed to load checkpoint: {}", .source)] LoadCheckpoint { /// Load checkpoint error details returned when loading checkpoint failed. #[from] source: LoadCheckpointError, }, /// Error returned when reading the delta log object failed. #[error("Failed to read delta log object: {}", .source)] StorageError { /// Storage error details when reading the delta log object failed. #[from] source: StorageError, }, /// Error returned when reading the checkpoint failed. #[error("Failed to read checkpoint: {}", .source)] ParquetError { /// Parquet error details returned when reading the checkpoint failed. #[from] source: ParquetError, }, /// Error returned when converting the schema in Arrow format failed. #[error("Failed to convert into Arrow schema: {}", .source)] ArrowError { /// Arrow error details returned when converting the schema in Arrow format failed #[from] source: ArrowError, }, /// Error returned when the table has an invalid path. #[error("Invalid table path: {}", .source)] UriError { /// Uri error details returned when the table has an invalid path. #[from] source: UriError, }, /// Error returned when the log record has an invalid JSON. #[error("Invalid JSON in log record: {}", .source)] InvalidJson { /// JSON error details returned when the log record has an invalid JSON. #[from] source: serde_json::error::Error, }, /// Error returned when the DeltaTable has an invalid version. #[error("Invalid table version: {0}")] InvalidVersion(DeltaDataTypeVersion), /// Error returned when the DeltaTable has no data files. #[error("Corrupted table, cannot read data file {}: {}", .path, .source)] MissingDataFile { /// Source error details returned when the DeltaTable has no data files. source: std::io::Error, /// The Path used of the DeltaTable path: String, }, /// Error returned when the datetime string is invalid for a conversion. #[error("Invalid datetime string: {}", .source)] InvalidDateTimeString { /// Parse error details returned of the datetime string parse error. #[from] source: chrono::ParseError, }, /// Error returned when the action record is invalid in log. #[error("Invalid action record found in log: {}", .source)] InvalidAction { /// Action error details returned of the invalid action. #[from] source: action::ActionError, }, /// Error returned when it is not a DeltaTable. #[error("Not a Delta table: {0}")] NotATable(String), /// Error returned when no metadata was found in the DeltaTable. #[error("No metadata found, please make sure table is loaded.")] NoMetadata, /// Error returned when no schema was found in the DeltaTable. #[error("No schema found, please make sure table is loaded.")] NoSchema, /// Error returned when no partition was found in the DeltaTable. #[error("No partitions found, please make sure table is partitioned.")] LoadPartitions, /// Error returned when writes are attempted with data that doesn't match the schema of the /// table #[error("Data does not match the schema or partitions of the table: {}", msg)] SchemaMismatch { /// Information about the mismatch msg: String, }, /// Error returned when a partition is not formatted as a Hive Partition. #[error("This partition is not formatted with key=value: {}", .partition)] PartitionError { /// The malformed partition used. partition: String, }, /// Error returned when a invalid partition filter was found. #[error("Invalid partition filter found: {}.", .partition_filter)] InvalidPartitionFilter { /// The invalid partition filter used. partition_filter: String, }, /// Error returned when Vacuum retention period is below the safe threshold #[error( "Invalid retention period, retention for Vacuum must be greater than 1 week (168 hours)" )] InvalidVacuumRetentionPeriod, /// Generic Delta Table error #[error("Generic DeltaTable error: {0}")] Generic(String), } /// Delta table metadata #[derive(Clone, Debug)] pub struct DeltaTableMetaData { /// Unique identifier for this table pub id: Guid, /// User-provided identifier for this table pub name: Option<String>, /// User-provided description for this table pub description: Option<String>, /// Specification of the encoding for the files stored in the table pub format: action::Format, /// Schema of the table pub schema: Schema, /// An array containing the names of columns by which the data should be partitioned pub partition_columns: Vec<String>, /// The time when this metadata action is created, in milliseconds since the Unix epoch pub created_time: DeltaDataTypeTimestamp, /// table properties pub configuration: HashMap<String, String>, } impl fmt::Display for DeltaTableMetaData { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "GUID={}, name={:?}, description={:?}, partitionColumns={:?}, createdTime={:?}, configuration={:?}", self.id, self.name, self.description, self.partition_columns, self.created_time, self.configuration ) } } impl TryFrom<action::MetaData> for DeltaTableMetaData { type Error = serde_json::error::Error; fn try_from(action_metadata: action::MetaData) -> Result<Self, Self::Error> { let schema = action_metadata.get_schema()?; Ok(Self { id: action_metadata.id, name: action_metadata.name, description: action_metadata.description, format: action_metadata.format, schema, partition_columns: action_metadata.partition_columns, created_time: action_metadata.created_time, configuration: action_metadata.configuration, }) } } impl TryFrom<DeltaTableMetaData> for action::MetaData { type Error = serde_json::error::Error; fn try_from(metadata: DeltaTableMetaData) -> Result<Self, Self::Error> { let schema_string = serde_json::to_string(&metadata.schema)?; Ok(Self { id: metadata.id, name: metadata.name, description: metadata.description, format: metadata.format, schema_string, partition_columns: metadata.partition_columns, created_time: metadata.created_time, configuration: metadata.configuration, }) } } /// Error related to Delta log application #[derive(thiserror::Error, Debug)] pub enum ApplyLogError { /// Error returned when the end of transaction log is reached. #[error("End of transaction log")] EndOfLog, /// Error returned when the JSON of the log record is invalid. #[error("Invalid JSON in log record")] InvalidJson { /// JSON error details returned when reading the JSON log record. #[from] source: serde_json::error::Error, }, /// Error returned when the storage failed to read the log content. #[error("Failed to read log content")] Storage { /// Storage error details returned while reading the log content. source: StorageError, }, /// Error returned when a line from log record is invalid. #[error("Failed to read line from log record")] Io { /// Source error details returned while reading the log record. #[from] source: std::io::Error, }, } impl From<StorageError> for ApplyLogError { fn from(error: StorageError) -> Self { match error { StorageError::NotFound => ApplyLogError::EndOfLog, _ => ApplyLogError::Storage { source: error }, } } } /// Error related to checkpoint loading #[derive(thiserror::Error, Debug)] pub enum LoadCheckpointError { /// Error returned when the JSON checkpoint is not found. #[error("Checkpoint file not found")] NotFound, /// Error returned when the JSON checkpoint is invalid. #[error("Invalid JSON in checkpoint: {source}")] InvalidJson { /// Error details returned while reading the JSON. #[from] source: serde_json::error::Error, }, /// Error returned when it failed to read the checkpoint content. #[error("Failed to read checkpoint content: {source}")] Storage { /// Storage error details returned while reading the checkpoint content. source: StorageError, }, } impl From<StorageError> for LoadCheckpointError { fn from(error: StorageError) -> Self { match error { StorageError::NotFound => LoadCheckpointError::NotFound, _ => LoadCheckpointError::Storage { source: error }, } } } /// State snapshot currently held by the Delta Table instance. #[derive(Default, Debug, Clone)] pub struct DeltaTableState { // A remove action should remain in the state of the table as a tombstone until it has expired. // A tombstone expires when the creation timestamp of the delta file exceeds the expiration tombstones: Vec<action::Remove>, files: Vec<action::Add>, commit_infos: Vec<Value>, app_transaction_version: HashMap<String, DeltaDataTypeVersion>, min_reader_version: i32, min_writer_version: i32, current_metadata: Option<DeltaTableMetaData>, } impl DeltaTableState { /// Full list of tombstones (remove actions) representing files removed from table state). pub fn tombstones(&self) -> &Vec<action::Remove> { self.tombstones.as_ref() } /// Full list of add actions representing all parquet files that are part of the current /// delta table state. pub fn files(&self) -> &Vec<action::Add> { self.files.as_ref() } /// HashMap containing the last txn version stored for every app id writing txn /// actions. pub fn app_transaction_version(&self) -> &HashMap<String, DeltaDataTypeVersion> { &self.app_transaction_version } /// The min reader version required by the protocol. pub fn min_reader_version(&self) -> i32 { self.min_reader_version } /// The min writer version required by the protocol. pub fn min_writer_version(&self) -> i32 { self.min_writer_version } /// The most recent metadata of the table. pub fn current_metadata(&self) -> Option<&DeltaTableMetaData> { self.current_metadata.as_ref() } } #[inline] /// Return path relative to parent_path fn extract_rel_path<'a, 'b>( parent_path: &'b str, path: &'a str, ) -> Result<&'a str, DeltaTableError> { if path.starts_with(&parent_path) { // plus one to account for path separator Ok(&path[parent_path.len() + 1..]) } else { Err(DeltaTableError::Generic(format!( "Parent path `{}` is not a prefix of path `{}`", parent_path, path ))) } } /// In memory representation of a Delta Table pub struct DeltaTable { /// The version of the table as of the most recent loaded Delta log entry. pub version: DeltaDataTypeVersion, /// The URI the DeltaTable was loaded from. pub table_uri: String, state: DeltaTableState, // metadata // application_transactions storage: Box<dyn StorageBackend>, last_check_point: Option<CheckPoint>, log_uri: String, version_timestamp: HashMap<DeltaDataTypeVersion, i64>, } impl DeltaTable { fn commit_uri_from_version(&self, version: DeltaDataTypeVersion) -> String { let version = format!("{:020}.json", version); self.storage.join_path(&self.log_uri, &version) } fn get_checkpoint_data_paths(&self, check_point: &CheckPoint) -> Vec<String> { let checkpoint_prefix_pattern = format!("{:020}", check_point.version); let checkpoint_prefix = self .storage .join_path(&self.log_uri, &checkpoint_prefix_pattern); let mut checkpoint_data_paths = Vec::new(); match check_point.parts { None => { checkpoint_data_paths.push(format!("{}.checkpoint.parquet", checkpoint_prefix)); } Some(parts) => { for i in 0..parts { checkpoint_data_paths.push(format!( "{}.checkpoint.{:010}.{:010}.parquet", checkpoint_prefix, i + 1, parts )); } } } checkpoint_data_paths } async fn get_last_checkpoint(&self) -> Result<CheckPoint, LoadCheckpointError> { let last_checkpoint_path = self.storage.join_path(&self.log_uri, "_last_checkpoint"); let data = self.storage.get_obj(&last_checkpoint_path).await?; Ok(serde_json::from_slice(&data)?) } async fn find_latest_check_point_for_version( &self, version: DeltaDataTypeVersion, ) -> Result<Option<CheckPoint>, DeltaTableError> { lazy_static! { static ref CHECKPOINT_REGEX: Regex = Regex::new(r#"^*[/\\]_delta_log[/\\](\d{20})\.checkpoint\.parquet$"#).unwrap(); static ref CHECKPOINT_PARTS_REGEX: Regex = Regex::new( r#"^*[/\\]_delta_log[/\\](\d{20})\.checkpoint\.\d{10}\.(\d{10})\.parquet$"# ) .unwrap(); } let mut cp: Option<CheckPoint> = None; let mut stream = self.storage.list_objs(&self.log_uri).await?; while let Some(obj_meta) = stream.next().await { // Exit early if any objects can't be listed. let obj_meta = obj_meta?; if let Some(captures) = CHECKPOINT_REGEX.captures(&obj_meta.path) { let curr_ver_str = captures.get(1).unwrap().as_str(); let curr_ver: DeltaDataTypeVersion = curr_ver_str.parse().unwrap(); if curr_ver > version { // skip checkpoints newer than max version continue; } if cp.is_none() || curr_ver > cp.unwrap().version { cp = Some(CheckPoint { version: curr_ver, size: 0, parts: None, }); } continue; } if let Some(captures) = CHECKPOINT_PARTS_REGEX.captures(&obj_meta.path) { let curr_ver_str = captures.get(1).unwrap().as_str(); let curr_ver: DeltaDataTypeVersion = curr_ver_str.parse().unwrap(); if curr_ver > version { // skip checkpoints newer than max version continue; } if cp.is_none() || curr_ver > cp.unwrap().version { let parts_str = captures.get(2).unwrap().as_str(); let parts = parts_str.parse().unwrap(); cp = Some(CheckPoint { version: curr_ver, size: 0, parts: Some(parts), }); } continue; } } Ok(cp) } fn apply_log_from_bufread<R: BufRead>( &mut self, reader: BufReader<R>, ) -> Result<(), ApplyLogError> { for line in reader.lines() { let action: Action = serde_json::from_str(line?.as_str())?; process_action(&mut self.state, action)?; } Ok(()) } async fn apply_log(&mut self, version: DeltaDataTypeVersion) -> Result<(), ApplyLogError> { let commit_uri = self.commit_uri_from_version(version); let commit_log_bytes = self.storage.get_obj(&commit_uri).await?; let reader = BufReader::new(Cursor::new(commit_log_bytes)); self.apply_log_from_bufread(reader) } async fn restore_checkpoint(&mut self, check_point: CheckPoint) -> Result<(), DeltaTableError> { let checkpoint_data_paths = self.get_checkpoint_data_paths(&check_point); // process actions from checkpoint self.state = DeltaTableState::default(); for f in &checkpoint_data_paths { let obj = self.storage.get_obj(&f).await?; let preader = SerializedFileReader::new(SliceableCursor::new(obj))?; let schema = preader.metadata().file_metadata().schema(); if !schema.is_group() { return Err(DeltaTableError::from(action::ActionError::Generic( "Action record in checkpoint should be a struct".to_string(), ))); } for record in preader.get_row_iter(None)? { process_action( &mut self.state, Action::from_parquet_record(&schema, &record)?, )?; } } Ok(()) } async fn get_latest_version(&mut self) -> Result<DeltaDataTypeVersion, DeltaTableError> { let mut version = match self.get_last_checkpoint().await { Ok(last_check_point) => last_check_point.version + 1, Err(LoadCheckpointError::NotFound) => { // no checkpoint, start with version 0 0 } Err(e) => { return Err(DeltaTableError::LoadCheckpoint { source: e }); } }; // scan logs after checkpoint loop { match self .storage .head_obj(&self.commit_uri_from_version(version)) .await { Ok(meta) => { // also cache timestamp for version self.version_timestamp .insert(version, meta.modified.timestamp()); version += 1; } Err(e) => { match e { StorageError::NotFound => { version -= 1; } _ => return Err(DeltaTableError::from(e)), } break; } } } Ok(version) } /// Load DeltaTable with data from latest checkpoint pub async fn load(&mut self) -> Result<(), DeltaTableError> { match self.get_last_checkpoint().await { Ok(last_check_point) => { self.last_check_point = Some(last_check_point); self.restore_checkpoint(last_check_point).await?; self.version = last_check_point.version + 1; } Err(LoadCheckpointError::NotFound) => { // no checkpoint, start with version 0 self.version = 0; } Err(e) => { return Err(DeltaTableError::LoadCheckpoint { source: e }); } } self.apply_logs_from_current_version().await?; Ok(()) } /// Updates the DeltaTable to the most recent state committed to the transaction log by /// loading the last checkpoint and incrementally applying each version since. pub async fn update(&mut self) -> Result<(), DeltaTableError> { match self.get_last_checkpoint().await { Ok(last_check_point) => { if self.last_check_point != Some(last_check_point) { self.last_check_point = Some(last_check_point); self.restore_checkpoint(last_check_point).await?; self.version = last_check_point.version + 1; } } Err(LoadCheckpointError::NotFound) => { self.version += 1; } Err(e) => { return Err(DeltaTableError::LoadCheckpoint { source: e }); } } self.apply_logs_from_current_version().await?; Ok(()) } /// Updates the DeltaTable to the most recent state committed to the transaction by /// incrementally applying each version since current. pub async fn update_incremental(&mut self) -> Result<(), DeltaTableError> { self.version += 1; self.apply_logs_from_current_version().await } async fn apply_logs_from_current_version(&mut self) -> Result<(), DeltaTableError> { // replay logs after checkpoint loop { match self.apply_log(self.version).await { Ok(_) => { self.version += 1; } Err(e) => { match e { ApplyLogError::EndOfLog => { self.version -= 1; if self.version == -1 { let err = format!( "No snapshot or version 0 found, perhaps {} is an empty dir?", self.table_uri ); return Err(DeltaTableError::NotATable(err)); } } _ => { return Err(DeltaTableError::from(e)); } } break; } } } Ok(()) } /// Loads the DeltaTable state for the given version. pub async fn load_version( &mut self, version: DeltaDataTypeVersion, ) -> Result<(), DeltaTableError> { // check if version is valid let commit_uri = self.commit_uri_from_version(version); match self.storage.head_obj(&commit_uri).await { Ok(_) => {} Err(StorageError::NotFound) => { return Err(DeltaTableError::InvalidVersion(version)); } Err(e) => { return Err(DeltaTableError::from(e)); } } self.version = version; let mut next_version; // 1. find latest checkpoint below version match self.find_latest_check_point_for_version(version).await? { Some(check_point) => { self.restore_checkpoint(check_point).await?; next_version = check_point.version + 1; } None => { // no checkpoint found, start from the beginning next_version = 0; } } // 2. apply all logs starting from checkpoint while next_version <= self.version { self.apply_log(next_version).await?; next_version += 1; } Ok(()) } async fn get_version_timestamp( &mut self, version: DeltaDataTypeVersion, ) -> Result<i64, DeltaTableError> { match self.version_timestamp.get(&version) { Some(ts) => Ok(*ts), None => { let meta = self .storage .head_obj(&self.commit_uri_from_version(version)) .await?; let ts = meta.modified.timestamp(); // also cache timestamp for version self.version_timestamp.insert(version, ts); Ok(ts) } } } /// Returns the file list tracked in current table state filtered by provided /// `PartitionFilter`s. pub fn get_files_by_partitions( &self, filters: &[PartitionFilter<&str>], ) -> Result<Vec<String>, DeltaTableError> { let partitions_number = match &self .state .current_metadata .as_ref() .ok_or(DeltaTableError::NoMetadata)? .partition_columns { partitions if !partitions.is_empty() => partitions.len(), _ => return Err(DeltaTableError::LoadPartitions), }; let separator = "/"; let files = self .state .files .iter() .filter(|add| { let partitions = add .path .splitn(partitions_number + 1, separator) .filter_map(|p: &str| DeltaTablePartition::try_from(p).ok()) .collect::<Vec<DeltaTablePartition>>(); filters .iter() .all(|filter| filter.match_partitions(&partitions)) }) .map(|add| add.path.clone()) .collect(); Ok(files) } /// Return the file uris as strings for the partition(s) #[deprecated( since = "0.4.0", note = "Please use the get_file_uris_by_partitions function instead" )] pub fn get_file_paths_by_partitions( &self, filters: &[PartitionFilter<&str>], ) -> Result<Vec<String>, DeltaTableError> { self.get_file_uris_by_partitions(filters) } /// Return the file uris as strings for the partition(s) pub fn get_file_uris_by_partitions( &self, filters: &[PartitionFilter<&str>], ) -> Result<Vec<String>, DeltaTableError> { let files = self.get_files_by_partitions(filters)?; Ok(files .iter() .map(|fname| self.storage.join_path(&self.table_uri, fname)) .collect()) } /// Return a refernece to all active "add" actions present in the loaded state pub fn get_active_add_actions(&self) -> &Vec<action::Add> { &self.state.files } /// Returns an iterator of file names present in the loaded state #[inline] pub fn get_files_iter(&self) -> impl Iterator<Item = &str> { self.state.files.iter().map(|add| add.path.as_str()) } /// Returns a collection of file names present in the loaded state #[inline] pub fn get_files(&self) -> Vec<&str> { self.get_files_iter().collect() } /// Returns file names present in the loaded state in HashSet pub fn get_file_set(&self) -> HashSet<&str> { self.state .files .iter() .map(|add| add.path.as_str()) .collect() } /// Returns a URIs for all active files present in the current table version. #[deprecated( since = "0.4.0", note = "Please use the get_file_uris function instead" )] pub fn get_file_paths(&self) -> Vec<String> { self.get_file_uris() } /// Returns a URIs for all active files present in the current table version. pub fn get_file_uris(&self) -> Vec<String> { self.state .files .iter() .map(|add| self.storage.join_path(&self.table_uri, &add.path)) .collect() } /// Returns statistics for files, in order pub fn get_stats(&self) -> Vec<Result<Option<Stats>, DeltaTableError>> { self.state .files .iter() .map(|add| add.get_stats().map_err(DeltaTableError::from)) .collect() } /// Returns the currently loaded state snapshot. pub fn get_state(&self) -> &DeltaTableState { &self.state } /// Returns the metadata associated with the loaded state. pub fn get_metadata(&self) -> Result<&DeltaTableMetaData, DeltaTableError> { self.state .current_metadata .as_ref() .ok_or(DeltaTableError::NoMetadata) } /// Returns a vector of tombstones (i.e. `Remove` actions present in the current delta log. pub fn get_tombstones(&self) -> &Vec<action::Remove> { &self.state.tombstones } /// Returns the current version of the DeltaTable based on the loaded metadata. pub fn get_app_transaction_version(&self) -> &HashMap<String, DeltaDataTypeVersion> { &self.state.app_transaction_version } /// Returns the minimum reader version supported by the DeltaTable based on the loaded /// metadata. pub fn get_min_reader_version(&self) -> i32 { self.state.min_reader_version } /// Returns the minimum writer version supported by the DeltaTable based on the loaded /// metadata. pub fn get_min_writer_version(&self) -> i32 { self.state.min_writer_version } /// List files no longer referenced by a Delta table and are older than the retention threshold. fn get_stale_files(&self, retention_hours: u64) -> Result<HashSet<&str>, DeltaTableError> { if retention_hours < 168 { return Err(DeltaTableError::InvalidVacuumRetentionPeriod); } let before_duration = (SystemTime::now() - Duration::from_secs(3600 * retention_hours)) .duration_since(UNIX_EPOCH); let delete_before_timestamp = match before_duration { Ok(duration) => duration.as_millis() as i64, Err(_) => return Err(DeltaTableError::InvalidVacuumRetentionPeriod), }; Ok(self .get_tombstones() .iter() .filter(|tombstone| tombstone.deletion_timestamp < delete_before_timestamp) .map(|tombstone| tombstone.path.as_str()) .collect::<HashSet<_>>()) } /// Whether a path should be hidden for delta-related file operations, such as Vacuum. /// Names of the form partitionCol=[value] are partition directories, and should be /// deleted even if they'd normally be hidden. The _db_index directory contains (bloom filter) /// indexes and these must be deleted when the data they are tied to is deleted. fn is_hidden_directory(&self, path_name: &str) -> Result<bool, DeltaTableError> { Ok((path_name.starts_with('.') || path_name.starts_with('_')) && !path_name.starts_with("_delta_index") && !path_name.starts_with("_change_data") && !self .state .current_metadata .as_ref() .ok_or(DeltaTableError::NoMetadata)? .partition_columns .iter() .any(|partition_column| path_name.starts_with(partition_column))) } /// Run the Vacuum command on the Delta Table: delete files no longer referenced by a Delta table and are older than the retention threshold. /// We do not recommend that you set a retention interval shorter than 7 days, because old snapshots and uncommitted files can still be in use by concurrent readers or writers to the table. If vacuum cleans up active files, concurrent readers can fail or, worse, tables can be corrupted when vacuum deletes files that have not yet been committed. pub async fn vacuum( &mut self, retention_hours: u64, dry_run: bool, ) -> Result<Vec<String>, DeltaTableError> { let expired_tombstones = self.get_stale_files(retention_hours)?; let valid_files = self.get_file_set(); let mut files_to_delete = vec![]; let mut all_files = self.storage.list_objs(&self.table_uri).await?; // TODO: table_path is currently only used in vacuum, consider precalcualte it during table // struct initialization if it ends up being used in other hot paths let table_path = parse_uri(&self.table_uri)?.path(); while let Some(obj_meta) = all_files.next().await { let obj_meta = obj_meta?; // We can't use self.table_uri as the prefix to extract relative path because // obj_meta.path is not a URI. For example, for S3 objects, obj_meta.path is just the // object key without `s3://` and bucket name. let rel_path = extract_rel_path(&table_path, &obj_meta.path)?; if valid_files.contains(rel_path) // file is still being tracked in table || !expired_tombstones.contains(rel_path) // file is not an expired tombstone || self.is_hidden_directory(rel_path)? { continue; } files_to_delete.push(obj_meta.path); } if dry_run { return Ok(files_to_delete); } for rel_path in &files_to_delete { match self .storage .delete_obj(&self.storage.join_path(&self.table_uri, rel_path)) .await { Ok(_) => continue, Err(StorageError::NotFound) => continue, Err(err) => return Err(DeltaTableError::StorageError { source: err }), } } Ok(files_to_delete) } /// Return table schema parsed from transaction log. Return None if table hasn't been loaded or /// no metadata was found in the log. pub fn schema(&self) -> Option<&Schema> { self.state.current_metadata.as_ref().map(|m| &m.schema) } /// Return table schema parsed from transaction log. Return `DeltaTableError` if table hasn't /// been loaded or no metadata was found in the log. pub fn get_schema(&self) -> Result<&Schema, DeltaTableError> { self.schema().ok_or(DeltaTableError::NoSchema) } /// Creates a new DeltaTransaction for the DeltaTable. /// The transaction holds a mutable reference to the DeltaTable, preventing other references /// until the transaction is dropped. pub fn create_transaction( &mut self, options: Option<DeltaTransactionOptions>, ) -> DeltaTransaction { DeltaTransaction::new(self, options) } /// Tries to commit a prepared commit file. Returns `DeltaTransactionError::VersionAlreadyExists` /// if the given `version` already exists. The caller should handle the retry logic itself. /// This is low-level transaction API. If user does not want to maintain the commit loop then /// the `DeltaTransaction.commit` is desired to be used as it handles `try_commit_transaction` /// with retry logic. pub async fn try_commit_transaction( &mut self, commit: &PreparedCommit, version: DeltaDataTypeVersion, ) -> Result<DeltaDataTypeVersion, DeltaTransactionError> { // move temporary commit file to delta log directory // rely on storage to fail if the file already exists - self.storage .rename_obj(&commit.uri, &self.commit_uri_from_version(version)) .await?; // NOTE: since we have the log entry in memory already, // we could optimize this further by merging the log entry instead of updating from storage. self.update().await?; Ok(version) } /// Create a new Delta Table struct without loading any data from backing storage. /// /// NOTE: This is for advanced users. If you don't know why you need to use this method, please /// call one of the `open_table` helper methods instead. pub fn new( table_uri: &str, storage_backend: Box<dyn StorageBackend>, ) -> Result<Self, DeltaTableError> { let table_uri = storage_backend.trim_path(table_uri); let log_uri_normalized = storage_backend.join_path(&table_uri, "_delta_log"); Ok(Self { version: 0, state: DeltaTableState::default(), storage: storage_backend, table_uri, last_check_point: None, log_uri: log_uri_normalized, version_timestamp: HashMap::new(), }) } /// Time travel Delta table to latest version that's created at or before provided `datetime` /// argument. /// /// Internally, this methods performs a binary search on all Delta transaction logs. pub async fn load_with_datetime( &mut self, datetime: DateTime<Utc>, ) -> Result<(), DeltaTableError> { let mut min_version = 0; let mut max_version = self.get_latest_version().await?; let mut version = min_version; let target_ts = datetime.timestamp(); // binary search while min_version <= max_version { let pivot = (max_version + min_version) / 2; version = pivot; let pts = self.get_version_timestamp(pivot).await?; match pts.cmp(&target_ts) { Ordering::Equal => { break; } Ordering::Less => { min_version = pivot + 1; } Ordering::Greater => { max_version = pivot - 1; version = max_version } } } if version < 0 { version = 0; } self.load_version(version).await } } impl fmt::Display for DeltaTable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "DeltaTable({})", self.table_uri)?; writeln!(f, "\tversion: {}", self.version)?; match self.state.current_metadata.as_ref() { Some(metadata) => { writeln!(f, "\tmetadata: {}", metadata)?; } None => { writeln!(f, "\tmetadata: None")?; } } writeln!( f, "\tmin_version: read={}, write={}", self.state.min_reader_version, self.state.min_writer_version )?; writeln!(f, "\tfiles count: {}", self.state.files.len()) } } impl std::fmt::Debug for DeltaTable { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { write!(f, "DeltaTable <{}>", self.table_uri) } } /// Error returned by the DeltaTransaction struct #[derive(thiserror::Error, Debug)] pub enum DeltaTransactionError { /// Error that indicates a Delta version conflict. i.e. a writer tried to write version _N_ but /// version _N_ already exists in the delta log. #[error("Version already existed when writing transaction. Last error: {source}")] VersionAlreadyExists { /// The wrapped TransactionCommitAttemptError. source: StorageError, }, /// Error that indicates the record batch is missing a partition column required by the Delta /// schema. #[error("RecordBatch is missing partition column in Delta schema.")] MissingPartitionColumn, /// Error that indicates the transaction failed due to an underlying storage error. /// Specific details of the error are described by the wrapped storage error. #[error("Storage interaction failed: {source}")] Storage { /// The wrapped StorageError. source: StorageError, }, /// Error that wraps an underlying DeltaTable error. /// The wrapped error describes the specific cause. #[error("DeltaTable interaction failed: {source}")] DeltaTable { /// The wrapped DeltaTable error. #[from] source: DeltaTableError, }, /// Error caused by a problem while using serde_json to serialize an action. #[error("Action serialization failed: {source}")] ActionSerializationFailed { /// The wrapped serde_json Error. #[from] source: serde_json::Error, }, } impl From<StorageError> for DeltaTransactionError { fn from(error: StorageError) -> Self { match error { StorageError::AlreadyExists(_) => { DeltaTransactionError::VersionAlreadyExists { source: error } } _ => DeltaTransactionError::Storage { source: error }, } } } const DEFAULT_DELTA_MAX_RETRY_COMMIT_ATTEMPTS: u32 = 10_000_000; /// Options for customizing behavior of a `DeltaTransaction` #[derive(Debug)] pub struct DeltaTransactionOptions { /// number of retry attempts allowed when committing a transaction max_retry_commit_attempts: u32, } impl DeltaTransactionOptions { /// Creates a new `DeltaTransactionOptions` pub fn new(max_retry_commit_attempts: u32) -> Self { Self { max_retry_commit_attempts, } } } impl Default for DeltaTransactionOptions { fn default() -> Self { Self { max_retry_commit_attempts: DEFAULT_DELTA_MAX_RETRY_COMMIT_ATTEMPTS, } } } /// Object representing a delta transaction. /// Clients that do not need to mutate action content in case a transaction conflict is encountered /// may use the `commit` method and rely on optimistic concurrency to determine the /// appropriate Delta version number for a commit. A good example of this type of client is an /// append only client that does not need to maintain transaction state with external systems. /// Clients that may need to do conflict resolution if the Delta version changes should use /// the `prepare_commit` and `try_commit_transaction` methods and manage the Delta version /// themselves so that they can resolve data conflicts that may occur between Delta versions. /// /// Please not that in case of non-retryable error the temporary commit file such as /// `_delta_log/_commit_<uuid>.json` will orphaned in storage. #[derive(Debug)] pub struct DeltaTransaction<'a> { delta_table: &'a mut DeltaTable, actions: Vec<Action>, options: DeltaTransactionOptions, } impl<'a> DeltaTransaction<'a> { /// Creates a new delta transaction. /// Holds a mutable reference to the delta table to prevent outside mutation while a transaction commit is in progress. /// Transaction behavior may be customized by passing an instance of `DeltaTransactionOptions`. pub fn new(delta_table: &'a mut DeltaTable, options: Option<DeltaTransactionOptions>) -> Self { DeltaTransaction { delta_table, actions: vec![], options: options.unwrap_or_else(DeltaTransactionOptions::default), } } /// Add an arbitrary "action" to the actions associated with this transaction pub fn add_action(&mut self, action: action::Action) { self.actions.push(action); } /// Add an arbitrary number of actions to the actions associated with this transaction pub fn add_actions(&mut self, actions: Vec<action::Action>) { for action in actions.into_iter() { self.actions.push(action); } } /// Create a new add action and write the given bytes to the storage backend as a fully formed /// Parquet file /// /// add_file accepts two optional parameters: /// /// partitions: an ordered vec of WritablePartitionValues for the file to be added /// actions: an ordered list of Actions to be inserted into the log file _ahead_ of the Add /// action for the file added. This should typically be used for txn type actions pub async fn add_file( &mut self, bytes: &[u8], partitions: Option<Vec<(String, String)>>, ) -> Result<(), DeltaTransactionError> { let mut partition_values = HashMap::new(); if let Some(partitions) = &partitions { for (key, value) in partitions { partition_values.insert(key.clone(), value.clone()); } } let path = self.generate_parquet_filename(partitions); let parquet_uri = self .delta_table .storage .join_path(&self.delta_table.table_uri, &path); debug!("Writing a parquet file to {}", &parquet_uri); self.delta_table .storage .put_obj(&parquet_uri, &bytes) .await .map_err(|source| DeltaTransactionError::Storage { source })?; // Determine the modification timestamp to include in the add action - milliseconds since epoch // Err should be impossible in this case since `SystemTime::now()` is always greater than `UNIX_EPOCH` let modification_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); let modification_time = modification_time.as_millis() as i64; self.actions.push(Action::add(action::Add { path, partition_values, modification_time, size: bytes.len() as i64, partition_values_parsed: None, data_change: true, stats: None, stats_parsed: None, tags: None, })); Ok(()) } fn generate_parquet_filename(&self, partitions: Option<Vec<(String, String)>>) -> String { /* * The specific file naming for parquet is not well documented including the preceding five * zeros and the trailing c000 string * */ let mut path_parts = vec![]; if let Some(partitions) = partitions { for partition in partitions { path_parts.push(format!("{}={}", partition.0, partition.1)); } } path_parts.push(format!("part-00000-{}-c000.snappy.parquet", Uuid::new_v4())); self.delta_table .storage .join_paths(&path_parts.iter().map(|s| s.as_str()).collect::<Vec<&str>>()) } /// Commits the given actions to the delta log. /// This method will retry the transaction commit based on the value of `max_retry_commit_attempts` set in `DeltaTransactionOptions`. pub async fn commit( &mut self, _operation: Option<DeltaOperation>, ) -> Result<DeltaDataTypeVersion, DeltaTransactionError> { // TODO: stubbing `operation` parameter (which will be necessary for writing the CommitInfo action), but leaving it unused for now. // `CommitInfo` is a fairly dynamic data structure so we should work out the data structure approach separately. // TODO: calculate isolation level to use when checking for conflicts. // Leaving conflict checking unimplemented for now to get the "single writer" implementation off the ground. // Leaving some commmented code in place as a guidepost for the future. // let no_data_changed = actions.iter().all(|a| match a { // Action::add(x) => !x.dataChange, // Action::remove(x) => !x.dataChange, // _ => false, // }); // let isolation_level = if no_data_changed { // IsolationLevel::SnapshotIsolation // } else { // IsolationLevel::Serializable // }; let prepared_commit = self.prepare_commit(_operation).await?; // try to commit in a loop in case other writers write the next version first let version = self.try_commit_loop(&prepared_commit).await?; Ok(version) } /// Low-level transaction API. Creates a temporary commit file. Once created, /// the transaction object could be dropped and the actual commit could be executed /// with `DeltaTable.try_commit_transaction`. pub async fn prepare_commit( &self, _operation: Option<DeltaOperation>, ) -> Result<PreparedCommit, DeltaTransactionError> { let token = Uuid::new_v4().to_string(); // TODO: create a CommitInfo action and prepend it to actions. // Serialize all actions that are part of this log entry. let log_entry = log_entry_from_actions(&self.actions)?; let file_name = format!("_commit_{}.json", token); let uri = self .delta_table .storage .join_path(&self.delta_table.log_uri, &file_name); self.delta_table .storage .put_obj(&uri, log_entry.as_bytes()) .await?; Ok(PreparedCommit { uri }) } async fn try_commit_loop( &mut self, commit: &PreparedCommit, ) -> Result<DeltaDataTypeVersion, DeltaTransactionError> { let mut attempt_number: u32 = 0; loop { self.delta_table.update_incremental().await?; let version = self.delta_table.version + 1; match self .delta_table .try_commit_transaction(commit, version) .await { Ok(v) => { return Ok(v); } Err(e) => { match e { DeltaTransactionError::VersionAlreadyExists { .. } if attempt_number > self.options.max_retry_commit_attempts + 1 => { debug!("Transaction attempt failed. Attempts exhausted beyond max_retry_commit_attempts of {} so failing.", self.options.max_retry_commit_attempts); return Err(e); } DeltaTransactionError::VersionAlreadyExists { .. } => { attempt_number += 1; debug!("Transaction attempt failed. Incrementing attempt number to {} and retrying.", attempt_number); } // NOTE: Add other retryable errors as needed here _ => { return Err(e); } } } } } } } /// Holds the uri to prepared commit temporary file created with `DeltaTransaction.prepare_commit`. /// Once created, the actual commit could be executed with `DeltaTransaction.try_commit`. #[derive(Debug)] pub struct PreparedCommit { uri: String, } fn log_entry_from_actions(actions: &[Action]) -> Result<String, serde_json::Error> { let mut jsons = Vec::<String>::new(); for action in actions { let json = serde_json::to_string(action)?; jsons.push(json); } Ok(jsons.join("\n")) } fn process_action( state: &mut DeltaTableState, action: Action, ) -> Result<(), serde_json::error::Error> { match action { Action::add(v) => { state.files.push(v); } Action::remove(v) => { state.files.retain(|a| *a.path != v.path); state.tombstones.push(v); } Action::protocol(v) => { state.min_reader_version = v.min_reader_version; state.min_writer_version = v.min_writer_version; } Action::metaData(v) => { state.current_metadata = Some(DeltaTableMetaData::try_from(v)?); } Action::txn(v) => { *state .app_transaction_version .entry(v.app_id) .or_insert(v.version) = v.version; } Action::commitInfo(v) => { state.commit_infos.push(v); } } Ok(()) } /// Creates and loads a DeltaTable from the given path with current metadata. /// Infers the storage backend to use from the scheme in the given table path. pub async fn open_table(table_uri: &str) -> Result<DeltaTable, DeltaTableError> { let storage_backend = storage::get_backend_for_uri(table_uri)?; let mut table = DeltaTable::new(table_uri, storage_backend)?; table.load().await?; Ok(table) } /// Creates a DeltaTable from the given path and loads it with the metadata from the given version. /// Infers the storage backend to use from the scheme in the given table path. pub async fn open_table_with_version( table_uri: &str, version: DeltaDataTypeVersion, ) -> Result<DeltaTable, DeltaTableError> { let storage_backend = storage::get_backend_for_uri(table_uri)?; let mut table = DeltaTable::new(table_uri, storage_backend)?; table.load_version(version).await?; Ok(table) } /// Creates a DeltaTable from the given path. /// Loads metadata from the version appropriate based on the given ISO-8601/RFC-3339 timestamp. /// Infers the storage backend to use from the scheme in the given table path. pub async fn open_table_with_ds(table_uri: &str, ds: &str) -> Result<DeltaTable, DeltaTableError> { let datetime = DateTime::<Utc>::from(DateTime::<FixedOffset>::parse_from_rfc3339(ds)?); let storage_backend = storage::get_backend_for_uri(table_uri)?; let mut table = DeltaTable::new(table_uri, storage_backend)?; table.load_with_datetime(datetime).await?; Ok(table) } /// Returns rust crate version, can be use used in language bindings to expose Rust core version pub fn crate_version() -> &'static str { env!("CARGO_PKG_VERSION") } #[cfg(test)] mod tests { use super::*; use pretty_assertions::assert_eq; use std::collections::HashMap; #[test] fn state_records_new_txn_version() { let mut app_transaction_version = HashMap::new(); app_transaction_version.insert("abc".to_string(), 1); app_transaction_version.insert("xyz".to_string(), 1); let mut state = DeltaTableState { files: vec![], commit_infos: vec![], tombstones: vec![], current_metadata: None, min_reader_version: 1, min_writer_version: 2, app_transaction_version, }; let txn_action = Action::txn(action::Txn { app_id: "abc".to_string(), version: 2, last_updated: Some(0), }); let _ = process_action(&mut state, txn_action).unwrap(); assert_eq!(2, *state.app_transaction_version.get("abc").unwrap()); assert_eq!(1, *state.app_transaction_version.get("xyz").unwrap()); } #[cfg(feature = "s3")] #[test] fn normalize_table_uri() { for table_uri in [ "s3://tests/data/delta-0.8.0/", "s3://tests/data/delta-0.8.0//", "s3://tests/data/delta-0.8.0", ] .iter() { let be = storage::get_backend_for_uri(table_uri).unwrap(); let table = DeltaTable::new(table_uri, be).unwrap(); assert_eq!(table.table_uri, "s3://tests/data/delta-0.8.0"); } } #[test] fn rel_path() { assert!(matches!( extract_rel_path("data/delta-0.8.0", "data/delta-0.8.0/abc/123"), Ok("abc/123"), )); assert!(matches!( extract_rel_path("data/delta-0.8.0", "data/delta-0.8.0/abc.json"), Ok("abc.json"), )); assert!(matches!( extract_rel_path("data/delta-0.8.0", "tests/abc.json"), Err(DeltaTableError::Generic(_)), )); } #[tokio::test] async fn parquet_filename() { let mut table = open_table("./tests/data/simple_table").await.unwrap(); let txn = DeltaTransaction { delta_table: &mut table, actions: vec![], options: DeltaTransactionOptions::default(), }; let partitions = vec![ (String::from("col1"), String::from("a")), (String::from("col2"), String::from("b")), ]; let parquet_filename = txn.generate_parquet_filename(Some(partitions)); if cfg!(windows) { assert!(parquet_filename.contains("col1=a\\col2=b\\part-00000-")); } else { assert!(parquet_filename.contains("col1=a/col2=b/part-00000-")); } } }
36.15866
350
0.596193
9b0af95f7eec532978b6be9065dfb23e0d448c6f
22,410
use super::{ candidate, chain::{self, AppliedBlock, CheckHeaderProof, LeadershipBlock}, tip::TipUpdater, Blockchain, Error, PreCheckedHeader, Ref, Tip, }; use crate::{ blockcfg::{Block, Header, HeaderHash}, blockchain::Checkpoints, intercom::{self, BlockMsg, NetworkMsg, PropagateMsg, TransactionMsg, WatchMsg}, metrics::{Metrics, MetricsBackend}, topology::NodeId, utils::{ async_msg::{self, MessageBox, MessageQueue}, fire_forget_scheduler::{ FireForgetScheduler, FireForgetSchedulerConfig, FireForgetSchedulerFuture, }, task::TokioServiceInfo, }, }; use chain_core::property::{Block as _, Header as _}; use futures::prelude::*; use tracing::{span, Level}; use tracing_futures::Instrument; use std::{sync::Arc, time::Duration}; type PullHeadersScheduler = FireForgetScheduler<HeaderHash, NodeId, Checkpoints>; type GetNextBlockScheduler = FireForgetScheduler<HeaderHash, NodeId, ()>; const TIP_UPDATE_QUEUE_SIZE: usize = 10; const DEFAULT_TIMEOUT_PROCESS_LEADERSHIP: u64 = 5; const DEFAULT_TIMEOUT_PROCESS_ANNOUNCEMENT: u64 = 5; const DEFAULT_TIMEOUT_PROCESS_BLOCKS: u64 = 60; const DEFAULT_TIMEOUT_PROCESS_HEADERS: u64 = 60; const PULL_HEADERS_SCHEDULER_CONFIG: FireForgetSchedulerConfig = FireForgetSchedulerConfig { max_running: 16, max_running_same_task: 2, command_channel_size: 1024, timeout: Duration::from_millis(500), }; const GET_NEXT_BLOCK_SCHEDULER_CONFIG: FireForgetSchedulerConfig = FireForgetSchedulerConfig { max_running: 16, max_running_same_task: 2, command_channel_size: 1024, timeout: Duration::from_millis(500), }; pub struct TaskData { pub blockchain: Blockchain, pub blockchain_tip: Tip, pub stats_counter: Metrics, pub network_msgbox: MessageBox<NetworkMsg>, pub fragment_msgbox: MessageBox<TransactionMsg>, pub watch_msgbox: MessageBox<WatchMsg>, pub garbage_collection_interval: Duration, } /// The blockchain process is comprised mainly of two parts: /// /// * Bookkeeping of all blocks known to the node: /// This is the most resource heavy operation but can be parallelized depending on the chain structure. /// * Tip selection and update: /// Tip updates must be serialized to avoid inconsistent states but are very light on resources. /// No performance penalty should come from this synchronization point. struct Process { blockchain: Blockchain, blockchain_tip: Tip, stats_counter: Metrics, network_msgbox: MessageBox<NetworkMsg>, fragment_msgbox: MessageBox<TransactionMsg>, watch_msgbox: MessageBox<WatchMsg>, garbage_collection_interval: Duration, tip_update_mbox: MessageBox<Arc<Ref>>, pull_headers_scheduler: PullHeadersScheduler, get_next_block_scheduler: GetNextBlockScheduler, service_info: TokioServiceInfo, } fn spawn_pull_headers_scheduler( network_mbox: MessageBox<NetworkMsg>, info: &TokioServiceInfo, ) -> PullHeadersScheduler { let scheduler_future = FireForgetSchedulerFuture::new( &PULL_HEADERS_SCHEDULER_CONFIG, move |to, node_id, from| { network_mbox .clone() .try_send(NetworkMsg::PullHeaders { node_id, from, to, }) .unwrap_or_else(|e| { tracing::error!(reason = %e.to_string(), "cannot send PullHeaders request to network") }) }, ); let scheduler = scheduler_future.scheduler(); let future = scheduler_future .map_err(move |e| tracing::error!(reason = ?e, "pull headers scheduling failed")); info.spawn_fallible("pull headers scheduling", future); scheduler } fn spawn_get_next_block_scheduler( network_mbox: MessageBox<NetworkMsg>, info: &TokioServiceInfo, ) -> GetNextBlockScheduler { let scheduler_future = FireForgetSchedulerFuture::new( &GET_NEXT_BLOCK_SCHEDULER_CONFIG, move |header_id, node_id, ()| { network_mbox .clone() .try_send(NetworkMsg::GetNextBlock(node_id, header_id)) .unwrap_or_else(|e| { tracing::error!( reason = ?e, "cannot send GetNextBlock request to network" ) }); }, ); let scheduler = scheduler_future.scheduler(); let future = scheduler_future .map_err(move |e| tracing::error!(reason = ?e, "get next block scheduling failed")); info.spawn_fallible("get next block scheduling", future); scheduler } pub async fn start( task_data: TaskData, service_info: TokioServiceInfo, input: MessageQueue<BlockMsg>, ) { let TaskData { blockchain, blockchain_tip, stats_counter, network_msgbox, fragment_msgbox, garbage_collection_interval, watch_msgbox, } = task_data; let (tip_update_mbox, tip_update_queue) = async_msg::channel(TIP_UPDATE_QUEUE_SIZE); let pull_headers_scheduler = spawn_pull_headers_scheduler(network_msgbox.clone(), &service_info); let get_next_block_scheduler = spawn_get_next_block_scheduler(network_msgbox.clone(), &service_info); Process { blockchain, blockchain_tip, stats_counter, network_msgbox, fragment_msgbox, watch_msgbox, garbage_collection_interval, tip_update_mbox, pull_headers_scheduler, get_next_block_scheduler, service_info, } .start(input, tip_update_queue) .await } impl Process { async fn start( mut self, mut input: MessageQueue<BlockMsg>, tip_update_queue: MessageQueue<Arc<Ref>>, ) { self.start_garbage_collector(&self.service_info); let mut tip_updater = TipUpdater::new( self.blockchain_tip.clone(), self.blockchain.clone(), Some(self.fragment_msgbox.clone()), Some(self.watch_msgbox.clone()), self.stats_counter.clone(), ); self.service_info.spawn("tip updater", async move { tip_updater.run(tip_update_queue).await }); while let Some(input) = input.next().await { self.handle_input(input); } } fn handle_input(&mut self, input: BlockMsg) { let blockchain = self.blockchain.clone(); let blockchain_tip = self.blockchain_tip.clone(); let network_msg_box = self.network_msgbox.clone(); let watch_msg_box = self.watch_msgbox.clone(); let stats_counter = self.stats_counter.clone(); tracing::trace!("handling new blockchain task item"); match input { BlockMsg::LeadershipBlock(leadership_block) => { let span = span!( parent: self.service_info.span(), Level::DEBUG, "process_leadership_block", hash = %leadership_block.block.header().hash(), parent = %leadership_block.block.header().parent_id(), date = %leadership_block.block.header().block_date() ); let _enter = span.enter(); tracing::debug!("receiving block from leadership service"); self.service_info.timeout_spawn_fallible( "process leadership block", Duration::from_secs(DEFAULT_TIMEOUT_PROCESS_LEADERSHIP), process_leadership_block( blockchain, self.tip_update_mbox.clone(), network_msg_box, watch_msg_box, *leadership_block, ) .instrument(span.clone()), ); } BlockMsg::AnnouncedBlock(header, node_id) => { let span = span!( parent: self.service_info.span(), Level::DEBUG, "process_announced_block", hash = %header.hash(), parent = %header.parent_id(), date = %header.block_date(), %node_id ); let _enter = span.enter(); tracing::debug!("received block announcement from network"); self.service_info.timeout_spawn_fallible( "process block announcement", Duration::from_secs(DEFAULT_TIMEOUT_PROCESS_ANNOUNCEMENT), process_block_announcement( blockchain, blockchain_tip, *header, node_id, self.pull_headers_scheduler.clone(), self.get_next_block_scheduler.clone(), ) .instrument(span.clone()), ) } BlockMsg::NetworkBlocks(handle) => { let span = span!( parent: self.service_info.span(), Level::DEBUG, "process_network_blocks", ); let _guard = span.enter(); tracing::debug!("receiving block stream from network"); self.service_info.timeout_spawn_fallible( "process network blocks", Duration::from_secs(DEFAULT_TIMEOUT_PROCESS_BLOCKS), process_network_blocks( self.blockchain.clone(), self.tip_update_mbox.clone(), network_msg_box, watch_msg_box, self.get_next_block_scheduler.clone(), handle, stats_counter, ) .instrument(span.clone()), ); } BlockMsg::ChainHeaders(handle) => { let span = span!(parent: self.service_info.span(), Level::DEBUG, "process_chain_headers", sub_task = "chain_pull"); let _enter = span.enter(); tracing::debug!("receiving header stream from network"); self.service_info.timeout_spawn( "process network headers", Duration::from_secs(DEFAULT_TIMEOUT_PROCESS_HEADERS), process_chain_headers( blockchain, handle, self.pull_headers_scheduler.clone(), network_msg_box, ) .instrument(span.clone()), ); } } tracing::trace!("item handling finished"); } fn start_garbage_collector(&self, info: &TokioServiceInfo) { let blockchain = self.blockchain.clone(); let tip = self.blockchain_tip.clone(); async fn blockchain_gc(blockchain: Blockchain, tip: Tip) -> chain::Result<()> { blockchain.gc(tip.get_ref().await).await } info.run_periodic_fallible( "collect stale branches", self.garbage_collection_interval, move || blockchain_gc(blockchain.clone(), tip.clone()), ) } } async fn process_and_propagate_new_ref( new_block_ref: Arc<Ref>, mut tip_update_mbox: MessageBox<Arc<Ref>>, mut network_msg_box: MessageBox<NetworkMsg>, ) -> chain::Result<()> { let header = new_block_ref.header().clone(); let span = span!(Level::DEBUG, "process_and_propagate_new_ref", block = %header.hash()); async { tracing::debug!("processing the new block and propagating"); // Even if this fails because the queue is full we periodically recompute the tip tip_update_mbox .try_send(new_block_ref) .unwrap_or_else(|err| { tracing::error!( "cannot send new ref to be evaluated as candidate tip: {}", err ) }); tracing::debug!("propagating block to the network"); network_msg_box .send(NetworkMsg::Propagate(Box::new(PropagateMsg::Block( Box::new(header), )))) .await?; Ok::<(), Error>(()) } .instrument(span) .await?; Ok(()) } #[allow(clippy::too_many_arguments)] async fn process_leadership_block( mut blockchain: Blockchain, tip_update_mbox: MessageBox<Arc<Ref>>, network_msg_box: MessageBox<NetworkMsg>, mut watch_msg_box: MessageBox<WatchMsg>, leadership_block: LeadershipBlock, ) -> chain::Result<()> { let block = leadership_block.block.clone(); let new_block_ref = process_leadership_block_inner(&mut blockchain, leadership_block).await?; watch_msg_box .send(WatchMsg::NewBlock(block.clone())) .await?; process_and_propagate_new_ref(Arc::clone(&new_block_ref), tip_update_mbox, network_msg_box) .await?; Ok(()) } async fn process_leadership_block_inner( blockchain: &mut Blockchain, leadership_block: LeadershipBlock, ) -> Result<Arc<Ref>, Error> { let applied = blockchain .apply_and_store_leadership_block(leadership_block) .await?; let new_ref = applied .new_ref() .expect("block from leadership must be unique"); tracing::info!("block from leader event successfully stored"); Ok(new_ref) } async fn process_block_announcement( blockchain: Blockchain, blockchain_tip: Tip, header: Header, node_id: NodeId, mut pull_headers_scheduler: PullHeadersScheduler, mut get_next_block_scheduler: GetNextBlockScheduler, ) -> Result<(), Error> { let pre_checked = blockchain.pre_check_header(header, false).await?; match pre_checked { PreCheckedHeader::AlreadyPresent { .. } => { tracing::debug!("block is already present"); Ok(()) } PreCheckedHeader::MissingParent { header, .. } => { tracing::debug!("block is missing a locally stored parent"); let to = header.hash(); let from = blockchain.get_checkpoints(&blockchain_tip.branch().await); pull_headers_scheduler .schedule(to, node_id, from) .unwrap_or_else(move |err| { tracing::error!( reason = ?err, "cannot schedule pulling headers" ) }); Ok(()) } PreCheckedHeader::HeaderWithCache { header, parent_ref: _, } => { tracing::debug!("Announced block has a locally stored parent, fetch it"); get_next_block_scheduler .schedule(header.id(), node_id, ()) .unwrap_or_else(move |err| { tracing::error!( reason = ?err, "cannot schedule getting next block" ) }); Ok(()) } } } #[allow(clippy::too_many_arguments)] async fn process_network_blocks( blockchain: Blockchain, tip_update_mbox: MessageBox<Arc<Ref>>, network_msg_box: MessageBox<NetworkMsg>, mut watch_msg_box: MessageBox<WatchMsg>, mut get_next_block_scheduler: GetNextBlockScheduler, handle: intercom::RequestStreamHandle<Block, ()>, stats_counter: Metrics, ) -> Result<(), Error> { let (mut stream, reply) = handle.into_stream_and_reply(); let mut candidate = None; let maybe_updated: Option<Arc<Ref>> = loop { let (maybe_block, stream_tail) = stream.into_future().await; match maybe_block { Some(block) => { let res = process_network_block( &blockchain, block.clone(), &mut watch_msg_box, &mut get_next_block_scheduler, ) .await; match res { Ok(Some(r)) => { stats_counter.add_block_recv_cnt(1); stream = stream_tail; candidate = Some(r); } Ok(None) => { reply.reply_ok(()); break candidate; } Err(e) => { tracing::info!( reason = ?e, "validation of an incoming block failed" ); reply.reply_error(network_block_error_into_reply(e)); break candidate; } } } None => { reply.reply_ok(()); break candidate; } } }; match maybe_updated { Some(new_block_ref) => { process_and_propagate_new_ref( Arc::clone(&new_block_ref), tip_update_mbox, network_msg_box, ) .await?; Ok(()) } None => Ok(()), } } async fn process_network_block( blockchain: &Blockchain, block: Block, watch_msg_box: &mut MessageBox<WatchMsg>, get_next_block_scheduler: &mut GetNextBlockScheduler, ) -> Result<Option<Arc<Ref>>, chain::Error> { let header = block.header().clone(); let span = tracing::span!( Level::DEBUG, "network_block", block = %header.hash(), parent = %header.parent_id(), date = %header.block_date(), ); async { get_next_block_scheduler .declare_completed(block.id()) .unwrap_or_else( |e| tracing::error!(reason = ?e, "get next block schedule completion failed"), ); let pre_checked = blockchain.pre_check_header(header, false).await?; match pre_checked { PreCheckedHeader::AlreadyPresent { .. } => { tracing::debug!("block is already present"); Ok(None) } PreCheckedHeader::MissingParent { header } => { let parent_hash = header.parent_id(); tracing::debug!("block is missing a locally stored parent"); Err(Error::MissingParentBlock(parent_hash)) } PreCheckedHeader::HeaderWithCache { parent_ref, .. } => { let r = check_and_apply_block(blockchain, parent_ref, block, watch_msg_box).await; r } } } .instrument(span) .await } async fn check_and_apply_block( blockchain: &Blockchain, parent_ref: Arc<Ref>, block: Block, watch_msg_box: &mut MessageBox<WatchMsg>, ) -> Result<Option<Arc<Ref>>, chain::Error> { let post_checked = blockchain .post_check_header( block.header().clone(), parent_ref, CheckHeaderProof::Enabled, ) .await?; tracing::debug!("applying block to storage"); let block_for_watchers = block.clone(); let applied_block = blockchain .apply_and_store_block(post_checked, block) .await?; if let AppliedBlock::New(block_ref) = applied_block { tracing::debug!("applied block to storage"); watch_msg_box .try_send(WatchMsg::NewBlock(block_for_watchers)) .unwrap_or_else(|err| { tracing::error!("cannot propagate block to watch clients: {}", err) }); Ok(Some(block_ref)) } else { tracing::debug!("block is already present in storage, not applied"); Ok(None) } } async fn process_chain_headers( blockchain: Blockchain, handle: intercom::RequestStreamHandle<Header, ()>, mut pull_headers_scheduler: PullHeadersScheduler, mut network_msg_box: MessageBox<NetworkMsg>, ) { let (stream, reply) = handle.into_stream_and_reply(); match candidate::advance_branch(blockchain, stream).await { Err(e) => { tracing::info!( reason = %e, "error processing an incoming header stream" ); reply.reply_error(chain_header_error_into_reply(e)); } Ok((header_ids, _maybe_remainder)) => { header_ids .iter() .try_for_each(|header_id| pull_headers_scheduler.declare_completed(*header_id)) .unwrap_or_else( |e| tracing::error!(reason = ?e, "get blocks schedule completion failed"), ); if !header_ids.is_empty() { network_msg_box .send(NetworkMsg::GetBlocks(header_ids)) .await .map_err(|_| tracing::error!("cannot request blocks from network")) .map(|_| ()) .unwrap(); reply.reply_ok(()) // TODO: if the stream is not ended, resume processing // after more blocks arrive } } } } fn network_block_error_into_reply(err: chain::Error) -> intercom::Error { use super::chain::Error::*; match err { Storage(e) => intercom::Error::failed(e), Ledger(e) => intercom::Error::failed_precondition(e), Block0(e) => intercom::Error::failed(e), MissingParentBlock(_) => intercom::Error::failed_precondition(err.to_string()), BlockHeaderVerificationFailed(_) => intercom::Error::invalid_argument(err.to_string()), _ => intercom::Error::failed(err.to_string()), } } fn chain_header_error_into_reply(err: candidate::Error) -> intercom::Error { use super::candidate::Error::*; // TODO: more detailed error case matching match err { Blockchain(e) => intercom::Error::failed(e.to_string()), EmptyHeaderStream => intercom::Error::invalid_argument(err.to_string()), MissingParentBlock(_) => intercom::Error::failed_precondition(err.to_string()), BrokenHeaderChain(_) => intercom::Error::invalid_argument(err.to_string()), HeaderChainVerificationFailed(e) => intercom::Error::invalid_argument(e), } }
34.906542
131
0.571664
380fbdeb8c27ca8d18a6eb3204783a1e54188d6a
170
#![feature(existential_type)] fn main() {} existential type Two<T, U>: 'static; //~ ERROR type parameter `U` is unused fn one<T: 'static>(t: T) -> Two<T, T> { t }
17
75
0.6
e5f4080de1cf766aa8adaec939c2726b8663aab5
9,625
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use graphql_syntax::OperationKind; use rand::seq::SliceRandom; use relay_transforms::extract_module_name; use std::{collections::HashSet, fmt}; #[derive(Clone, Copy, Debug)] pub enum DefinitionNameSuffix { Query, Mutation, Subscription, } impl From<&OperationKind> for DefinitionNameSuffix { fn from(kind: &OperationKind) -> Self { match kind { OperationKind::Query => DefinitionNameSuffix::Query, OperationKind::Subscription => DefinitionNameSuffix::Subscription, OperationKind::Mutation => DefinitionNameSuffix::Mutation, } } } impl fmt::Display for DefinitionNameSuffix { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", self) } } /// This function will create a default name suggestion for operation/fragment in a file. /// Default name is {prefix}{Query|Mutation|Subscription}, /// where {prefix} is a cameCased base file stem, without extension and suffix (like .react.js, .jsx, etc..) pub fn create_default_name(file_name: &str, suffix: DefinitionNameSuffix) -> Option<String> { let module_name = extract_module_name(file_name)?; if module_name.ends_with(&suffix.to_string()) { Some(module_name) } else { Some(format!("{}{}", module_name, suffix)) } } /// This function will create a name suggestion for operation/fragment /// in a file adding an incremental index. /// Suggested name is {prefix}{index}{Query|Mutation|Subscription}, /// We will keep incrementing the index, /// while the suggested name is not in the already used names in the file. pub fn create_default_name_with_index( file_name: &str, suffix: DefinitionNameSuffix, used_names: &HashSet<String>, ) -> Option<String> { let module_name = extract_module_name(file_name)?; let mut index = 1; loop { let new_name = format!("{}{}{}", module_name, index, suffix); if used_names.contains(&new_name) { index += 1; } else { return Some(new_name); } } } /// If you already have a name for your fragment/operation, /// it doesn't start/end with correct prefixes/suffixes - /// this function will return a correctly wrapped name. pub fn create_name_wrapper( original_name: &str, file_name: &str, suffix: DefinitionNameSuffix, ) -> Option<String> { let module_name = extract_module_name(file_name)?; let new_prefix = if original_name.starts_with(&module_name) { None } else { Some(module_name) }; let new_suffix = if original_name.ends_with(&suffix.to_string()) { None } else { Some(suffix) }; // if the `original_name` already have correct prefix/suffix, we don't need to return anything if new_prefix.is_none() && new_suffix.is_none() { None } else { let new_name = format!( "{}{}{}", match new_prefix { Some(value) => value, None => "".to_string(), }, original_name, match new_suffix { Some(value) => value.to_string(), None => "".to_string(), }, ); Some(new_name) } } /// This function will create a very impactful name for your query/fragment pub fn create_impactful_name(file_name: &str, suffix: DefinitionNameSuffix) -> Option<String> { let module_name = extract_module_name(file_name)?; // This will make your query/fragment more impactful let impact = create_impactful_part(); Some(format!("{}{}{}", module_name, impact, suffix)) } fn create_impactful_part() -> String { let adjectives = vec![ "Redefined", "Awesome", "Formidable", "Remarkable", "Outstanding", "Fantastic", "Striking", "Noticeable", "Perceptible", "Fast", "Brisk", "Super", "Cool", "Impactful", "Meaningful", "DoubleQuick", "Prominent", "Swift", "Successful", "Impressive", "Egregious", "HighQuality", "Redefining", "Unique", "Impossible", "Robust", "Comprehensive", "Bold", "Useful", "Disruptive", "TopNotch", "WorldClass", "Exceptional", ]; let nouns = vec![ "Expectation", "Impact", "Awesomeness", "Feature", "Fix", "Improvement", "Implementation", "Project", "Success", "Profit", "Product", "Goal", "Effort", "Performance", "Result", "Solution", ]; let adjective: &str = adjectives .choose(&mut rand::thread_rng()) .unwrap_or(&adjectives[0]); let noun: &str = nouns.choose(&mut rand::thread_rng()).unwrap_or(&nouns[0]); format!("{}{}", adjective, noun) } #[cfg(not(windows))] #[cfg(test)] mod tests { use super::{ create_default_name, create_default_name_with_index, create_name_wrapper, DefinitionNameSuffix, }; use std::collections::HashSet; #[test] fn test_create_default_name() { assert_eq!( create_default_name("/data/user/ReactFile.js", DefinitionNameSuffix::Query), Some("ReactFileQuery".to_string()) ); assert_eq!( create_default_name("/data/user/react-file.js", DefinitionNameSuffix::Query), Some("reactFileQuery".to_string()) ); assert_eq!( create_default_name("/data/user/My_react-file.js", DefinitionNameSuffix::Query), Some("MyReactFileQuery".to_string()) ); assert_eq!( create_default_name("/data/user/ReactFile.react.js", DefinitionNameSuffix::Query), Some("ReactFileQuery".to_string()) ); assert_eq!( create_default_name( "/data/user/ReactFile.android.js", DefinitionNameSuffix::Query ), Some("ReactFileAndroidQuery".to_string()) ); assert_eq!( create_default_name("/data/user/ReactFile.ios.js", DefinitionNameSuffix::Query), Some("ReactFileIosQuery".to_string()) ); assert_eq!( create_default_name("ReactFile", DefinitionNameSuffix::Query), Some("ReactFileQuery".to_string()) ); assert_eq!( create_default_name( "/data/users/project/EntityCreateMutation.js", DefinitionNameSuffix::Mutation ), Some("EntityCreateMutation".to_string()) ); assert_eq!( create_default_name("0001-----2-2-2", DefinitionNameSuffix::Query), Some("0001222Query".to_string()) ); } #[test] fn test_name_with_index1() { let mut used_names = HashSet::new(); used_names.insert("ReactFileQuery".to_string()); assert_eq!( create_default_name_with_index( "/data/user/ReactFile.js", DefinitionNameSuffix::Query, &used_names ), Some("ReactFile1Query".to_string()) ); } #[test] fn test_name_with_index_after_suffix() { let used_names = HashSet::new(); assert_eq!( create_default_name_with_index( "/data/users/project/EntityCreateMutation.js", DefinitionNameSuffix::Mutation, &used_names ), Some("EntityCreateMutation1Mutation".to_string()) ); } #[test] fn test_name_with_index2() { let mut used_names = HashSet::new(); used_names.insert("ReactFileQuery".to_string()); used_names.insert("ReactFile1Query".to_string()); assert_eq!( create_default_name_with_index( "/data/user/ReactFile.js", DefinitionNameSuffix::Query, &used_names ), Some("ReactFile2Query".to_string()) ); } #[test] fn test_create_name_wrapper() { assert_eq!( create_name_wrapper( "MyQuery", "/data/user/ReactFile.js", DefinitionNameSuffix::Query ), Some("ReactFileMyQuery".to_string()) ); assert_eq!( create_name_wrapper( "ReactFileMyQuery", "/data/user/ReactFile.js", DefinitionNameSuffix::Query ), None ); assert_eq!( create_name_wrapper( "Test", "/data/user/ReactFile.js", DefinitionNameSuffix::Query ), Some("ReactFileTestQuery".to_string()) ); } } #[cfg(windows)] #[cfg(test)] mod tests { use super::{create_default_name, DefinitionNameSuffix}; #[test] fn test_create_default_name() { assert_eq!( create_default_name("C:\\user\\ReactFile.js", DefinitionNameSuffix::Query), Some("ReactFileQuery".to_string()) ); assert_eq!( create_default_name( "\\\\?\\D:\\data\\user\\react-file.js", DefinitionNameSuffix::Query ), Some("reactFileQuery".to_string()) ); } }
29.434251
108
0.569039
9b485ec619d74e0015edff5600cf2a5fee7e2727
889
use { crate::{ templates::{pages, partials, Layout, Width}, utils, }, common::{database::Database, models::Id, prelude::*}, enrgy::{web, HttpResponse}, }; pub fn story( db: web::Data<Database>, id: web::ParseParam<"id", Id>, index: web::Param<"chapter">, ) -> HttpResponse { utils::wrap(|| { let index: usize = index.parse().map_err(anyhow::Error::from)?; let story = utils::get_story_full(&*db, &id)?; let chapter = db.get_chapter_body(&id, index)?; let body = Layout::new( Width::Slim, db.settings().theme, story.info.title.clone(), None, pages::Chapter::new( partials::StoryPartial::new(&id, story, None)?, &chapter, index, ), ); Ok(crate::res!(200; body)) }) }
24.694444
71
0.497188
bf3c53daa7309fcb6cd320411d90575f41163d04
113,187
//! A cross-platform graphics and compute library based on [WebGPU](https://gpuweb.github.io/gpuweb/). //! //! To start using the API, create an [`Instance`]. #![doc(html_logo_url = "https://raw.githubusercontent.com/gfx-rs/wgpu/master/logo.png")] #![warn(missing_docs)] mod backend; pub mod util; #[macro_use] mod macros; use std::{ borrow::Cow, error, fmt::{Debug, Display}, future::Future, marker::PhantomData, num::{NonZeroU32, NonZeroU8}, ops::{Bound, Range, RangeBounds}, sync::Arc, thread, }; use parking_lot::Mutex; pub use wgt::{ AdapterInfo, AddressMode, Backend, Backends, BindGroupLayoutEntry, BindingType, BlendComponent, BlendFactor, BlendOperation, BlendState, BufferAddress, BufferBindingType, BufferSize, BufferUsages, Color, ColorTargetState, ColorWrites, CommandBufferDescriptor, CompareFunction, DepthBiasState, DepthStencilState, DeviceType, DownlevelCapabilities, DownlevelFlags, DynamicOffset, Extent3d, Face, Features, FilterMode, FrontFace, ImageDataLayout, ImageSubresourceRange, IndexFormat, Limits, MultisampleState, Origin3d, PipelineStatisticsTypes, PolygonMode, PowerPreference, PresentMode, PrimitiveState, PrimitiveTopology, PushConstantRange, QueryType, RenderBundleDepthStencil, SamplerBorderColor, ShaderLocation, ShaderModel, ShaderStages, StencilFaceState, StencilOperation, StencilState, StorageTextureAccess, SurfaceConfiguration, SurfaceStatus, TextureAspect, TextureDimension, TextureFormat, TextureFormatFeatureFlags, TextureFormatFeatures, TextureSampleType, TextureUsages, TextureViewDimension, VertexAttribute, VertexFormat, VertexStepMode, BIND_BUFFER_ALIGNMENT, COPY_BUFFER_ALIGNMENT, COPY_BYTES_PER_ROW_ALIGNMENT, MAP_ALIGNMENT, PUSH_CONSTANT_ALIGNMENT, QUERY_SET_MAX_QUERIES, QUERY_SIZE, VERTEX_STRIDE_ALIGNMENT, }; use backend::{BufferMappedRange, Context as C}; trait ComputePassInner<Ctx: Context> { fn set_pipeline(&mut self, pipeline: &Ctx::ComputePipelineId); fn set_bind_group( &mut self, index: u32, bind_group: &Ctx::BindGroupId, offsets: &[DynamicOffset], ); fn set_push_constants(&mut self, offset: u32, data: &[u8]); fn insert_debug_marker(&mut self, label: &str); fn push_debug_group(&mut self, group_label: &str); fn pop_debug_group(&mut self); fn write_timestamp(&mut self, query_set: &Ctx::QuerySetId, query_index: u32); fn begin_pipeline_statistics_query(&mut self, query_set: &Ctx::QuerySetId, query_index: u32); fn end_pipeline_statistics_query(&mut self); fn dispatch(&mut self, x: u32, y: u32, z: u32); fn dispatch_indirect( &mut self, indirect_buffer: &Ctx::BufferId, indirect_offset: BufferAddress, ); } trait RenderInner<Ctx: Context> { fn set_pipeline(&mut self, pipeline: &Ctx::RenderPipelineId); fn set_bind_group( &mut self, index: u32, bind_group: &Ctx::BindGroupId, offsets: &[DynamicOffset], ); fn set_index_buffer( &mut self, buffer: &Ctx::BufferId, index_format: IndexFormat, offset: BufferAddress, size: Option<BufferSize>, ); fn set_vertex_buffer( &mut self, slot: u32, buffer: &Ctx::BufferId, offset: BufferAddress, size: Option<BufferSize>, ); fn set_push_constants(&mut self, stages: ShaderStages, offset: u32, data: &[u8]); fn draw(&mut self, vertices: Range<u32>, instances: Range<u32>); fn draw_indexed(&mut self, indices: Range<u32>, base_vertex: i32, instances: Range<u32>); fn draw_indirect(&mut self, indirect_buffer: &Ctx::BufferId, indirect_offset: BufferAddress); fn draw_indexed_indirect( &mut self, indirect_buffer: &Ctx::BufferId, indirect_offset: BufferAddress, ); fn multi_draw_indirect( &mut self, indirect_buffer: &Ctx::BufferId, indirect_offset: BufferAddress, count: u32, ); fn multi_draw_indexed_indirect( &mut self, indirect_buffer: &Ctx::BufferId, indirect_offset: BufferAddress, count: u32, ); fn multi_draw_indirect_count( &mut self, indirect_buffer: &Ctx::BufferId, indirect_offset: BufferAddress, count_buffer: &Ctx::BufferId, count_buffer_offset: BufferAddress, max_count: u32, ); fn multi_draw_indexed_indirect_count( &mut self, indirect_buffer: &Ctx::BufferId, indirect_offset: BufferAddress, count_buffer: &Ctx::BufferId, count_buffer_offset: BufferAddress, max_count: u32, ); } trait RenderPassInner<Ctx: Context>: RenderInner<Ctx> { fn set_blend_constant(&mut self, color: Color); fn set_scissor_rect(&mut self, x: u32, y: u32, width: u32, height: u32); fn set_viewport( &mut self, x: f32, y: f32, width: f32, height: f32, min_depth: f32, max_depth: f32, ); fn set_stencil_reference(&mut self, reference: u32); fn insert_debug_marker(&mut self, label: &str); fn push_debug_group(&mut self, group_label: &str); fn pop_debug_group(&mut self); fn write_timestamp(&mut self, query_set: &Ctx::QuerySetId, query_index: u32); fn begin_pipeline_statistics_query(&mut self, query_set: &Ctx::QuerySetId, query_index: u32); fn end_pipeline_statistics_query(&mut self); fn execute_bundles<'a, I: Iterator<Item = &'a Ctx::RenderBundleId>>( &mut self, render_bundles: I, ); } trait Context: Debug + Send + Sized + Sync { type AdapterId: Debug + Send + Sync + 'static; type DeviceId: Debug + Send + Sync + 'static; type QueueId: Debug + Send + Sync + 'static; type ShaderModuleId: Debug + Send + Sync + 'static; type BindGroupLayoutId: Debug + Send + Sync + 'static; type BindGroupId: Debug + Send + Sync + 'static; type TextureViewId: Debug + Send + Sync + 'static; type SamplerId: Debug + Send + Sync + 'static; type BufferId: Debug + Send + Sync + 'static; type TextureId: Debug + Send + Sync + 'static; type QuerySetId: Debug + Send + Sync + 'static; type PipelineLayoutId: Debug + Send + Sync + 'static; type RenderPipelineId: Debug + Send + Sync + 'static; type ComputePipelineId: Debug + Send + Sync + 'static; type CommandEncoderId: Debug; type ComputePassId: Debug + ComputePassInner<Self>; type RenderPassId: Debug + RenderPassInner<Self>; type CommandBufferId: Debug + Send + Sync; type RenderBundleEncoderId: Debug + RenderInner<Self>; type RenderBundleId: Debug + Send + Sync + 'static; type SurfaceId: Debug + Send + Sync + 'static; type SurfaceOutputDetail: Send; type RequestAdapterFuture: Future<Output = Option<Self::AdapterId>> + Send; type RequestDeviceFuture: Future<Output = Result<(Self::DeviceId, Self::QueueId), RequestDeviceError>> + Send; type MapAsyncFuture: Future<Output = Result<(), BufferAsyncError>> + Send; type OnSubmittedWorkDoneFuture: Future<Output = ()> + Send; fn init(backends: Backends) -> Self; fn instance_create_surface( &self, handle: &impl raw_window_handle::HasRawWindowHandle, ) -> Self::SurfaceId; fn instance_request_adapter( &self, options: &RequestAdapterOptions<'_>, ) -> Self::RequestAdapterFuture; fn adapter_request_device( self: &Arc<Self>, adapter: &Self::AdapterId, desc: &DeviceDescriptor, auto_poll: bool, trace_dir: Option<&std::path::Path>, ) -> Self::RequestDeviceFuture; fn instance_poll_all_devices(&self, force_wait: bool); fn adapter_is_surface_supported( &self, adapter: &Self::AdapterId, surface: &Self::SurfaceId, ) -> bool; fn adapter_features(&self, adapter: &Self::AdapterId) -> Features; fn adapter_limits(&self, adapter: &Self::AdapterId) -> Limits; fn adapter_downlevel_properties(&self, adapter: &Self::AdapterId) -> DownlevelCapabilities; fn adapter_get_info(&self, adapter: &Self::AdapterId) -> AdapterInfo; fn adapter_get_texture_format_features( &self, adapter: &Self::AdapterId, format: TextureFormat, ) -> TextureFormatFeatures; fn surface_get_preferred_format( &self, surface: &Self::SurfaceId, adapter: &Self::AdapterId, ) -> Option<TextureFormat>; fn surface_configure( &self, surface: &Self::SurfaceId, device: &Self::DeviceId, config: &SurfaceConfiguration, ); fn surface_get_current_texture( &self, surface: &Self::SurfaceId, ) -> ( Option<Self::TextureId>, SurfaceStatus, Self::SurfaceOutputDetail, ); fn surface_present(&self, texture: &Self::TextureId, detail: &Self::SurfaceOutputDetail); fn device_features(&self, device: &Self::DeviceId) -> Features; fn device_limits(&self, device: &Self::DeviceId) -> Limits; fn device_downlevel_properties(&self, device: &Self::DeviceId) -> DownlevelCapabilities; fn device_create_shader_module( &self, device: &Self::DeviceId, desc: &ShaderModuleDescriptor, ) -> Self::ShaderModuleId; unsafe fn device_create_shader_module_spirv( &self, device: &Self::DeviceId, desc: &ShaderModuleDescriptorSpirV, ) -> Self::ShaderModuleId; fn device_create_bind_group_layout( &self, device: &Self::DeviceId, desc: &BindGroupLayoutDescriptor, ) -> Self::BindGroupLayoutId; fn device_create_bind_group( &self, device: &Self::DeviceId, desc: &BindGroupDescriptor, ) -> Self::BindGroupId; fn device_create_pipeline_layout( &self, device: &Self::DeviceId, desc: &PipelineLayoutDescriptor, ) -> Self::PipelineLayoutId; fn device_create_render_pipeline( &self, device: &Self::DeviceId, desc: &RenderPipelineDescriptor, ) -> Self::RenderPipelineId; fn device_create_compute_pipeline( &self, device: &Self::DeviceId, desc: &ComputePipelineDescriptor, ) -> Self::ComputePipelineId; fn device_create_buffer( &self, device: &Self::DeviceId, desc: &BufferDescriptor, ) -> Self::BufferId; fn device_create_texture( &self, device: &Self::DeviceId, desc: &TextureDescriptor, ) -> Self::TextureId; fn device_create_sampler( &self, device: &Self::DeviceId, desc: &SamplerDescriptor, ) -> Self::SamplerId; fn device_create_query_set( &self, device: &Self::DeviceId, desc: &QuerySetDescriptor, ) -> Self::QuerySetId; fn device_create_command_encoder( &self, device: &Self::DeviceId, desc: &CommandEncoderDescriptor, ) -> Self::CommandEncoderId; fn device_create_render_bundle_encoder( &self, device: &Self::DeviceId, desc: &RenderBundleEncoderDescriptor, ) -> Self::RenderBundleEncoderId; fn device_drop(&self, device: &Self::DeviceId); fn device_poll(&self, device: &Self::DeviceId, maintain: Maintain); fn device_on_uncaptured_error( &self, device: &Self::DeviceId, handler: impl UncapturedErrorHandler, ); fn buffer_map_async( &self, buffer: &Self::BufferId, mode: MapMode, range: Range<BufferAddress>, ) -> Self::MapAsyncFuture; fn buffer_get_mapped_range( &self, buffer: &Self::BufferId, sub_range: Range<BufferAddress>, ) -> BufferMappedRange; fn buffer_unmap(&self, buffer: &Self::BufferId); fn texture_create_view( &self, texture: &Self::TextureId, desc: &TextureViewDescriptor, ) -> Self::TextureViewId; fn surface_drop(&self, surface: &Self::SurfaceId); fn adapter_drop(&self, adapter: &Self::AdapterId); fn buffer_destroy(&self, buffer: &Self::BufferId); fn buffer_drop(&self, buffer: &Self::BufferId); fn texture_destroy(&self, buffer: &Self::TextureId); fn texture_drop(&self, texture: &Self::TextureId); fn texture_view_drop(&self, texture_view: &Self::TextureViewId); fn sampler_drop(&self, sampler: &Self::SamplerId); fn query_set_drop(&self, query_set: &Self::QuerySetId); fn bind_group_drop(&self, bind_group: &Self::BindGroupId); fn bind_group_layout_drop(&self, bind_group_layout: &Self::BindGroupLayoutId); fn pipeline_layout_drop(&self, pipeline_layout: &Self::PipelineLayoutId); fn shader_module_drop(&self, shader_module: &Self::ShaderModuleId); fn command_encoder_drop(&self, command_encoder: &Self::CommandEncoderId); fn command_buffer_drop(&self, command_buffer: &Self::CommandBufferId); fn render_bundle_drop(&self, render_bundle: &Self::RenderBundleId); fn compute_pipeline_drop(&self, pipeline: &Self::ComputePipelineId); fn render_pipeline_drop(&self, pipeline: &Self::RenderPipelineId); fn compute_pipeline_get_bind_group_layout( &self, pipeline: &Self::ComputePipelineId, index: u32, ) -> Self::BindGroupLayoutId; fn render_pipeline_get_bind_group_layout( &self, pipeline: &Self::RenderPipelineId, index: u32, ) -> Self::BindGroupLayoutId; fn command_encoder_copy_buffer_to_buffer( &self, encoder: &Self::CommandEncoderId, source: &Self::BufferId, source_offset: BufferAddress, destination: &Self::BufferId, destination_offset: BufferAddress, copy_size: BufferAddress, ); fn command_encoder_copy_buffer_to_texture( &self, encoder: &Self::CommandEncoderId, source: ImageCopyBuffer, destination: ImageCopyTexture, copy_size: Extent3d, ); fn command_encoder_copy_texture_to_buffer( &self, encoder: &Self::CommandEncoderId, source: ImageCopyTexture, destination: ImageCopyBuffer, copy_size: Extent3d, ); fn command_encoder_copy_texture_to_texture( &self, encoder: &Self::CommandEncoderId, source: ImageCopyTexture, destination: ImageCopyTexture, copy_size: Extent3d, ); fn command_encoder_begin_compute_pass( &self, encoder: &Self::CommandEncoderId, desc: &ComputePassDescriptor, ) -> Self::ComputePassId; fn command_encoder_end_compute_pass( &self, encoder: &Self::CommandEncoderId, pass: &mut Self::ComputePassId, ); fn command_encoder_begin_render_pass<'a>( &self, encoder: &Self::CommandEncoderId, desc: &RenderPassDescriptor<'a, '_>, ) -> Self::RenderPassId; fn command_encoder_end_render_pass( &self, encoder: &Self::CommandEncoderId, pass: &mut Self::RenderPassId, ); fn command_encoder_finish(&self, encoder: Self::CommandEncoderId) -> Self::CommandBufferId; fn command_encoder_clear_image( &self, encoder: &Self::CommandEncoderId, texture: &Texture, subresource_range: &ImageSubresourceRange, ); fn command_encoder_clear_buffer( &self, encoder: &Self::CommandEncoderId, buffer: &Buffer, offset: BufferAddress, size: Option<BufferSize>, ); fn command_encoder_insert_debug_marker(&self, encoder: &Self::CommandEncoderId, label: &str); fn command_encoder_push_debug_group(&self, encoder: &Self::CommandEncoderId, label: &str); fn command_encoder_pop_debug_group(&self, encoder: &Self::CommandEncoderId); fn command_encoder_write_timestamp( &self, encoder: &Self::CommandEncoderId, query_set: &Self::QuerySetId, query_index: u32, ); fn command_encoder_resolve_query_set( &self, encoder: &Self::CommandEncoderId, query_set: &Self::QuerySetId, first_query: u32, query_count: u32, destination: &Self::BufferId, destination_offset: BufferAddress, ); fn render_bundle_encoder_finish( &self, encoder: Self::RenderBundleEncoderId, desc: &RenderBundleDescriptor, ) -> Self::RenderBundleId; fn queue_write_buffer( &self, queue: &Self::QueueId, buffer: &Self::BufferId, offset: BufferAddress, data: &[u8], ); fn queue_write_texture( &self, queue: &Self::QueueId, texture: ImageCopyTexture, data: &[u8], data_layout: ImageDataLayout, size: Extent3d, ); fn queue_submit<I: Iterator<Item = Self::CommandBufferId>>( &self, queue: &Self::QueueId, command_buffers: I, ); fn queue_get_timestamp_period(&self, queue: &Self::QueueId) -> f32; fn queue_on_submitted_work_done( &self, queue: &Self::QueueId, ) -> Self::OnSubmittedWorkDoneFuture; fn device_start_capture(&self, device: &Self::DeviceId); fn device_stop_capture(&self, device: &Self::DeviceId); } /// Context for all other wgpu objects. Instance of wgpu. /// /// This is the first thing you create when using wgpu. /// Its primary use is to create [`Adapter`]s and [`Surface`]s. /// /// Does not have to be kept alive. #[derive(Debug)] pub struct Instance { context: Arc<C>, } /// Handle to a physical graphics and/or compute device. /// /// Adapters can be used to open a connection to the corresponding [`Device`] /// on the host system by using [`Adapter::request_device`]. /// /// Does not have to be kept alive. #[derive(Debug)] pub struct Adapter { context: Arc<C>, id: <C as Context>::AdapterId, } impl Drop for Adapter { fn drop(&mut self) { if !thread::panicking() { self.context.adapter_drop(&self.id) } } } /// Open connection to a graphics and/or compute device. /// /// Responsible for the creation of most rendering and compute resources. /// These are then used in commands, which are submitted to a [`Queue`]. /// /// A device may be requested from an adapter with [`Adapter::request_device`]. #[derive(Debug)] pub struct Device { context: Arc<C>, id: <C as Context>::DeviceId, } /// Passed to [`Device::poll`] to control if it should block or not. This has no effect on /// the web. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum Maintain { /// Block Wait, /// Don't block Poll, } /// The main purpose of this struct is to resolve mapped ranges (convert sizes /// to end points), and to ensure that the sub-ranges don't intersect. #[derive(Debug)] struct MapContext { total_size: BufferAddress, initial_range: Range<BufferAddress>, sub_ranges: Vec<Range<BufferAddress>>, } impl MapContext { fn new(total_size: BufferAddress) -> Self { Self { total_size, initial_range: 0..0, sub_ranges: Vec::new(), } } fn reset(&mut self) { self.initial_range = 0..0; assert!( self.sub_ranges.is_empty(), "You cannot unmap a buffer that still has accessible mapped views" ); } fn add(&mut self, offset: BufferAddress, size: Option<BufferSize>) -> BufferAddress { let end = match size { Some(s) => offset + s.get(), None => self.initial_range.end, }; assert!(self.initial_range.start <= offset && end <= self.initial_range.end); for sub in self.sub_ranges.iter() { assert!( end <= sub.start || offset >= sub.end, "Intersecting map range with {:?}", sub ); } self.sub_ranges.push(offset..end); end } fn remove(&mut self, offset: BufferAddress, size: Option<BufferSize>) { let end = match size { Some(s) => offset + s.get(), None => self.initial_range.end, }; let index = self .sub_ranges .iter() .position(|r| *r == (offset..end)) .expect("unable to remove range from map context"); self.sub_ranges.swap_remove(index); } } /// Handle to a GPU-accessible buffer. /// /// Created with [`Device::create_buffer`] or /// [`DeviceExt::create_buffer_init`](util::DeviceExt::create_buffer_init). #[derive(Debug)] pub struct Buffer { context: Arc<C>, id: <C as Context>::BufferId, map_context: Mutex<MapContext>, usage: BufferUsages, } /// Slice into a [`Buffer`]. /// /// Created by calling [`Buffer::slice`]. To use the whole buffer, call with unbounded slice: /// /// `buffer.slice(..)` #[derive(Copy, Clone, Debug)] pub struct BufferSlice<'a> { buffer: &'a Buffer, offset: BufferAddress, size: Option<BufferSize>, } /// Handle to a texture on the GPU. /// /// Created by calling [`Device::create_texture`] #[derive(Debug)] pub struct Texture { context: Arc<C>, id: <C as Context>::TextureId, owned: bool, } /// Handle to a texture view. /// /// A `TextureView` object describes a texture and associated metadata needed by a /// [`RenderPipeline`] or [`BindGroup`]. #[derive(Debug)] pub struct TextureView { context: Arc<C>, id: <C as Context>::TextureViewId, } /// Handle to a sampler. /// /// A `Sampler` object defines how a pipeline will sample from a [`TextureView`]. Samplers define /// image filters (including anisotropy) and address (wrapping) modes, among other things. See /// the documentation for [`SamplerDescriptor`] for more information. #[derive(Debug)] pub struct Sampler { context: Arc<C>, id: <C as Context>::SamplerId, } impl Drop for Sampler { fn drop(&mut self) { if !thread::panicking() { self.context.sampler_drop(&self.id); } } } /// Handle to a presentable surface. /// /// A `Surface` represents a platform-specific surface (e.g. a window) onto which rendered images may /// be presented. A `Surface` may be created with the unsafe function [`Instance::create_surface`]. #[derive(Debug)] pub struct Surface { context: Arc<C>, id: <C as Context>::SurfaceId, } impl Drop for Surface { fn drop(&mut self) { if !thread::panicking() { self.context.surface_drop(&self.id) } } } /// Handle to a binding group layout. /// /// A `BindGroupLayout` is a handle to the GPU-side layout of a binding group. It can be used to /// create a [`BindGroupDescriptor`] object, which in turn can be used to create a [`BindGroup`] /// object with [`Device::create_bind_group`]. A series of `BindGroupLayout`s can also be used to /// create a [`PipelineLayoutDescriptor`], which can be used to create a [`PipelineLayout`]. #[derive(Debug)] pub struct BindGroupLayout { context: Arc<C>, id: <C as Context>::BindGroupLayoutId, } impl Drop for BindGroupLayout { fn drop(&mut self) { if !thread::panicking() { self.context.bind_group_layout_drop(&self.id); } } } /// Handle to a binding group. /// /// A `BindGroup` represents the set of resources bound to the bindings described by a /// [`BindGroupLayout`]. It can be created with [`Device::create_bind_group`]. A `BindGroup` can /// be bound to a particular [`RenderPass`] with [`RenderPass::set_bind_group`], or to a /// [`ComputePass`] with [`ComputePass::set_bind_group`]. #[derive(Debug)] pub struct BindGroup { context: Arc<C>, id: <C as Context>::BindGroupId, } impl Drop for BindGroup { fn drop(&mut self) { if !thread::panicking() { self.context.bind_group_drop(&self.id); } } } /// Handle to a compiled shader module. /// /// A `ShaderModule` represents a compiled shader module on the GPU. It can be created by passing /// valid SPIR-V source code to [`Device::create_shader_module`]. Shader modules are used to define /// programmable stages of a pipeline. #[derive(Debug)] pub struct ShaderModule { context: Arc<C>, id: <C as Context>::ShaderModuleId, } impl Drop for ShaderModule { fn drop(&mut self) { if !thread::panicking() { self.context.shader_module_drop(&self.id); } } } /// Source of a shader module. pub enum ShaderSource<'a> { /// SPIR-V module represented as a slice of words. /// /// wgpu will attempt to parse and validate it, but the original binary /// is passed to `gfx-rs` and `spirv_cross` for translation. #[cfg(feature = "spirv")] SpirV(Cow<'a, [u32]>), /// WGSL module as a string slice. /// /// wgpu-rs will parse it and use for validation. It will attempt /// to build a SPIR-V module internally and panic otherwise. /// /// Note: WGSL is not yet supported on the Web. Wgsl(Cow<'a, str>), } /// Descriptor for a shader module. pub struct ShaderModuleDescriptor<'a> { /// Debug label of the shader module. This will show up in graphics debuggers for easy identification. pub label: Label<'a>, /// Source code for the shader. pub source: ShaderSource<'a>, } /// Descriptor for a shader module given by SPIR-V binary. pub struct ShaderModuleDescriptorSpirV<'a> { /// Debug label of the shader module. This will show up in graphics debuggers for easy identification. pub label: Label<'a>, /// Binary SPIR-V data, in 4-byte words. pub source: Cow<'a, [u32]>, } /// Handle to a pipeline layout. /// /// A `PipelineLayout` object describes the available binding groups of a pipeline. #[derive(Debug)] pub struct PipelineLayout { context: Arc<C>, id: <C as Context>::PipelineLayoutId, } impl Drop for PipelineLayout { fn drop(&mut self) { if !thread::panicking() { self.context.pipeline_layout_drop(&self.id); } } } /// Handle to a rendering (graphics) pipeline. /// /// A `RenderPipeline` object represents a graphics pipeline and its stages, bindings, vertex /// buffers and targets. A `RenderPipeline` may be created with [`Device::create_render_pipeline`]. #[derive(Debug)] pub struct RenderPipeline { context: Arc<C>, id: <C as Context>::RenderPipelineId, } impl Drop for RenderPipeline { fn drop(&mut self) { if !thread::panicking() { self.context.render_pipeline_drop(&self.id); } } } impl RenderPipeline { /// Get an object representing the bind group layout at a given index. pub fn get_bind_group_layout(&self, index: u32) -> BindGroupLayout { let context = Arc::clone(&self.context); BindGroupLayout { context, id: self .context .render_pipeline_get_bind_group_layout(&self.id, index), } } } /// Handle to a compute pipeline. /// /// A `ComputePipeline` object represents a compute pipeline and its single shader stage. /// A `ComputePipeline` may be created with [`Device::create_compute_pipeline`]. #[derive(Debug)] pub struct ComputePipeline { context: Arc<C>, id: <C as Context>::ComputePipelineId, } impl Drop for ComputePipeline { fn drop(&mut self) { if !thread::panicking() { self.context.compute_pipeline_drop(&self.id); } } } impl ComputePipeline { /// Get an object representing the bind group layout at a given index. pub fn get_bind_group_layout(&self, index: u32) -> BindGroupLayout { let context = Arc::clone(&self.context); BindGroupLayout { context, id: self .context .compute_pipeline_get_bind_group_layout(&self.id, index), } } } /// Handle to a command buffer on the GPU. /// /// A `CommandBuffer` represents a complete sequence of commands that may be submitted to a command /// queue with [`Queue::submit`]. A `CommandBuffer` is obtained by recording a series of commands to /// a [`CommandEncoder`] and then calling [`CommandEncoder::finish`]. #[derive(Debug)] pub struct CommandBuffer { context: Arc<C>, id: Option<<C as Context>::CommandBufferId>, } impl Drop for CommandBuffer { fn drop(&mut self) { if !thread::panicking() { if let Some(ref id) = self.id { self.context.command_buffer_drop(id); } } } } /// Encodes a series of GPU operations. /// /// A command encoder can record [`RenderPass`]es, [`ComputePass`]es, /// and transfer operations between driver-managed resources like [`Buffer`]s and [`Texture`]s. /// /// When finished recording, call [`CommandEncoder::finish`] to obtain a [`CommandBuffer`] which may /// be submitted for execution. #[derive(Debug)] pub struct CommandEncoder { context: Arc<C>, id: Option<<C as Context>::CommandEncoderId>, /// This type should be !Send !Sync, because it represents an allocation on this thread's /// command buffer. _p: PhantomData<*const u8>, } impl Drop for CommandEncoder { fn drop(&mut self) { if !thread::panicking() { if let Some(id) = self.id.take() { self.context.command_encoder_drop(&id); } } } } /// In-progress recording of a render pass. #[derive(Debug)] pub struct RenderPass<'a> { id: <C as Context>::RenderPassId, parent: &'a mut CommandEncoder, } /// In-progress recording of a compute pass. #[derive(Debug)] pub struct ComputePass<'a> { id: <C as Context>::ComputePassId, parent: &'a mut CommandEncoder, } /// Encodes a series of GPU operations into a reusable "render bundle". /// /// It only supports a handful of render commands, but it makes them reusable. [`RenderBundle`]s /// can be executed onto a [`CommandEncoder`] using [`RenderPass::execute_bundles`]. /// /// Executing a [`RenderBundle`] is often more efficient then issuing the underlying commands manually. #[derive(Debug)] pub struct RenderBundleEncoder<'a> { context: Arc<C>, id: <C as Context>::RenderBundleEncoderId, _parent: &'a Device, /// This type should be !Send !Sync, because it represents an allocation on this thread's /// command buffer. _p: PhantomData<*const u8>, } /// Pre-prepared reusable bundle of GPU operations. /// /// It only supports a handful of render commands, but it makes them reusable. [`RenderBundle`]s /// can be executed onto a [`CommandEncoder`] using [`RenderPass::execute_bundles`]. /// /// Executing a [`RenderBundle`] is often more efficient then issuing the underlying commands manually. #[derive(Debug)] pub struct RenderBundle { context: Arc<C>, id: <C as Context>::RenderBundleId, } impl Drop for RenderBundle { fn drop(&mut self) { if !thread::panicking() { self.context.render_bundle_drop(&self.id); } } } /// Handle to a query set. pub struct QuerySet { context: Arc<C>, id: <C as Context>::QuerySetId, } impl Drop for QuerySet { fn drop(&mut self) { if !thread::panicking() { self.context.query_set_drop(&self.id); } } } /// Handle to a command queue on a device. /// /// A `Queue` executes recorded [`CommandBuffer`] objects and provides convenience methods /// for writing to [buffers](Queue::write_buffer) and [textures](Queue::write_texture). #[derive(Debug)] pub struct Queue { context: Arc<C>, id: <C as Context>::QueueId, } /// Resource that can be bound to a pipeline. #[non_exhaustive] #[derive(Clone, Debug)] pub enum BindingResource<'a> { /// Binding is backed by a buffer. /// /// Corresponds to [`wgt::BufferBindingType::Uniform`] and [`wgt::BufferBindingType::Storage`] /// with [`BindGroupLayoutEntry::count`] set to None. Buffer(BufferBinding<'a>), /// Binding is backed by an array of buffers. /// /// [`Features::BUFFER_BINDING_ARRAY`] must be supported to use this feature. /// /// Corresponds to [`wgt::BufferBindingType::Uniform`] and [`wgt::BufferBindingType::Storage`] /// with [`BindGroupLayoutEntry::count`] set to Some. BufferArray(&'a [BufferBinding<'a>]), /// Binding is a sampler. /// /// Corresponds to [`wgt::BindingType::Sampler`] with [`BindGroupLayoutEntry::count`] set to None. Sampler(&'a Sampler), /// Binding is backed by a texture. /// /// Corresponds to [`wgt::BindingType::Texture`] and [`wgt::BindingType::StorageTexture`] with /// [`BindGroupLayoutEntry::count`] set to None. TextureView(&'a TextureView), /// Binding is backed by an array of textures. /// /// [`Features::TEXTURE_BINDING_ARRAY`] must be supported to use this feature. /// /// Corresponds to [`wgt::BindingType::Texture`] and [`wgt::BindingType::StorageTexture`] with /// [`BindGroupLayoutEntry::count`] set to Some. TextureViewArray(&'a [&'a TextureView]), } /// Describes the segment of a buffer to bind. #[derive(Clone, Debug)] pub struct BufferBinding<'a> { /// The buffer to bind. pub buffer: &'a Buffer, /// Base offset of the buffer. For bindings with `dynamic == true`, this offset /// will be added to the dynamic offset provided in [`RenderPass::set_bind_group`]. /// /// The offset has to be aligned to [`BIND_BUFFER_ALIGNMENT`]. pub offset: BufferAddress, /// Size of the binding, or `None` for using the rest of the buffer. pub size: Option<BufferSize>, } /// Operation to perform to the output attachment at the start of a renderpass. /// /// The render target must be cleared at least once before its content is loaded. #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] #[cfg_attr(feature = "trace", derive(serde::Serialize))] #[cfg_attr(feature = "replay", derive(serde::Deserialize))] pub enum LoadOp<V> { /// Clear with a specified value. Clear(V), /// Load from memory. Load, } impl<V: Default> Default for LoadOp<V> { fn default() -> Self { Self::Clear(Default::default()) } } /// Pair of load and store operations for an attachment aspect. #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] #[cfg_attr(feature = "trace", derive(serde::Serialize))] #[cfg_attr(feature = "replay", derive(serde::Deserialize))] pub struct Operations<V> { /// How data should be read through this attachment. pub load: LoadOp<V>, /// Whether data will be written to through this attachment. pub store: bool, } impl<V: Default> Default for Operations<V> { fn default() -> Self { Self { load: Default::default(), store: true, } } } /// Describes a color attachment to a [`RenderPass`]. #[derive(Clone, Debug)] pub struct RenderPassColorAttachment<'a> { /// The view to use as an attachment. pub view: &'a TextureView, /// The view that will receive the resolved output if multisampling is used. pub resolve_target: Option<&'a TextureView>, /// What operations will be performed on this color attachment. pub ops: Operations<Color>, } /// Describes a depth/stencil attachment to a [`RenderPass`]. #[derive(Clone, Debug)] pub struct RenderPassDepthStencilAttachment<'a> { /// The view to use as an attachment. pub view: &'a TextureView, /// What operations will be performed on the depth part of the attachment. pub depth_ops: Option<Operations<f32>>, /// What operations will be performed on the stencil part of the attachment. pub stencil_ops: Option<Operations<u32>>, } // The underlying types are also exported so that documentation shows up for them /// Object label. pub type Label<'a> = Option<&'a str>; pub use wgt::RequestAdapterOptions as RequestAdapterOptionsBase; /// Additional information required when requesting an adapter. pub type RequestAdapterOptions<'a> = RequestAdapterOptionsBase<&'a Surface>; /// Describes a [`Device`]. pub type DeviceDescriptor<'a> = wgt::DeviceDescriptor<Label<'a>>; /// Describes a [`Buffer`]. pub type BufferDescriptor<'a> = wgt::BufferDescriptor<Label<'a>>; /// Describes a [`CommandEncoder`]. pub type CommandEncoderDescriptor<'a> = wgt::CommandEncoderDescriptor<Label<'a>>; /// Describes a [`RenderBundle`]. pub type RenderBundleDescriptor<'a> = wgt::RenderBundleDescriptor<Label<'a>>; /// Describes a [`Texture`]. pub type TextureDescriptor<'a> = wgt::TextureDescriptor<Label<'a>>; /// Describes a [`QuerySet`]. pub type QuerySetDescriptor<'a> = wgt::QuerySetDescriptor<Label<'a>>; /// Describes a [`TextureView`]. #[derive(Clone, Debug, Default, PartialEq)] pub struct TextureViewDescriptor<'a> { /// Debug label of the texture view. This will show up in graphics debuggers for easy identification. pub label: Label<'a>, /// Format of the texture view. At this time, it must be the same as the underlying format of the texture. pub format: Option<TextureFormat>, /// The dimension of the texture view. For 1D textures, this must be `1D`. For 2D textures it must be one of /// `D2`, `D2Array`, `Cube`, and `CubeArray`. For 3D textures it must be `3D` pub dimension: Option<TextureViewDimension>, /// Aspect of the texture. Color textures must be [`TextureAspect::All`]. pub aspect: TextureAspect, /// Base mip level. pub base_mip_level: u32, /// Mip level count. /// If `Some(count)`, `base_mip_level + count` must be less or equal to underlying texture mip count. /// If `None`, considered to include the rest of the mipmap levels, but at least 1 in total. pub mip_level_count: Option<NonZeroU32>, /// Base array layer. pub base_array_layer: u32, /// Layer count. /// If `Some(count)`, `base_array_layer + count` must be less or equal to the underlying array count. /// If `None`, considered to include the rest of the array layers, but at least 1 in total. pub array_layer_count: Option<NonZeroU32>, } /// Describes a pipeline layout. /// /// A `PipelineLayoutDescriptor` can be used to create a pipeline layout. #[derive(Clone, Debug, Default)] pub struct PipelineLayoutDescriptor<'a> { /// Debug label of the pipeline layout. This will show up in graphics debuggers for easy identification. pub label: Label<'a>, /// Bind groups that this pipeline uses. The first entry will provide all the bindings for /// "set = 0", second entry will provide all the bindings for "set = 1" etc. pub bind_group_layouts: &'a [&'a BindGroupLayout], /// Set of push constant ranges this pipeline uses. Each shader stage that uses push constants /// must define the range in push constant memory that corresponds to its single `layout(push_constant)` /// uniform block. /// /// If this array is non-empty, the [`Features::PUSH_CONSTANTS`] must be enabled. pub push_constant_ranges: &'a [PushConstantRange], } /// Describes a [`Sampler`] #[derive(Clone, Debug, PartialEq)] pub struct SamplerDescriptor<'a> { /// Debug label of the sampler. This will show up in graphics debuggers for easy identification. pub label: Label<'a>, /// How to deal with out of bounds accesses in the u (i.e. x) direction pub address_mode_u: AddressMode, /// How to deal with out of bounds accesses in the v (i.e. y) direction pub address_mode_v: AddressMode, /// How to deal with out of bounds accesses in the w (i.e. z) direction pub address_mode_w: AddressMode, /// How to filter the texture when it needs to be magnified (made larger) pub mag_filter: FilterMode, /// How to filter the texture when it needs to be minified (made smaller) pub min_filter: FilterMode, /// How to filter between mip map levels pub mipmap_filter: FilterMode, /// Minimum level of detail (i.e. mip level) to use pub lod_min_clamp: f32, /// Maximum level of detail (i.e. mip level) to use pub lod_max_clamp: f32, /// If this is enabled, this is a comparison sampler using the given comparison function. pub compare: Option<CompareFunction>, /// Valid values: 1, 2, 4, 8, and 16. pub anisotropy_clamp: Option<NonZeroU8>, /// Border color to use when address_mode is [`AddressMode::ClampToBorder`] pub border_color: Option<SamplerBorderColor>, } impl Default for SamplerDescriptor<'_> { fn default() -> Self { Self { label: None, address_mode_u: Default::default(), address_mode_v: Default::default(), address_mode_w: Default::default(), mag_filter: Default::default(), min_filter: Default::default(), mipmap_filter: Default::default(), lod_min_clamp: 0.0, lod_max_clamp: std::f32::MAX, compare: None, anisotropy_clamp: None, border_color: None, } } } /// Bindable resource and the slot to bind it to. #[derive(Clone, Debug)] pub struct BindGroupEntry<'a> { /// Slot for which binding provides resource. Corresponds to an entry of the same /// binding index in the [`BindGroupLayoutDescriptor`]. pub binding: u32, /// Resource to attach to the binding pub resource: BindingResource<'a>, } /// Describes a group of bindings and the resources to be bound. #[derive(Clone, Debug)] pub struct BindGroupDescriptor<'a> { /// Debug label of the bind group. This will show up in graphics debuggers for easy identification. pub label: Label<'a>, /// The [`BindGroupLayout`] that corresponds to this bind group. pub layout: &'a BindGroupLayout, /// The resources to bind to this bind group. pub entries: &'a [BindGroupEntry<'a>], } /// Describes the attachments of a render pass. /// /// Note: separate lifetimes are needed because the texture views /// have to live as long as the pass is recorded, while everything else doesn't. #[derive(Clone, Debug, Default)] pub struct RenderPassDescriptor<'a, 'b> { /// Debug label of the render pass. This will show up in graphics debuggers for easy identification. pub label: Label<'a>, /// The color attachments of the render pass. pub color_attachments: &'b [RenderPassColorAttachment<'a>], /// The depth and stencil attachment of the render pass, if any. pub depth_stencil_attachment: Option<RenderPassDepthStencilAttachment<'a>>, } /// Describes how the vertex buffer is interpreted. #[derive(Clone, Debug, Hash, Eq, PartialEq)] pub struct VertexBufferLayout<'a> { /// The stride, in bytes, between elements of this buffer. pub array_stride: BufferAddress, /// How often this vertex buffer is "stepped" forward. pub step_mode: VertexStepMode, /// The list of attributes which comprise a single vertex. pub attributes: &'a [VertexAttribute], } /// Describes the vertex process in a render pipeline. #[derive(Clone, Debug)] pub struct VertexState<'a> { /// The compiled shader module for this stage. pub module: &'a ShaderModule, /// The name of the entry point in the compiled shader. There must be a function that returns /// void with this name in the shader. pub entry_point: &'a str, /// The format of any vertex buffers used with this pipeline. pub buffers: &'a [VertexBufferLayout<'a>], } /// Describes the fragment process in a render pipeline. #[derive(Clone, Debug)] pub struct FragmentState<'a> { /// The compiled shader module for this stage. pub module: &'a ShaderModule, /// The name of the entry point in the compiled shader. There must be a function that returns /// void with this name in the shader. pub entry_point: &'a str, /// The color state of the render targets. pub targets: &'a [ColorTargetState], } /// Describes a render (graphics) pipeline. #[derive(Clone, Debug)] pub struct RenderPipelineDescriptor<'a> { /// Debug label of the pipeline. This will show up in graphics debuggers for easy identification. pub label: Label<'a>, /// The layout of bind groups for this pipeline. pub layout: Option<&'a PipelineLayout>, /// The compiled vertex stage, its entry point, and the input buffers layout. pub vertex: VertexState<'a>, /// The properties of the pipeline at the primitive assembly and rasterization level. pub primitive: PrimitiveState, /// The effect of draw calls on the depth and stencil aspects of the output target, if any. pub depth_stencil: Option<DepthStencilState>, /// The multi-sampling properties of the pipeline. pub multisample: MultisampleState, /// The compiled fragment stage, its entry point, and the color targets. pub fragment: Option<FragmentState<'a>>, } /// Describes the attachments of a compute pass. #[derive(Clone, Debug, Default)] pub struct ComputePassDescriptor<'a> { /// Debug label of the compute pass. This will show up in graphics debuggers for easy identification. pub label: Label<'a>, } /// Describes a compute pipeline. #[derive(Clone, Debug)] pub struct ComputePipelineDescriptor<'a> { /// Debug label of the pipeline. This will show up in graphics debuggers for easy identification. pub label: Label<'a>, /// The layout of bind groups for this pipeline. pub layout: Option<&'a PipelineLayout>, /// The compiled shader module for this stage. pub module: &'a ShaderModule, /// The name of the entry point in the compiled shader. There must be a function that returns /// void with this name in the shader. pub entry_point: &'a str, } pub use wgt::ImageCopyBuffer as ImageCopyBufferBase; /// View of a buffer which can be used to copy to/from a texture. pub type ImageCopyBuffer<'a> = ImageCopyBufferBase<&'a Buffer>; pub use wgt::ImageCopyTexture as ImageCopyTextureBase; /// View of a texture which can be used to copy to/from a buffer/texture. pub type ImageCopyTexture<'a> = ImageCopyTextureBase<&'a Texture>; /// Describes a [`BindGroupLayout`]. #[derive(Clone, Debug)] pub struct BindGroupLayoutDescriptor<'a> { /// Debug label of the bind group layout. This will show up in graphics debuggers for easy identification. pub label: Label<'a>, /// Array of entries in this BindGroupLayout pub entries: &'a [BindGroupLayoutEntry], } /// Describes a [`RenderBundleEncoder`]. #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] pub struct RenderBundleEncoderDescriptor<'a> { /// Debug label of the render bundle encoder. This will show up in graphics debuggers for easy identification. pub label: Label<'a>, /// The formats of the color attachments that this render bundle is capable to rendering to. This /// must match the formats of the color attachments in the renderpass this render bundle is executed in. pub color_formats: &'a [TextureFormat], /// Information about the depth attachment that this render bundle is capable to rendering to. This /// must match the format of the depth attachments in the renderpass this render bundle is executed in. pub depth_stencil: Option<RenderBundleDepthStencil>, /// Sample count this render bundle is capable of rendering to. This must match the pipelines and /// the renderpasses it is used in. pub sample_count: u32, } /// Surface texture that can be rendered to. #[derive(Debug)] pub struct SurfaceTexture { /// Accessible view of the frame. pub texture: Texture, detail: <C as Context>::SurfaceOutputDetail, } /// Result of a successful call to [`Surface::get_current_frame`]. #[derive(Debug)] pub struct SurfaceFrame { /// The texture into which the next frame should be rendered. pub output: SurfaceTexture, /// `true` if the acquired buffer can still be used for rendering, /// but should be recreated for maximum performance. pub suboptimal: bool, } /// Result of an unsuccessful call to [`Surface::get_current_frame`]. #[derive(Clone, PartialEq, Eq, Debug)] pub enum SurfaceError { /// A timeout was encountered while trying to acquire the next frame. Timeout, /// The underlying surface has changed, and therefore the swap chain must be updated. Outdated, /// The swap chain has been lost and needs to be recreated. Lost, /// There is no more memory left to allocate a new frame. OutOfMemory, } impl Display for SurfaceError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", match self { Self::Timeout => "A timeout was encountered while trying to acquire the next frame", Self::Outdated => "The underlying surface has changed, and therefore the swap chain must be updated", Self::Lost => "The swap chain has been lost and needs to be recreated", Self::OutOfMemory => "There is no more memory left to allocate a new frame", }) } } impl error::Error for SurfaceError {} impl Instance { /// Create an new instance of wgpu. /// /// # Arguments /// /// - `backends` - Controls from which [backends][Backends] wgpu will choose /// during instantiation. pub fn new(backends: Backends) -> Self { Self { context: Arc::new(C::init(backends)), } } /// Create an new instance of wgpu from a wgpu-hal instance. /// /// # Arguments /// /// - `hal_instance` - wgpu-hal instance. /// /// # Safety /// /// Refer to the creation of wgpu-hal Instance for every backend. #[cfg(not(target_arch = "wasm32"))] pub unsafe fn from_hal<A: wgc::hub::HalApi>(hal_instance: A::Instance) -> Self { Self { context: Arc::new(C::from_hal_instance::<A>(hal_instance)), } } /// Retrieves all available [`Adapter`]s that match the given [`Backends`]. /// /// # Arguments /// /// - `backends` - Backends from which to enumerate adapters. #[cfg(not(target_arch = "wasm32"))] pub fn enumerate_adapters(&self, backends: Backends) -> impl Iterator<Item = Adapter> { let context = Arc::clone(&self.context); self.context .enumerate_adapters(backends) .into_iter() .map(move |id| crate::Adapter { id, context: Arc::clone(&context), }) } /// Retrieves an [`Adapter`] which matches the given [`RequestAdapterOptions`]. /// /// Some options are "soft", so treated as non-mandatory. Others are "hard". /// /// If no adapters are found that suffice all the "hard" options, `None` is returned. pub fn request_adapter( &self, options: &RequestAdapterOptions, ) -> impl Future<Output = Option<Adapter>> + Send { let context = Arc::clone(&self.context); let adapter = self.context.instance_request_adapter(options); async move { adapter.await.map(|id| Adapter { context, id }) } } /// Converts a wgpu-hal `ExposedAdapter` to a wgpu [`Adapter`]. /// /// # Safety /// /// `hal_adapter` must be created from this instance internal handle. #[cfg(not(target_arch = "wasm32"))] pub unsafe fn create_adapter_from_hal<A: wgc::hub::HalApi>( &self, hal_adapter: hal::ExposedAdapter<A>, ) -> Adapter { let context = Arc::clone(&self.context); let id = context.create_adapter_from_hal(hal_adapter); Adapter { context, id } } /// Creates a surface from a raw window handle. /// /// # Safety /// /// - Raw Window Handle must be a valid object to create a surface upon and /// must remain valid for the lifetime of the returned surface. pub unsafe fn create_surface<W: raw_window_handle::HasRawWindowHandle>( &self, window: &W, ) -> Surface { Surface { context: Arc::clone(&self.context), id: Context::instance_create_surface(&*self.context, window), } } /*TODO: raw CAL surface /// Creates a surface from `CoreAnimationLayer`. /// /// # Safety /// /// - layer must be a valid object to create a surface upon. #[cfg(any(target_os = "ios", target_os = "macos"))] pub unsafe fn create_surface_from_core_animation_layer( &self, layer: *mut std::ffi::c_void, ) -> Surface { self.context.create_surface_from_core_animation_layer(layer) }*/ /// Polls all devices. /// If `force_wait` is true and this is not running on the web, /// then this function will block until all in-flight buffers have been mapped. pub fn poll_all(&self, force_wait: bool) { self.context.instance_poll_all_devices(force_wait); } /// Generates memory report. #[cfg(not(target_arch = "wasm32"))] pub fn generate_report(&self) -> wgc::hub::GlobalReport { self.context.generate_report() } } impl Adapter { /// Requests a connection to a physical device, creating a logical device. /// /// Returns the [`Device`] together with a [`Queue`] that executes command buffers. /// /// # Arguments /// /// - `desc` - Description of the features and limits requested from the given device. /// - `trace_path` - Can be used for API call tracing, if that feature is /// enabled in `wgpu-core`. /// - `auto_poll` - Set to `true` to automatically resolve [`BufferSlice::map_async`] /// futures in a background thread. Ignored on the web backend. /// /// # Panics /// /// - Features specified by `desc` are not supported by this adapter. /// - Unsafe features were requested but not enabled when requesting the adapter. /// - Limits requested exceed the values provided by the adapter. /// - Adapter does not support all features wgpu requires to safely operate. pub fn request_device( &self, desc: &DeviceDescriptor, trace_path: Option<&std::path::Path>, auto_poll: bool, ) -> impl Future<Output = Result<(Device, Queue), RequestDeviceError>> + Send { let context = Arc::clone(&self.context); let device = Context::adapter_request_device(&self.context, &self.id, desc, auto_poll, trace_path); async move { device.await.map(|(device_id, queue_id)| { ( Device { context: Arc::clone(&context), id: device_id, }, Queue { context, id: queue_id, }, ) }) } } /// Create a wgpu [`Device`] and [`Queue`] from a wgpu-hal `OpenDevice` /// /// # Safety /// /// - `hal_device` must be created from this adapter internal handle. /// - `desc.features` must be a subset of `hal_device` features. #[cfg(not(target_arch = "wasm32"))] pub unsafe fn create_device_from_hal<A: wgc::hub::HalApi>( &self, hal_device: hal::OpenDevice<A>, desc: &DeviceDescriptor, auto_poll: bool, trace_path: Option<&std::path::Path>, ) -> Result<(Device, Queue), RequestDeviceError> { let context = Arc::clone(&self.context); self.context .create_device_from_hal(&self.id, hal_device, desc, auto_poll, trace_path) .map(|(device_id, queue_id)| { ( Device { context: Arc::clone(&context), id: device_id, }, Queue { context, id: queue_id, }, ) }) } /// Returns whether this adapter may present to the passed surface. pub fn is_surface_supported(&self, surface: &Surface) -> bool { Context::adapter_is_surface_supported(&*self.context, &self.id, &surface.id) } /// List all features that are supported with this adapter. /// /// Features must be explicitly requested in [`Adapter::request_device`] in order /// to use them. pub fn features(&self) -> Features { Context::adapter_features(&*self.context, &self.id) } /// List the "best" limits that are supported by this adapter. /// /// Limits must be explicitly requested in [`Adapter::request_device`] to set /// the values that you are allowed to use. pub fn limits(&self) -> Limits { Context::adapter_limits(&*self.context, &self.id) } /// Get info about the adapter itself. pub fn get_info(&self) -> AdapterInfo { Context::adapter_get_info(&*self.context, &self.id) } /// Get info about the adapter itself. pub fn get_downlevel_properties(&self) -> DownlevelCapabilities { Context::adapter_downlevel_properties(&*self.context, &self.id) } /// Returns the features supported for a given texture format by this adapter. /// /// Note that the WebGPU spec further restricts the available usages/features. /// To disable these restrictions on a device, request the [`Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES`] feature. pub fn get_texture_format_features(&self, format: TextureFormat) -> TextureFormatFeatures { Context::adapter_get_texture_format_features(&*self.context, &self.id, format) } } impl Device { /// Check for resource cleanups and mapping callbacks. /// /// no-op on the web, device is automatically polled. pub fn poll(&self, maintain: Maintain) { Context::device_poll(&*self.context, &self.id, maintain); } /// List all features that may be used with this device. /// /// Functions may panic if you use unsupported features. pub fn features(&self) -> Features { Context::device_features(&*self.context, &self.id) } /// List all limits that were requested of this device. /// /// If any of these limits are exceeded, functions may panic. pub fn limits(&self) -> Limits { Context::device_limits(&*self.context, &self.id) } /// Creates a shader module from either SPIR-V or WGSL source code. pub fn create_shader_module(&self, desc: &ShaderModuleDescriptor) -> ShaderModule { ShaderModule { context: Arc::clone(&self.context), id: Context::device_create_shader_module(&*self.context, &self.id, desc), } } /// Creates a shader module from SPIR-V binary directly. /// /// # Safety /// /// This function passes binary data to the backend as-is and can potentially result in a /// driver crash or bogus behaviour. No attempt is made to ensure that data is valid SPIR-V. /// /// See also [`include_spirv_raw!`] and [`util::make_spirv_raw`]. pub unsafe fn create_shader_module_spirv( &self, desc: &ShaderModuleDescriptorSpirV, ) -> ShaderModule { ShaderModule { context: Arc::clone(&self.context), id: Context::device_create_shader_module_spirv(&*self.context, &self.id, desc), } } /// Creates an empty [`CommandEncoder`]. pub fn create_command_encoder(&self, desc: &CommandEncoderDescriptor) -> CommandEncoder { CommandEncoder { context: Arc::clone(&self.context), id: Some(Context::device_create_command_encoder( &*self.context, &self.id, desc, )), _p: Default::default(), } } /// Creates an empty [`RenderBundleEncoder`]. pub fn create_render_bundle_encoder( &self, desc: &RenderBundleEncoderDescriptor, ) -> RenderBundleEncoder { RenderBundleEncoder { context: Arc::clone(&self.context), id: Context::device_create_render_bundle_encoder(&*self.context, &self.id, desc), _parent: self, _p: Default::default(), } } /// Creates a new [`BindGroup`]. pub fn create_bind_group(&self, desc: &BindGroupDescriptor) -> BindGroup { BindGroup { context: Arc::clone(&self.context), id: Context::device_create_bind_group(&*self.context, &self.id, desc), } } /// Creates a [`BindGroupLayout`]. pub fn create_bind_group_layout(&self, desc: &BindGroupLayoutDescriptor) -> BindGroupLayout { BindGroupLayout { context: Arc::clone(&self.context), id: Context::device_create_bind_group_layout(&*self.context, &self.id, desc), } } /// Creates a [`PipelineLayout`]. pub fn create_pipeline_layout(&self, desc: &PipelineLayoutDescriptor) -> PipelineLayout { PipelineLayout { context: Arc::clone(&self.context), id: Context::device_create_pipeline_layout(&*self.context, &self.id, desc), } } /// Creates a [`RenderPipeline`]. pub fn create_render_pipeline(&self, desc: &RenderPipelineDescriptor) -> RenderPipeline { RenderPipeline { context: Arc::clone(&self.context), id: Context::device_create_render_pipeline(&*self.context, &self.id, desc), } } /// Creates a [`ComputePipeline`]. pub fn create_compute_pipeline(&self, desc: &ComputePipelineDescriptor) -> ComputePipeline { ComputePipeline { context: Arc::clone(&self.context), id: Context::device_create_compute_pipeline(&*self.context, &self.id, desc), } } /// Creates a [`Buffer`]. pub fn create_buffer(&self, desc: &BufferDescriptor) -> Buffer { let mut map_context = MapContext::new(desc.size); if desc.mapped_at_creation { map_context.initial_range = 0..desc.size; } Buffer { context: Arc::clone(&self.context), id: Context::device_create_buffer(&*self.context, &self.id, desc), map_context: Mutex::new(map_context), usage: desc.usage, } } /// Creates a new [`Texture`]. /// /// `desc` specifies the general format of the texture. pub fn create_texture(&self, desc: &TextureDescriptor) -> Texture { Texture { context: Arc::clone(&self.context), id: Context::device_create_texture(&*self.context, &self.id, desc), owned: true, } } /// Creates a [`Texture`] from a wgpu-hal Texture. /// /// # Safety /// /// - `hal_texture` must be created from this device internal handle /// - `hal_texture` must be created respecting `desc` #[cfg(not(target_arch = "wasm32"))] pub unsafe fn create_texture_from_hal<A: wgc::hub::HalApi>( &self, hal_texture: A::Texture, desc: &TextureDescriptor, ) -> Texture { Texture { context: Arc::clone(&self.context), id: self .context .create_texture_from_hal::<A>(hal_texture, &self.id, desc), owned: true, } } /// Creates a new [`Sampler`]. /// /// `desc` specifies the behavior of the sampler. pub fn create_sampler(&self, desc: &SamplerDescriptor) -> Sampler { Sampler { context: Arc::clone(&self.context), id: Context::device_create_sampler(&*self.context, &self.id, desc), } } /// Creates a new [`QuerySet`]. pub fn create_query_set(&self, desc: &QuerySetDescriptor) -> QuerySet { QuerySet { context: Arc::clone(&self.context), id: Context::device_create_query_set(&*self.context, &self.id, desc), } } /// Set a callback for errors that are not handled in error scopes. pub fn on_uncaptured_error(&self, handler: impl UncapturedErrorHandler) { self.context.device_on_uncaptured_error(&self.id, handler); } /// Starts frame capture. pub fn start_capture(&self) { Context::device_start_capture(&*self.context, &self.id) } /// Stops frame capture. pub fn stop_capture(&self) { Context::device_stop_capture(&*self.context, &self.id) } } impl Drop for Device { fn drop(&mut self) { if !thread::panicking() { self.context.device_drop(&self.id); } } } /// Requesting a device failed. #[derive(Clone, PartialEq, Eq, Debug)] pub struct RequestDeviceError; impl Display for RequestDeviceError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "Requesting a device failed") } } impl error::Error for RequestDeviceError {} /// Error occurred when trying to async map a buffer. #[derive(Clone, PartialEq, Eq, Debug)] pub struct BufferAsyncError; impl Display for BufferAsyncError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "Error occurred when trying to async map a buffer") } } impl error::Error for BufferAsyncError {} /// Type of buffer mapping. #[derive(Debug, Clone, Copy, PartialEq)] pub enum MapMode { /// Map only for reading Read, /// Map only for writing Write, } fn range_to_offset_size<S: RangeBounds<BufferAddress>>( bounds: S, ) -> (BufferAddress, Option<BufferSize>) { let offset = match bounds.start_bound() { Bound::Included(&bound) => bound, Bound::Excluded(&bound) => bound + 1, Bound::Unbounded => 0, }; let size = match bounds.end_bound() { Bound::Included(&bound) => Some(bound + 1 - offset), Bound::Excluded(&bound) => Some(bound - offset), Bound::Unbounded => None, } .map(|size| BufferSize::new(size).expect("Buffer slices can not be empty")); (offset, size) } #[cfg(test)] mod tests { use crate::BufferSize; #[test] fn range_to_offset_size_works() { assert_eq!(crate::range_to_offset_size(0..2), (0, BufferSize::new(2))); assert_eq!(crate::range_to_offset_size(2..5), (2, BufferSize::new(3))); assert_eq!(crate::range_to_offset_size(..), (0, None)); assert_eq!(crate::range_to_offset_size(21..), (21, None)); assert_eq!(crate::range_to_offset_size(0..), (0, None)); assert_eq!(crate::range_to_offset_size(..21), (0, BufferSize::new(21))); } #[test] #[should_panic] fn range_to_offset_size_panics_for_empty_range() { crate::range_to_offset_size(123..123); } #[test] #[should_panic] fn range_to_offset_size_panics_for_unbounded_empty_range() { crate::range_to_offset_size(..0); } } trait BufferMappedRangeSlice { fn slice(&self) -> &[u8]; fn slice_mut(&mut self) -> &mut [u8]; } /// Read only view into a mapped buffer. #[derive(Debug)] pub struct BufferView<'a> { slice: BufferSlice<'a>, data: BufferMappedRange, } /// Write only view into mapped buffer. #[derive(Debug)] pub struct BufferViewMut<'a> { slice: BufferSlice<'a>, data: BufferMappedRange, readable: bool, } impl std::ops::Deref for BufferView<'_> { type Target = [u8]; fn deref(&self) -> &[u8] { self.data.slice() } } impl std::ops::Deref for BufferViewMut<'_> { type Target = [u8]; fn deref(&self) -> &[u8] { assert!( self.readable, "Attempting to read a write-only mapping for buffer {:?}", self.slice.buffer.id ); self.data.slice() } } impl std::ops::DerefMut for BufferViewMut<'_> { fn deref_mut(&mut self) -> &mut Self::Target { self.data.slice_mut() } } impl AsRef<[u8]> for BufferView<'_> { fn as_ref(&self) -> &[u8] { self.data.slice() } } impl AsMut<[u8]> for BufferViewMut<'_> { fn as_mut(&mut self) -> &mut [u8] { self.data.slice_mut() } } impl Drop for BufferView<'_> { fn drop(&mut self) { self.slice .buffer .map_context .lock() .remove(self.slice.offset, self.slice.size); } } impl Drop for BufferViewMut<'_> { fn drop(&mut self) { self.slice .buffer .map_context .lock() .remove(self.slice.offset, self.slice.size); } } impl Buffer { /// Return the binding view of the entire buffer. pub fn as_entire_binding(&self) -> BindingResource { BindingResource::Buffer(self.as_entire_buffer_binding()) } /// Return the binding view of the entire buffer. pub fn as_entire_buffer_binding(&self) -> BufferBinding { BufferBinding { buffer: self, offset: 0, size: None, } } /// Use only a portion of this Buffer for a given operation. Choosing a range with no end /// will use the rest of the buffer. Using a totally unbounded range will use the entire buffer. pub fn slice<S: RangeBounds<BufferAddress>>(&self, bounds: S) -> BufferSlice { let (offset, size) = range_to_offset_size(bounds); BufferSlice { buffer: self, offset, size, } } /// Flushes any pending write operations and unmaps the buffer from host memory. pub fn unmap(&self) { self.map_context.lock().reset(); Context::buffer_unmap(&*self.context, &self.id); } /// Destroy the associated native resources as soon as possible. pub fn destroy(&self) { Context::buffer_destroy(&*self.context, &self.id); } } impl<'a> BufferSlice<'a> { //TODO: fn slice(&self) -> Self /// Maps this slice of a buffer into memory. The buffer slice is ready to be read or written /// once the future has been resolved. /// /// For the future to complete, the device has to be polled. This is done automatically /// in a background thread if /// /// - the `auto_poll` parameter on [`Adapter::request_device`] was set to `true`, or /// - the web backend of wgpu is used. /// /// Otherwise, [`Device::poll`] must be called manually, for example in an event loop, /// on a separate thread, or in a blocking manner on the same thread. pub fn map_async( &self, mode: MapMode, ) -> impl Future<Output = Result<(), BufferAsyncError>> + Send { let mut mc = self.buffer.map_context.lock(); assert_eq!( mc.initial_range, 0..0, "Buffer {:?} is already mapped", self.buffer.id ); let end = match self.size { Some(s) => self.offset + s.get(), None => mc.total_size, }; mc.initial_range = self.offset..end; Context::buffer_map_async( &*self.buffer.context, &self.buffer.id, mode, self.offset..end, ) } /// Synchronously and immediately map a buffer for reading. If the buffer is not immediately mappable /// through [`BufferDescriptor::mapped_at_creation`] or [`BufferSlice::map_async`], will panic. pub fn get_mapped_range(&self) -> BufferView<'a> { let end = self.buffer.map_context.lock().add(self.offset, self.size); let data = Context::buffer_get_mapped_range( &*self.buffer.context, &self.buffer.id, self.offset..end, ); BufferView { slice: *self, data } } /// Synchronously and immediately map a buffer for writing. If the buffer is not immediately mappable /// through [`BufferDescriptor::mapped_at_creation`] or [`BufferSlice::map_async`], will panic. pub fn get_mapped_range_mut(&self) -> BufferViewMut<'a> { let end = self.buffer.map_context.lock().add(self.offset, self.size); let data = Context::buffer_get_mapped_range( &*self.buffer.context, &self.buffer.id, self.offset..end, ); BufferViewMut { slice: *self, data, readable: self.buffer.usage.contains(BufferUsages::MAP_READ), } } } impl Drop for Buffer { fn drop(&mut self) { if !thread::panicking() { self.context.buffer_drop(&self.id); } } } impl Texture { /// Returns the inner hal Texture using a callback. The hal texture will be `None` if the /// backend type argument does not match with this wgpu Texture /// /// # Safety /// /// - The raw handle obtained from the hal Texture must not be manually destroyed #[cfg(not(target_arch = "wasm32"))] pub unsafe fn as_hal<A: wgc::hub::HalApi>( &self, hal_texture_callback: impl FnOnce(Option<&A::Texture>), ) { self.context .texture_as_hal::<A, _>(&self.id, hal_texture_callback) } /// Creates a view of this texture. pub fn create_view(&self, desc: &TextureViewDescriptor) -> TextureView { TextureView { context: Arc::clone(&self.context), id: Context::texture_create_view(&*self.context, &self.id, desc), } } /// Destroy the associated native resources as soon as possible. pub fn destroy(&self) { Context::texture_destroy(&*self.context, &self.id); } /// Make an `ImageCopyTexture` representing the whole texture. pub fn as_image_copy(&self) -> ImageCopyTexture { ImageCopyTexture { texture: self, mip_level: 0, origin: Origin3d::ZERO, aspect: TextureAspect::All, } } } impl Drop for Texture { fn drop(&mut self) { if self.owned && !thread::panicking() { self.context.texture_drop(&self.id); } } } impl Drop for TextureView { fn drop(&mut self) { if !thread::panicking() { self.context.texture_view_drop(&self.id); } } } impl CommandEncoder { /// Finishes recording and returns a [`CommandBuffer`] that can be submitted for execution. pub fn finish(mut self) -> CommandBuffer { CommandBuffer { context: Arc::clone(&self.context), id: Some(Context::command_encoder_finish( &*self.context, self.id.take().unwrap(), )), } } /// Begins recording of a render pass. /// /// This function returns a [`RenderPass`] object which records a single render pass. pub fn begin_render_pass<'a>( &'a mut self, desc: &RenderPassDescriptor<'a, '_>, ) -> RenderPass<'a> { let id = self.id.as_ref().unwrap(); RenderPass { id: Context::command_encoder_begin_render_pass(&*self.context, id, desc), parent: self, } } /// Begins recording of a compute pass. /// /// This function returns a [`ComputePass`] object which records a single compute pass. pub fn begin_compute_pass(&mut self, desc: &ComputePassDescriptor) -> ComputePass { let id = self.id.as_ref().unwrap(); ComputePass { id: Context::command_encoder_begin_compute_pass(&*self.context, id, desc), parent: self, } } /// Copy data from one buffer to another. /// /// # Panics /// /// - Buffer offsets or copy size not a multiple of [`COPY_BUFFER_ALIGNMENT`]. /// - Copy would overrun buffer. pub fn copy_buffer_to_buffer( &mut self, source: &Buffer, source_offset: BufferAddress, destination: &Buffer, destination_offset: BufferAddress, copy_size: BufferAddress, ) { Context::command_encoder_copy_buffer_to_buffer( &*self.context, self.id.as_ref().unwrap(), &source.id, source_offset, &destination.id, destination_offset, copy_size, ); } /// Copy data from a buffer to a texture. /// /// # Panics /// /// - Copy would overrun buffer. /// - Copy would overrun texture. /// - `source.layout.bytes_per_row` isn't divisible by [`COPY_BYTES_PER_ROW_ALIGNMENT`]. pub fn copy_buffer_to_texture( &mut self, source: ImageCopyBuffer, destination: ImageCopyTexture, copy_size: Extent3d, ) { Context::command_encoder_copy_buffer_to_texture( &*self.context, self.id.as_ref().unwrap(), source, destination, copy_size, ); } /// Copy data from a texture to a buffer. /// /// # Panics /// /// - Copy would overrun buffer. /// - Copy would overrun texture. /// - `source.layout.bytes_per_row` isn't divisible by [`COPY_BYTES_PER_ROW_ALIGNMENT`]. pub fn copy_texture_to_buffer( &mut self, source: ImageCopyTexture, destination: ImageCopyBuffer, copy_size: Extent3d, ) { Context::command_encoder_copy_texture_to_buffer( &*self.context, self.id.as_ref().unwrap(), source, destination, copy_size, ); } /// Copy data from one texture to another. /// /// # Panics /// /// - Textures are not the same type /// - If a depth texture, or a multisampled texture, the entire texture must be copied /// - Copy would overrun either texture pub fn copy_texture_to_texture( &mut self, source: ImageCopyTexture, destination: ImageCopyTexture, copy_size: Extent3d, ) { Context::command_encoder_copy_texture_to_texture( &*self.context, self.id.as_ref().unwrap(), source, destination, copy_size, ); } /// Clears texture to zero. /// /// # Panics /// /// - `CLEAR_COMMANDS` extension not enabled /// - Texture does not have `COPY_DST` usage. /// - Range it out of bounds pub fn clear_texture(&mut self, texture: &Texture, subresource_range: &ImageSubresourceRange) { Context::command_encoder_clear_image( &*self.context, self.id.as_ref().unwrap(), texture, subresource_range, ); } /// Clears buffer to zero. /// /// # Panics /// /// - `CLEAR_COMMANDS` extension not enabled /// - Buffer does not have `COPY_DST` usage. /// - Range it out of bounds pub fn clear_buffer( &mut self, buffer: &Buffer, offset: BufferAddress, size: Option<BufferSize>, ) { Context::command_encoder_clear_buffer( &*self.context, self.id.as_ref().unwrap(), buffer, offset, size, ); } /// Inserts debug marker. pub fn insert_debug_marker(&mut self, label: &str) { let id = self.id.as_ref().unwrap(); Context::command_encoder_insert_debug_marker(&*self.context, id, label); } /// Start record commands and group it into debug marker group. pub fn push_debug_group(&mut self, label: &str) { let id = self.id.as_ref().unwrap(); Context::command_encoder_push_debug_group(&*self.context, id, label); } /// Stops command recording and creates debug group. pub fn pop_debug_group(&mut self) { let id = self.id.as_ref().unwrap(); Context::command_encoder_pop_debug_group(&*self.context, id); } } /// [`Features::TIMESTAMP_QUERY`] must be enabled on the device in order to call these functions. impl CommandEncoder { /// Issue a timestamp command at this point in the queue. /// The timestamp will be written to the specified query set, at the specified index. /// /// Must be multiplied by [`Queue::get_timestamp_period`] to get /// the value in nanoseconds. Absolute values have no meaning, /// but timestamps can be subtracted to get the time it takes /// for a string of operations to complete. pub fn write_timestamp(&mut self, query_set: &QuerySet, query_index: u32) { Context::command_encoder_write_timestamp( &*self.context, self.id.as_ref().unwrap(), &query_set.id, query_index, ) } } /// [`Features::TIMESTAMP_QUERY`] or [`Features::PIPELINE_STATISTICS_QUERY`] must be enabled on the device in order to call these functions. impl CommandEncoder { /// Resolve a query set, writing the results into the supplied destination buffer. /// /// Queries may be between 8 and 40 bytes each. See [`PipelineStatisticsTypes`] for more information. pub fn resolve_query_set( &mut self, query_set: &QuerySet, query_range: Range<u32>, destination: &Buffer, destination_offset: BufferAddress, ) { Context::command_encoder_resolve_query_set( &*self.context, self.id.as_ref().unwrap(), &query_set.id, query_range.start, query_range.end - query_range.start, &destination.id, destination_offset, ) } } impl<'a> RenderPass<'a> { /// Sets the active bind group for a given bind group index. The bind group layout /// in the active pipeline when any `draw()` function is called must match the layout of this bind group. /// /// If the bind group have dynamic offsets, provide them in order of their declaration. /// These offsets have to be aligned to [`BIND_BUFFER_ALIGNMENT`]. pub fn set_bind_group( &mut self, index: u32, bind_group: &'a BindGroup, offsets: &[DynamicOffset], ) { RenderInner::set_bind_group(&mut self.id, index, &bind_group.id, offsets) } /// Sets the active render pipeline. /// /// Subsequent draw calls will exhibit the behavior defined by `pipeline`. pub fn set_pipeline(&mut self, pipeline: &'a RenderPipeline) { RenderInner::set_pipeline(&mut self.id, &pipeline.id) } /// Sets the blend color as used by some of the blending modes. /// /// Subsequent blending tests will test against this value. pub fn set_blend_constant(&mut self, color: Color) { self.id.set_blend_constant(color) } /// Sets the active index buffer. /// /// Subsequent calls to [`draw_indexed`](RenderPass::draw_indexed) on this [`RenderPass`] will /// use `buffer` as the source index buffer. pub fn set_index_buffer(&mut self, buffer_slice: BufferSlice<'a>, index_format: IndexFormat) { RenderInner::set_index_buffer( &mut self.id, &buffer_slice.buffer.id, index_format, buffer_slice.offset, buffer_slice.size, ) } /// Assign a vertex buffer to a slot. /// /// Subsequent calls to [`draw`] and [`draw_indexed`] on this /// [`RenderPass`] will use `buffer` as one of the source vertex buffers. /// /// The `slot` refers to the index of the matching descriptor in /// [`VertexState::buffers`]. /// /// [`draw`]: RenderPass::draw /// [`draw_indexed`]: RenderPass::draw_indexed pub fn set_vertex_buffer(&mut self, slot: u32, buffer_slice: BufferSlice<'a>) { RenderInner::set_vertex_buffer( &mut self.id, slot, &buffer_slice.buffer.id, buffer_slice.offset, buffer_slice.size, ) } /// Sets the scissor region. /// /// Subsequent draw calls will discard any fragments that fall outside this region. pub fn set_scissor_rect(&mut self, x: u32, y: u32, width: u32, height: u32) { self.id.set_scissor_rect(x, y, width, height); } /// Sets the viewport region. /// /// Subsequent draw calls will draw any fragments in this region. pub fn set_viewport(&mut self, x: f32, y: f32, w: f32, h: f32, min_depth: f32, max_depth: f32) { self.id.set_viewport(x, y, w, h, min_depth, max_depth); } /// Sets the stencil reference. /// /// Subsequent stencil tests will test against this value. pub fn set_stencil_reference(&mut self, reference: u32) { self.id.set_stencil_reference(reference); } /// Draws primitives from the active vertex buffer(s). /// /// The active vertex buffers can be set with [`RenderPass::set_vertex_buffer`]. pub fn draw(&mut self, vertices: Range<u32>, instances: Range<u32>) { RenderInner::draw(&mut self.id, vertices, instances) } /// Inserts debug marker. pub fn insert_debug_marker(&mut self, label: &str) { self.id.insert_debug_marker(label); } /// Start record commands and group it into debug marker group. pub fn push_debug_group(&mut self, label: &str) { self.id.push_debug_group(label); } /// Stops command recording and creates debug group. pub fn pop_debug_group(&mut self) { self.id.pop_debug_group(); } /// Draws indexed primitives using the active index buffer and the active vertex buffers. /// /// The active index buffer can be set with [`RenderPass::set_index_buffer`], while the active /// vertex buffers can be set with [`RenderPass::set_vertex_buffer`]. pub fn draw_indexed(&mut self, indices: Range<u32>, base_vertex: i32, instances: Range<u32>) { RenderInner::draw_indexed(&mut self.id, indices, base_vertex, instances); } /// Draws primitives from the active vertex buffer(s) based on the contents of the `indirect_buffer`. /// /// The active vertex buffers can be set with [`RenderPass::set_vertex_buffer`]. /// /// The structure expected in `indirect_buffer` is the following: /// /// ```rust /// #[repr(C)] /// struct DrawIndirect { /// vertex_count: u32, // The number of vertices to draw. /// instance_count: u32, // The number of instances to draw. /// base_vertex: u32, // The Index of the first vertex to draw. /// base_instance: u32, // The instance ID of the first instance to draw. /// } /// ``` pub fn draw_indirect(&mut self, indirect_buffer: &'a Buffer, indirect_offset: BufferAddress) { self.id.draw_indirect(&indirect_buffer.id, indirect_offset); } /// Draws indexed primitives using the active index buffer and the active vertex buffers, /// based on the contents of the `indirect_buffer`. /// /// The active index buffer can be set with [`RenderPass::set_index_buffer`], while the active /// vertex buffers can be set with [`RenderPass::set_vertex_buffer`]. /// /// The structure expected in `indirect_buffer` is the following: /// /// ```rust /// #[repr(C)] /// struct DrawIndexedIndirect { /// vertex_count: u32, // The number of vertices to draw. /// instance_count: u32, // The number of instances to draw. /// base_index: u32, // The base index within the index buffer. /// vertex_offset: i32, // The value added to the vertex index before indexing into the vertex buffer. /// base_instance: u32, // The instance ID of the first instance to draw. /// } /// ``` pub fn draw_indexed_indirect( &mut self, indirect_buffer: &'a Buffer, indirect_offset: BufferAddress, ) { self.id .draw_indexed_indirect(&indirect_buffer.id, indirect_offset); } /// Execute a [render bundle][RenderBundle], which is a set of pre-recorded commands /// that can be run together. pub fn execute_bundles<I: Iterator<Item = &'a RenderBundle>>(&mut self, render_bundles: I) { self.id .execute_bundles(render_bundles.into_iter().map(|rb| &rb.id)) } } /// [`Features::MULTI_DRAW_INDIRECT`] must be enabled on the device in order to call these functions. impl<'a> RenderPass<'a> { /// Dispatches multiple draw calls from the active vertex buffer(s) based on the contents of the `indirect_buffer`. /// `count` draw calls are issued. /// /// The active vertex buffers can be set with [`RenderPass::set_vertex_buffer`]. /// /// The structure expected in `indirect_buffer` is the following: /// /// ```rust /// #[repr(C)] /// struct DrawIndirect { /// vertex_count: u32, // The number of vertices to draw. /// instance_count: u32, // The number of instances to draw. /// base_vertex: u32, // The Index of the first vertex to draw. /// base_instance: u32, // The instance ID of the first instance to draw. /// } /// ``` /// /// These draw structures are expected to be tightly packed. pub fn multi_draw_indirect( &mut self, indirect_buffer: &'a Buffer, indirect_offset: BufferAddress, count: u32, ) { self.id .multi_draw_indirect(&indirect_buffer.id, indirect_offset, count); } /// Dispatches multiple draw calls from the active index buffer and the active vertex buffers, /// based on the contents of the `indirect_buffer`. `count` draw calls are issued. /// /// The active index buffer can be set with [`RenderPass::set_index_buffer`], while the active /// vertex buffers can be set with [`RenderPass::set_vertex_buffer`]. /// /// The structure expected in `indirect_buffer` is the following: /// /// ```rust /// #[repr(C)] /// struct DrawIndexedIndirect { /// vertex_count: u32, // The number of vertices to draw. /// instance_count: u32, // The number of instances to draw. /// base_index: u32, // The base index within the index buffer. /// vertex_offset: i32, // The value added to the vertex index before indexing into the vertex buffer. /// base_instance: u32, // The instance ID of the first instance to draw. /// } /// ``` /// /// These draw structures are expected to be tightly packed. pub fn multi_draw_indexed_indirect( &mut self, indirect_buffer: &'a Buffer, indirect_offset: BufferAddress, count: u32, ) { self.id .multi_draw_indexed_indirect(&indirect_buffer.id, indirect_offset, count); } } /// [`Features::MULTI_DRAW_INDIRECT_COUNT`] must be enabled on the device in order to call these functions. impl<'a> RenderPass<'a> { /// Disptaches multiple draw calls from the active vertex buffer(s) based on the contents of the `indirect_buffer`. /// The count buffer is read to determine how many draws to issue. /// /// The indirect buffer must be long enough to account for `max_count` draws, however only `count` will /// draws will be read. If `count` is greater than `max_count`, `max_count` will be used. /// /// The active vertex buffers can be set with [`RenderPass::set_vertex_buffer`]. /// /// The structure expected in `indirect_buffer` is the following: /// /// ```rust /// #[repr(C)] /// struct DrawIndirect { /// vertex_count: u32, // The number of vertices to draw. /// instance_count: u32, // The number of instances to draw. /// base_vertex: u32, // The Index of the first vertex to draw. /// base_instance: u32, // The instance ID of the first instance to draw. /// } /// ``` /// /// These draw structures are expected to be tightly packed. /// /// The structure expected in `count_buffer` is the following: /// /// ```rust /// #[repr(C)] /// struct DrawIndirectCount { /// count: u32, // Number of draw calls to issue. /// } /// ``` pub fn multi_draw_indirect_count( &mut self, indirect_buffer: &'a Buffer, indirect_offset: BufferAddress, count_buffer: &'a Buffer, count_offset: BufferAddress, max_count: u32, ) { self.id.multi_draw_indirect_count( &indirect_buffer.id, indirect_offset, &count_buffer.id, count_offset, max_count, ); } /// Dispatches multiple draw calls from the active index buffer and the active vertex buffers, /// based on the contents of the `indirect_buffer`. The count buffer is read to determine how many draws to issue. /// /// The indirect buffer must be long enough to account for `max_count` draws, however only `count` will /// draws will be read. If `count` is greater than `max_count`, `max_count` will be used. /// /// The active index buffer can be set with [`RenderPass::set_index_buffer`], while the active /// vertex buffers can be set with [`RenderPass::set_vertex_buffer`]. /// /// The structure expected in `indirect_buffer` is the following: /// /// ```rust /// #[repr(C)] /// struct DrawIndexedIndirect { /// vertex_count: u32, // The number of vertices to draw. /// instance_count: u32, // The number of instances to draw. /// base_index: u32, // The base index within the index buffer. /// vertex_offset: i32, // The value added to the vertex index before indexing into the vertex buffer. /// base_instance: u32, // The instance ID of the first instance to draw. /// } /// ``` /// /// These draw structures are expected to be tightly packed. /// /// The structure expected in `count_buffer` is the following: /// /// ```rust /// #[repr(C)] /// struct DrawIndexedIndirectCount { /// count: u32, // Number of draw calls to issue. /// } /// ``` pub fn multi_draw_indexed_indirect_count( &mut self, indirect_buffer: &'a Buffer, indirect_offset: BufferAddress, count_buffer: &'a Buffer, count_offset: BufferAddress, max_count: u32, ) { self.id.multi_draw_indexed_indirect_count( &indirect_buffer.id, indirect_offset, &count_buffer.id, count_offset, max_count, ); } } /// [`Features::PUSH_CONSTANTS`] must be enabled on the device in order to call these functions. impl<'a> RenderPass<'a> { /// Set push constant data. /// /// Offset is measured in bytes, but must be a multiple of [`PUSH_CONSTANT_ALIGNMENT`]. /// /// Data size must be a multiple of 4 and must be aligned to the 4s, so we take an array of u32. /// For example, with an offset of 4 and an array of `[u32; 3]`, that will write to the range /// of 4..16. /// /// For each byte in the range of push constant data written, the union of the stages of all push constant /// ranges that covers that byte must be exactly `stages`. There's no good way of explaining this simply, /// so here are some examples: /// /// ```text /// For the given ranges: /// - 0..4 Vertex /// - 4..8 Fragment /// ``` /// /// You would need to upload this in two set_push_constants calls. First for the `Vertex` range, second for the `Fragment` range. /// /// ```text /// For the given ranges: /// - 0..8 Vertex /// - 4..12 Fragment /// ``` /// /// You would need to upload this in three set_push_constants calls. First for the `Vertex` only range 0..4, second /// for the `Vertex | Fragment` range 4..8, third for the `Fragment` range 8..12. pub fn set_push_constants(&mut self, stages: ShaderStages, offset: u32, data: &[u8]) { self.id.set_push_constants(stages, offset, data); } } /// [`Features::TIMESTAMP_QUERY`] must be enabled on the device in order to call these functions. impl<'a> RenderPass<'a> { /// Issue a timestamp command at this point in the queue. The /// timestamp will be written to the specified query set, at the specified index. /// /// Must be multiplied by [`Queue::get_timestamp_period`] to get /// the value in nanoseconds. Absolute values have no meaning, /// but timestamps can be subtracted to get the time it takes /// for a string of operations to complete. pub fn write_timestamp(&mut self, query_set: &QuerySet, query_index: u32) { self.id.write_timestamp(&query_set.id, query_index) } } /// [`Features::PIPELINE_STATISTICS_QUERY`] must be enabled on the device in order to call these functions. impl<'a> RenderPass<'a> { /// Start a pipeline statistics query on this render pass. It can be ended with /// `end_pipeline_statistics_query`. Pipeline statistics queries may not be nested. pub fn begin_pipeline_statistics_query(&mut self, query_set: &QuerySet, query_index: u32) { self.id .begin_pipeline_statistics_query(&query_set.id, query_index); } /// End the pipeline statistics query on this render pass. It can be started with /// `begin_pipeline_statistics_query`. Pipeline statistics queries may not be nested. pub fn end_pipeline_statistics_query(&mut self) { self.id.end_pipeline_statistics_query(); } } impl<'a> Drop for RenderPass<'a> { fn drop(&mut self) { if !thread::panicking() { let parent_id = self.parent.id.as_ref().unwrap(); self.parent .context .command_encoder_end_render_pass(parent_id, &mut self.id); } } } impl<'a> ComputePass<'a> { /// Sets the active bind group for a given bind group index. The bind group layout /// in the active pipeline when the `dispatch()` function is called must match the layout of this bind group. /// /// If the bind group have dynamic offsets, provide them in order of their declaration. /// These offsets have to be aligned to [`BIND_BUFFER_ALIGNMENT`]. pub fn set_bind_group( &mut self, index: u32, bind_group: &'a BindGroup, offsets: &[DynamicOffset], ) { ComputePassInner::set_bind_group(&mut self.id, index, &bind_group.id, offsets); } /// Sets the active compute pipeline. pub fn set_pipeline(&mut self, pipeline: &'a ComputePipeline) { ComputePassInner::set_pipeline(&mut self.id, &pipeline.id); } /// Inserts debug marker. pub fn insert_debug_marker(&mut self, label: &str) { self.id.insert_debug_marker(label); } /// Start record commands and group it into debug marker group. pub fn push_debug_group(&mut self, label: &str) { self.id.push_debug_group(label); } /// Stops command recording and creates debug group. pub fn pop_debug_group(&mut self) { self.id.pop_debug_group(); } /// Dispatches compute work operations. /// /// `x`, `y` and `z` denote the number of work groups to dispatch in each dimension. pub fn dispatch(&mut self, x: u32, y: u32, z: u32) { ComputePassInner::dispatch(&mut self.id, x, y, z); } /// Dispatches compute work operations, based on the contents of the `indirect_buffer`. pub fn dispatch_indirect( &mut self, indirect_buffer: &'a Buffer, indirect_offset: BufferAddress, ) { ComputePassInner::dispatch_indirect(&mut self.id, &indirect_buffer.id, indirect_offset); } } /// [`Features::PUSH_CONSTANTS`] must be enabled on the device in order to call these functions. impl<'a> ComputePass<'a> { /// Set push constant data. /// /// Offset is measured in bytes, but must be a multiple of [`PUSH_CONSTANT_ALIGNMENT`]. /// /// Data size must be a multiple of 4 and must be aligned to the 4s, so we take an array of u32. /// For example, with an offset of 4 and an array of `[u32; 3]`, that will write to the range /// of 4..16. pub fn set_push_constants(&mut self, offset: u32, data: &[u8]) { self.id.set_push_constants(offset, data); } } /// [`Features::TIMESTAMP_QUERY`] must be enabled on the device in order to call these functions. impl<'a> ComputePass<'a> { /// Issue a timestamp command at this point in the queue. The timestamp will be written to the specified query set, at the specified index. /// /// Must be multiplied by [`Queue::get_timestamp_period`] to get /// the value in nanoseconds. Absolute values have no meaning, /// but timestamps can be subtracted to get the time it takes /// for a string of operations to complete. pub fn write_timestamp(&mut self, query_set: &QuerySet, query_index: u32) { self.id.write_timestamp(&query_set.id, query_index) } } /// [`Features::PIPELINE_STATISTICS_QUERY`] must be enabled on the device in order to call these functions. impl<'a> ComputePass<'a> { /// Start a pipeline statistics query on this render pass. It can be ended with /// `end_pipeline_statistics_query`. Pipeline statistics queries may not be nested. pub fn begin_pipeline_statistics_query(&mut self, query_set: &QuerySet, query_index: u32) { self.id .begin_pipeline_statistics_query(&query_set.id, query_index); } /// End the pipeline statistics query on this render pass. It can be started with /// `begin_pipeline_statistics_query`. Pipeline statistics queries may not be nested. pub fn end_pipeline_statistics_query(&mut self) { self.id.end_pipeline_statistics_query(); } } impl<'a> Drop for ComputePass<'a> { fn drop(&mut self) { if !thread::panicking() { let parent_id = self.parent.id.as_ref().unwrap(); self.parent .context .command_encoder_end_compute_pass(parent_id, &mut self.id); } } } impl<'a> RenderBundleEncoder<'a> { /// Finishes recording and returns a [`RenderBundle`] that can be executed in other render passes. pub fn finish(self, desc: &RenderBundleDescriptor) -> RenderBundle { RenderBundle { context: Arc::clone(&self.context), id: Context::render_bundle_encoder_finish(&*self.context, self.id, desc), } } /// Sets the active bind group for a given bind group index. The bind group layout /// in the active pipeline when any `draw()` function is called must match the layout of this bind group. /// /// If the bind group have dynamic offsets, provide them in order of their declaration. pub fn set_bind_group( &mut self, index: u32, bind_group: &'a BindGroup, offsets: &[DynamicOffset], ) { RenderInner::set_bind_group(&mut self.id, index, &bind_group.id, offsets) } /// Sets the active render pipeline. /// /// Subsequent draw calls will exhibit the behavior defined by `pipeline`. pub fn set_pipeline(&mut self, pipeline: &'a RenderPipeline) { RenderInner::set_pipeline(&mut self.id, &pipeline.id) } /// Sets the active index buffer. /// /// Subsequent calls to [`draw_indexed`](RenderBundleEncoder::draw_indexed) on this [`RenderBundleEncoder`] will /// use `buffer` as the source index buffer. pub fn set_index_buffer(&mut self, buffer_slice: BufferSlice<'a>, index_format: IndexFormat) { RenderInner::set_index_buffer( &mut self.id, &buffer_slice.buffer.id, index_format, buffer_slice.offset, buffer_slice.size, ) } /// Assign a vertex buffer to a slot. /// /// Subsequent calls to [`draw`] and [`draw_indexed`] on this /// [`RenderBundleEncoder`] will use `buffer` as one of the source vertex buffers. /// /// The `slot` refers to the index of the matching descriptor in /// [`VertexState::buffers`]. /// /// [`draw`]: RenderBundleEncoder::draw /// [`draw_indexed`]: RenderBundleEncoder::draw_indexed pub fn set_vertex_buffer(&mut self, slot: u32, buffer_slice: BufferSlice<'a>) { RenderInner::set_vertex_buffer( &mut self.id, slot, &buffer_slice.buffer.id, buffer_slice.offset, buffer_slice.size, ) } /// Draws primitives from the active vertex buffer(s). /// /// The active vertex buffers can be set with [`RenderBundleEncoder::set_vertex_buffer`]. pub fn draw(&mut self, vertices: Range<u32>, instances: Range<u32>) { RenderInner::draw(&mut self.id, vertices, instances) } /// Draws indexed primitives using the active index buffer and the active vertex buffers. /// /// The active index buffer can be set with [`RenderBundleEncoder::set_index_buffer`], while the active /// vertex buffers can be set with [`RenderBundleEncoder::set_vertex_buffer`]. pub fn draw_indexed(&mut self, indices: Range<u32>, base_vertex: i32, instances: Range<u32>) { RenderInner::draw_indexed(&mut self.id, indices, base_vertex, instances); } /// Draws primitives from the active vertex buffer(s) based on the contents of the `indirect_buffer`. /// /// The active vertex buffers can be set with [`RenderBundleEncoder::set_vertex_buffer`]. /// /// The structure expected in `indirect_buffer` is the following: /// /// ```rust /// #[repr(C)] /// struct DrawIndirect { /// vertex_count: u32, // The number of vertices to draw. /// instance_count: u32, // The number of instances to draw. /// base_vertex: u32, // The Index of the first vertex to draw. /// base_instance: u32, // The instance ID of the first instance to draw. /// } /// ``` pub fn draw_indirect(&mut self, indirect_buffer: &'a Buffer, indirect_offset: BufferAddress) { self.id.draw_indirect(&indirect_buffer.id, indirect_offset); } /// Draws indexed primitives using the active index buffer and the active vertex buffers, /// based on the contents of the `indirect_buffer`. /// /// The active index buffer can be set with [`RenderBundleEncoder::set_index_buffer`], while the active /// vertex buffers can be set with [`RenderBundleEncoder::set_vertex_buffer`]. /// /// The structure expected in `indirect_buffer` is the following: /// /// ```rust /// #[repr(C)] /// struct DrawIndexedIndirect { /// vertex_count: u32, // The number of vertices to draw. /// instance_count: u32, // The number of instances to draw. /// base_index: u32, // The base index within the index buffer. /// vertex_offset: i32, // The value added to the vertex index before indexing into the vertex buffer. /// base_instance: u32, // The instance ID of the first instance to draw. /// } /// ``` pub fn draw_indexed_indirect( &mut self, indirect_buffer: &'a Buffer, indirect_offset: BufferAddress, ) { self.id .draw_indexed_indirect(&indirect_buffer.id, indirect_offset); } } /// [`Features::PUSH_CONSTANTS`] must be enabled on the device in order to call these functions. impl<'a> RenderBundleEncoder<'a> { /// Set push constant data. /// /// Offset is measured in bytes, but must be a multiple of [`PUSH_CONSTANT_ALIGNMENT`]. /// /// Data size must be a multiple of 4 and must be aligned to the 4s, so we take an array of u32. /// For example, with an offset of 4 and an array of `[u32; 3]`, that will write to the range /// of 4..16. /// /// For each byte in the range of push constant data written, the union of the stages of all push constant /// ranges that covers that byte must be exactly `stages`. There's no good way of explaining this simply, /// so here are some examples: /// /// ```text /// For the given ranges: /// - 0..4 Vertex /// - 4..8 Fragment /// ``` /// /// You would need to upload this in two set_push_constants calls. First for the `Vertex` range, second for the `Fragment` range. /// /// ```text /// For the given ranges: /// - 0..8 Vertex /// - 4..12 Fragment /// ``` /// /// You would need to upload this in three set_push_constants calls. First for the `Vertex` only range 0..4, second /// for the `Vertex | Fragment` range 4..8, third for the `Fragment` range 8..12. pub fn set_push_constants(&mut self, stages: ShaderStages, offset: u32, data: &[u8]) { self.id.set_push_constants(stages, offset, data); } } impl Queue { /// Schedule a data write into `buffer` starting at `offset`. /// /// This method is intended to have low performance costs. /// As such, the write is not immediately submitted, and instead enqueued /// internally to happen at the start of the next `submit()` call. pub fn write_buffer(&self, buffer: &Buffer, offset: BufferAddress, data: &[u8]) { Context::queue_write_buffer(&*self.context, &self.id, &buffer.id, offset, data) } /// Schedule a data write into `texture`. /// /// This method is intended to have low performance costs. /// As such, the write is not immediately submitted, and instead enqueued /// internally to happen at the start of the next `submit()` call. pub fn write_texture( &self, texture: ImageCopyTexture, data: &[u8], data_layout: ImageDataLayout, size: Extent3d, ) { Context::queue_write_texture(&*self.context, &self.id, texture, data, data_layout, size) } /// Submits a series of finished command buffers for execution. pub fn submit<I: IntoIterator<Item = CommandBuffer>>(&self, command_buffers: I) { Context::queue_submit( &*self.context, &self.id, command_buffers .into_iter() .map(|mut comb| comb.id.take().unwrap()), ); } /// Gets the amount of nanoseconds each tick of a timestamp query represents. /// /// Returns zero if timestamp queries are unsupported. pub fn get_timestamp_period(&self) -> f32 { Context::queue_get_timestamp_period(&*self.context, &self.id) } /// Returns a future that resolves once all the work submitted by this point /// is done processing on GPU. pub fn on_submitted_work_done(&self) -> impl Future<Output = ()> + Send { Context::queue_on_submitted_work_done(&*self.context, &self.id) } } impl Drop for SurfaceTexture { fn drop(&mut self) { if !thread::panicking() { Context::surface_present(&*self.texture.context, &self.texture.id, &self.detail); } } } impl Surface { /// Returns an optimal texture format to use for the [`Surface`] with this adapter. /// /// Returns None if the surface is incompatible with the adapter. pub fn get_preferred_format(&self, adapter: &Adapter) -> Option<TextureFormat> { Context::surface_get_preferred_format(&*self.context, &self.id, &adapter.id) } /// Initializes [`Surface`] for presentation. /// /// # Panics /// /// - A old [`SurfaceFrame`] is still alive referencing an old surface. /// - Texture format requested is unsupported on the surface. pub fn configure(&self, device: &Device, config: &SurfaceConfiguration) { Context::surface_configure(&*self.context, &self.id, &device.id, config) } /// Returns the next texture to be presented by the swapchain for drawing. /// /// When the [`SurfaceFrame`] returned by this method is dropped, the swapchain will present /// the texture to the associated [`Surface`]. /// /// If a SurfaceFrame referencing this surface is alive when the swapchain is recreated, /// recreating the swapchain will panic. pub fn get_current_frame(&self) -> Result<SurfaceFrame, SurfaceError> { let (texture_id, status, detail) = Context::surface_get_current_texture(&*self.context, &self.id); let output = texture_id.map(|id| SurfaceTexture { texture: Texture { context: Arc::clone(&self.context), id, owned: false, }, detail, }); match status { SurfaceStatus::Good => Ok(SurfaceFrame { output: output.unwrap(), suboptimal: false, }), SurfaceStatus::Suboptimal => Ok(SurfaceFrame { output: output.unwrap(), suboptimal: true, }), SurfaceStatus::Timeout => Err(SurfaceError::Timeout), SurfaceStatus::Outdated => Err(SurfaceError::Outdated), SurfaceStatus::Lost => Err(SurfaceError::Lost), } } } /// Type for the callback of uncaptured error handler pub trait UncapturedErrorHandler: Fn(Error) + Send + 'static {} impl<T> UncapturedErrorHandler for T where T: Fn(Error) + Send + 'static {} /// Error type #[derive(Debug)] pub enum Error { /// Out of memory error OutOfMemoryError { /// source: Box<dyn error::Error + Send + 'static>, }, /// Validation error, signifying a bug in code or data ValidationError { /// source: Box<dyn error::Error + Send + 'static>, /// description: String, }, } impl error::Error for Error { fn source(&self) -> Option<&(dyn error::Error + 'static)> { match self { Error::OutOfMemoryError { source } => Some(source.as_ref()), Error::ValidationError { source, .. } => Some(source.as_ref()), } } } impl Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Error::OutOfMemoryError { .. } => f.write_str("Out of Memory"), Error::ValidationError { description, .. } => f.write_str(description), } } }
35.492944
143
0.633933
6ab5f9b7265aaf0754f80045a8870bbce300df4f
950
use crate::model::response::{OrderData, Response}; use crate::model::{Order, Orders}; use crate::{BitbankError, Error}; use serde::Deserialize; use std::convert::TryFrom; #[derive(Deserialize)] pub struct OrdersData { orders: Vec<OrderData>, } impl Into<Orders> for OrdersData { fn into(self) -> Orders { let orders = self.orders; let mut values: Vec<Order> = Vec::with_capacity(orders.len()); for order in orders { values.push(order.into()); } Orders { values } } } impl TryFrom<Response> for OrdersData { type Error = Error; fn try_from(resp: Response) -> Result<Self, Self::Error> { let code = resp.data.as_object().unwrap().get("code"); if code.is_some() { return Err(Error::ApiError(BitbankError::new( code.unwrap().as_i64().unwrap(), ))); } Ok(serde_json::from_value::<Self>(resp.data)?) } }
26.388889
70
0.593684
2fc0b9c6d0f6ac243b0529cfce8ee8374220f720
33,415
//! A simple, efficient utility for slicing string slices into smaller string //! slices. Useful for parsing anything represented by strings, such as //! programming languages or data formats. //! //! ## Examples //! //! Basic usage: //! //! ``` //! # use slicer::AsSlicer; //! let path = "images/cat.jpeg"; //! let mut slicer = path.as_slicer(); //! //! let directory = slicer.slice_until("/"); //! slicer.skip_over("/"); //! let filename = slicer.slice_until("."); //! slicer.skip_over("."); //! let extension = slicer.slice_to_end(); //! //! assert_eq!(Some("images"), directory); //! assert_eq!(Some("cat"), filename); //! assert_eq!(Some("jpeg"), extension); //! ``` /// Describes a type that can be cheaply converted into a [`StrSlicer`]. /// /// [`StrSlicer`]: struct.StrSlicer.html pub trait AsSlicer<'str> { /// Converts the type to a [`StrSlicer`]. /// /// # Examples /// /// ``` /// # use slicer::AsSlicer; /// let mut slicer = "This string will turn into a slicer".as_slicer(); /// ``` /// /// [`StrSlicer`]: struct.StrSlicer.html fn as_slicer(&self) -> StrSlicer<'str>; /// Converts the type to a slicer with the given [`Tracker`]. /// /// # Examples /// /// ``` /// # use slicer::AsSlicer; /// use slicer::trackers::LineTracker; /// /// let mut slicer = "This string will turn into a slicer using the given tracker".as_slicer_with_tracker(LineTracker::new()); /// ``` /// /// [`Tracker`]: trait.Tracker.html fn as_slicer_with_tracker<T: Tracker>(&'str self, tracker: T) -> StrSlicer<'str, T>; } impl<'str> AsSlicer<'str> for &'str str { fn as_slicer(&self) -> StrSlicer<'str> { StrSlicer::new(self) } fn as_slicer_with_tracker<T: Tracker>(&self, tracker: T) -> StrSlicer<'str, T> { StrSlicer::with_tracker(self, tracker) } } /// Describes a type that tracks information as the [`StrSlicer`] goes through the string. /// /// [`StrSlicer`]: struct.StrSlicer.html pub trait Tracker { /// Type of the position returned from [`StrSlicer::tracker_pos`]. /// /// [`StrSlicer::tracker_pos`]: struct.StrSlicer.html#method.tracker_pos type Pos; /// Returns the position information tracked by this tracker. Called by [`StrSlicer::tracker_pos`]. /// /// [`StrSlicer::tracker_pos`]: struct.StrSlicer.html#method.tracker_pos fn pos(&self) -> Self::Pos; /// Updates the position information tracked by this tracker. Called internally when the [`StrSlicer`] changes its position, such as when [`jump_to`] or [`jump_to_unchecked`] are called. /// /// [`StrSlicer`]: struct.StrSlicer.html /// [`jump_to`]: struct.StrSlicer.html#method.jump_to /// [`jump_to_unchecked`]: struct.StrSlicer.html#method.jump_to_unchecked fn update(&mut self, string: &str, old_byte_pos: usize, new_byte_pos: usize); } /// Allows the `()` type to be used as a null tracker, that doesn't do anything. impl Tracker for () { type Pos = (); fn pos(&self) -> Self::Pos { () } fn update(&mut self, _string: &str, _old_byte_pos: usize, _new_byte_pos: usize) {} } /// Describes a type that can be used as an input to many of [`StrSlicer`]'s methods. /// /// [`StrSlicer`]: struct.StrSlicer.html pub trait Pattern { /// Checks whether the pattern is found in the given [`StrSlicer`] at its current postion. /// /// See [`StrSlicer::is_next`] for more details. /// /// [`StrSlicer`]: struct.StrSlicer.html /// [`StrSlicer::is_next`]: struct.StrSlicer.html#method.is_next fn is_next<'str, T: Tracker>(&mut self, slicer: &StrSlicer<'str, T>) -> bool; /// Steps the given [`StrSlicer`] ahead until this pattern is next, or until the end of string is hit. /// /// See [`StrSlicer::skip_until`] and [`StrSlicer::slice_until`] for more details. /// /// [`StrSlicer`]: struct.StrSlicer.html /// [`StrSlicer::skip_until`]: struct.StrSlicer.html#method.skip_until /// [`StrSlicer::slice_until`]: struct.StrSlicer.html#method.slice_until fn skip_until<'str, T: Tracker>(&mut self, slicer: &mut StrSlicer<'str, T>); /// Steps the given [`StrSlicer`] over this pattern. Doesn't check if the pattern is actually next. /// /// See [`StrSlicer::skip_over`] for more details. /// /// [`StrSlicer`]: struct.StrSlicer.html /// [`StrSlicer::skip_over`]: struct.StrSlicer.html#method.skip_over unsafe fn skip_over_unchecked<'str, T: Tracker>(&mut self, slicer: &mut StrSlicer<'str, T>); } impl<'a> Pattern for &'a str { fn is_next<'str, T: Tracker>(&mut self, slicer: &StrSlicer<'str, T>) -> bool { /*let start_pos = slicer.byte_pos(); let end_pos = start_pos + self.len(); if end_pos >= slicer.end_byte_pos() { false } else { *self == &slicer.string[start_pos..end_pos] }*/ match slicer.cut_off() { None => false, Some(cut_off) => cut_off.starts_with(*self) } } fn skip_until<'str, T: Tracker>(&mut self, slicer: &mut StrSlicer<'str, T>) { let cut_off = match slicer.cut_off() { None => return, //return early, since the slicer is finished so there's nothing we can do Some(cut_off) => cut_off }; match cut_off.find(*self) { //if this pattern was not found in the string, simulate skipping until the end of the string None => slicer.skip_to_end(), //if the pattern was found, jump to it Some(offset) => { let byte_pos = slicer.byte_pos; unsafe { slicer.jump_to_unchecked(byte_pos + offset); } } } } unsafe fn skip_over_unchecked<'str, T: Tracker>(&mut self, slicer: &mut StrSlicer<'str, T>) { let byte_pos = slicer.byte_pos; slicer.jump_to_unchecked(byte_pos + self.len()); } } impl Pattern for char { fn is_next<'str, T: Tracker>(&mut self, slicer: &StrSlicer<'str, T>) -> bool { match slicer.as_str().chars().next() { Some(char) => *self == char, None => false } } fn skip_until<'str, T: Tracker>(&mut self, slicer: &mut StrSlicer<'str, T>) { let cut_off = match slicer.cut_off() { None => return, //return early, since the slicer is finished so there's nothing we can do Some(cut_off) => cut_off }; match cut_off.find(*self) { //if this pattern was not found in the string, simulate skipping until the end of the string None => slicer.skip_to_end(), //if the pattern was found, jump to it Some(offset) => { let byte_pos = slicer.byte_pos; unsafe { slicer.jump_to_unchecked(byte_pos + offset); } } } } unsafe fn skip_over_unchecked<'str, T: Tracker>(&mut self, slicer: &mut StrSlicer<'str, T>) { let byte_pos = slicer.byte_pos; slicer.jump_to_unchecked(byte_pos + self.len_utf8()); } } impl<F: FnMut(char) -> bool> Pattern for F { fn is_next<'str, T: Tracker>(&mut self, slicer: &StrSlicer<'str, T>) -> bool { match slicer.as_str().chars().next() { Some(char) => self(char), None => false } } fn skip_until<'str, T: Tracker>(&mut self, slicer: &mut StrSlicer<'str, T>) { let cut_off = match slicer.cut_off() { None => return, //return early, since the slicer is finished so there's nothing we can do Some(cut_off) => cut_off }; match cut_off.find(self) { //if this pattern was not found in the string, simulate skipping until the end of the string None => slicer.skip_to_end(), //if the pattern was found, jump to it Some(offset) => { let byte_pos = slicer.byte_pos; unsafe { slicer.jump_to_unchecked(byte_pos + offset) } } } } unsafe fn skip_over_unchecked<'str, T: Tracker>(&mut self, slicer: &mut StrSlicer<'str, T>) { slicer.advance_char(); } } /// A string slicer. /// /// Walks over a string slice, slicing it into smaller string slices. /// /// Slicing methods (those titled `slice_…`) return an `None` once the slicer /// has walked to the end, which makes it easy to avoid infinite loops. #[derive(Debug, Clone, Copy)] pub struct StrSlicer<'str, T: Tracker = ()> { string: &'str str, byte_pos: usize, tracker: T } impl<'str> StrSlicer<'str, ()> { /// Creates a `StrSlicer` from the given string slice. /// /// You should prefer to use [`AsSlicer::as_slicer`]. /// /// # Examples /// /// ``` /// # use slicer::StrSlicer; /// let mut slicer = StrSlicer::new("This string is being turned into a string slicer."); /// ``` /// /// [`AsSlicer::as_slicer`]: trait.AsSlicer.html#tymethod.as_slicer.html pub fn new(string: &'str str) -> Self { Self { string, byte_pos: 0, tracker: () } } } impl<'str, T: Tracker> StrSlicer<'str, T> { /// Creates a `StrSlicer` from the given string slice and [`Tracker`]. /// /// You should prefer to use [`AsSlicer::as_slicer_with_tracker`]. /// /// # Examples /// /// ``` /// # use slicer::StrSlicer; /// use slicer::trackers::LineTracker; /// /// let mut slicer = StrSlicer::with_tracker("This string is being turned into a string slicer.", LineTracker::new()); /// ``` /// /// [`AsSlicer::as_slicer_with_tracker`]: trait.AsSlicer.html#tymethod.as_slicer_with_tracker.html /// [`Tracker`]: trait.Tracker.html pub fn with_tracker(string: &'str str, tracker: T) -> Self { Self { string: string, byte_pos: 0, tracker } } fn next_char_boundary(&self) -> Option<usize> { let mut next_byte_pos = self.byte_pos + 1; loop { if next_byte_pos >= self.end_byte_pos() { return None; } if self.string.is_char_boundary(next_byte_pos) { return Some(next_byte_pos); } else { next_byte_pos += 1; continue; } } } fn advance_char(&mut self) { let byte_pos = self.next_char_boundary().unwrap_or(self.end_byte_pos()); unsafe { self.jump_to_unchecked(byte_pos); } } #[inline] fn end_byte_pos(&self) -> usize { self.string.len() } /// Returns a reference to the string slice that this slicer is operating on. /// /// The returned strign slice has the same lifetime as the slicer itself. /// /// `StrSlicer` also implments the standard trait [`AsRef<str>`](https://doc.rust-lang.org/nightly/std/convert/trait.AsRef.html), /// which does the same thing. /// /// # Examples /// /// ``` /// # use slicer::AsSlicer; /// let string = "..."; /// let slicer = string.as_slicer(); /// /// assert_eq!(string, slicer.as_str()); /// ``` #[inline] pub fn as_str(&self) -> &'str str { self.string } /// Cuts off the end of the string slice at the current position and returns that slice, /// without also jumping ahead to the end, as [`slice_to_end`] does. /// /// The returned string slice has the same lifetime as the slicer itself. /// /// # Examples /// /// ``` /// # use slicer::AsSlicer; /// let mut slicer = "beepboop".as_slicer(); /// slicer.jump_to(4); /// assert_eq!(slicer.cut_off(), Some("boop")); /// ``` /// /// [`slice_to_end`]: struct.StrSlicer.html#method.slice_to_end pub fn cut_off(&self) -> Option<&'str str> { if self.is_at_end() { None } else { let start_pos = self.byte_pos; let end_pos = self.end_byte_pos(); Some(&self.string[start_pos..end_pos]) } } /// Gets the slicer's current position in the string as a byte index. /// /// # Examples /// /// ``` /// # use slicer::AsSlicer; /// let mut slicer = "Violets are the best flower.".as_slicer(); /// slicer.jump_to(5); /// assert_eq!(slicer.byte_pos(), 5); /// ``` #[inline] pub fn byte_pos(&self) -> usize { self.byte_pos } /// Jumps the slicer to the given byte index /// /// # Panics /// /// Panics if `byte_pos` is not on a UTF-8 code point boundary, or if it is /// beyond the end of the string slice. /// /// # Examples /// /// ``` /// # use slicer::AsSlicer; /// let mut slicer = "Violets are the best flower.".as_slicer(); /// slicer.jump_to(5); /// assert_eq!(slicer.byte_pos(), 5); /// ``` /// /// Jumping to the middle of a UTF-8 codepoint panics. This example panics: /// /// ```should_panic /// # use slicer::AsSlicer; /// let mut slicer = "🌺 is a hibiscus.".as_slicer(); /// slicer.jump_to(2); //the hibiscus emoji is 4 bytes long, so jumping to the middle of it panics. /// ``` pub fn jump_to(&mut self, byte_pos: usize) { if byte_pos > self.end_byte_pos() { jump_oob_fail(self.string, byte_pos); } if self.string.is_char_boundary(byte_pos) { unsafe { self.jump_to_unchecked(byte_pos); } } else { jump_char_boundary_fail(self.string, byte_pos) } } /// Equivalent to [`jump_to`], except without any bounds checking. /// /// You should almost always prefer to use [`jump_to`]. /// /// # Safety /// /// This function will never panic, although if `byte_pos` is not on a UTF-8 /// code point boundary, the slicer will be left in an illegal state and may panic on later method calls. /// /// Jumping beyond the last code point of the string slice, however, will not leave /// the slicer in an illegal state, it will act the same as if [`skip_to_end`] was called. /// /// [`jump_to`]: struct.StrSlicer.html#method.jump_to /// [`skip_to_end`]: struct.StrSlicer.html#method.skip_to_end pub unsafe fn jump_to_unchecked(&mut self, byte_pos: usize) { let string = self.as_str(); self.tracker.update(string, self.byte_pos, byte_pos); self.byte_pos = byte_pos; } /// Returns a reference to this slicer's tracker. /// /// ``` /// # use slicer::AsSlicer; /// use slicer::trackers::LineTracker; /// /// let mut slicer = "This string is being turned into a string slicer.".as_slicer_with_tracker(LineTracker::new()); /// let tracker = slicer.tracker(); /// ``` pub fn tracker(&self) -> &T { &self.tracker } /// Returns a mutable reference to this slicer's tracker. /// /// ``` /// # use slicer::AsSlicer; /// use slicer::trackers::LineTracker; /// /// let mut slicer = "This string is being turned into a string slicer.".as_slicer_with_tracker(LineTracker::new()); /// let tracker = slicer.tracker_mut(); /// ``` pub fn tracker_mut(&mut self) -> &mut T { &mut self.tracker } /// Gets the position value that this slicer's [`Tracker`] is tracking. /// /// ``` /// # use slicer::AsSlicer; /// use slicer::trackers::LineTracker; /// /// let mut slicer = "Line 1\nLine 2\nLine 3".as_slicer_with_tracker(LineTracker::new()); /// slicer.skip_to_end(); /// assert_eq!(slicer.tracker_pos(), 2); /// ``` /// /// [`Tracker`]: trait.Tracker.html #[inline] pub fn tracker_pos(&self) -> T::Pos { self.tracker.pos() } //pub fn skip_num_bytes(&mut self, num: usize); //pub fn slice_num_bytes(&mut self, num: usize) -> Option<&'str str>; /// Skips over `num` chars in this slicer's string. /// /// # Examples /// /// ``` /// # use slicer::AsSlicer; /// let mut slicer = "🌷 Tulip!".as_slicer(); /// slicer.skip_num_chars(1); /// assert_eq!(slicer.cut_off(), Some(" Tulip!")); /// ``` pub fn skip_num_chars(&mut self, num: usize) { for _ in 0..num { self.advance_char(); if self.is_at_end() { break; } } } /// Skips over `num` chars in this slicer's string, and returns the area skipped over as a string slice. /// /// Returns `None` if this slicer is past the end of the string. /// /// # Examples /// /// ``` /// # use slicer::AsSlicer; /// let mut slicer = "🌷 For a period in 1636-1637, tulips were considered extremely valuable.".as_slicer(); /// assert_eq!(slicer.slice_num_chars(1), Some("🌷")); /// ``` pub fn slice_num_chars(&mut self, num: usize) -> Option<&'str str> { let start_pos = self.byte_pos; if start_pos >= self.end_byte_pos() { None } else { self.skip_num_chars(num); let end_pos = self.byte_pos; Some(&self.string[start_pos..end_pos]) } } /// Checks whether or not the given [`Pattern`] is next. /// /// # Examples /// /// ``` /// # use slicer::AsSlicer; /// let mut slicer = "123456".as_slicer(); /// assert_eq!(slicer.skip_over("123"), true); /// assert_eq!(slicer.is_next("456"), true); /// ``` pub fn is_next<P: Pattern>(&self, mut pattern: P) -> bool { pattern.is_next(self) } /// Checks whether or not the given [`Pattern`] is next, if its next, it skips over /// the pattern and returns true, if its not it does nothing and returns false. /// /// # Examples /// /// ``` /// # use slicer::AsSlicer; /// let mut slicer = "123456".as_slicer(); /// if slicer.skip_over("123") { /// assert_eq!(slicer.is_next("456"), true); /// } else { /// unreachable!() /// } /// ``` /// /// [`Pattern`]: trait.Pattern.html pub fn skip_over<P: Pattern>(&mut self, mut pattern: P) -> bool { if pattern.is_next(self) { unsafe { pattern.skip_over_unchecked(self); } true } else { false } } /// Skips over the given [`Pattern`] without checking to see if its actually next. /// /// You should almost always prefer to use [`skip_over`]. /// /// [`skip_over`]: struct.StrSlicer.html#method.skip_over /// [`Pattern`]: trait.Pattern.html pub unsafe fn skip_over_unchecked<P: Pattern>(&mut self, mut pattern: P) { pattern.skip_over_unchecked(self) } /// Skips forward until the given [`Pattern`] is next. /// /// # Examples /// /// ``` /// # use slicer::AsSlicer; /// let mut slicer = "This is a sentence.".as_slicer(); /// slicer.skip_until("sentence"); /// assert_eq!(slicer.is_next("sentence"), true); /// ``` /// /// [`Pattern`]: trait.Pattern.html pub fn skip_until<P: Pattern>(&mut self, mut pattern: P) { pattern.skip_until(self); } /// Skips forward until the given [`Pattern`] is next, and returns the area skipped over as a string slice. /// /// Returns `None` if this slicer is past the end of the string. /// /// # Examples /// /// ``` /// # use slicer::AsSlicer; /// let mut slicer = "This is a sentence.".as_slicer(); /// assert_eq!(slicer.slice_until("sentence"), Some("This is a ")); /// ``` /// /// [`Pattern`]: trait.Pattern.html pub fn slice_until<P: Pattern>(&mut self, pattern: P) -> Option<&'str str> { let start_pos = self.byte_pos; if start_pos >= self.end_byte_pos() { None } else { self.skip_until(pattern); let end_pos = self.byte_pos; Some(&self.string[start_pos..end_pos]) } } /// Skips forward until the given [`Pattern`] is next, then skips over the pattern. /// /// # Examples /// /// ``` /// # use slicer::AsSlicer; /// let mut slicer = "This is a sentence.".as_slicer(); /// slicer.skip_until_after("sentence"); /// assert_eq!(slicer.is_next("."), true); /// ``` /// /// [`Pattern`]: trait.Pattern.html pub fn skip_until_after<P: Pattern>(&mut self, mut pattern: P) { pattern.skip_until(self); if !self.is_at_end() { //`skip_until` skips through the string until the pattern is found, so we're safe to //assume the pattern is next and we don't need to use the checked version of `skip_over` unsafe { pattern.skip_over_unchecked(self); } } } /// Skips forward until the given [`Pattern`] is next, then skips over the pattern and returns the area skipped over as a string slice. /// /// Returns `None` if this slicer is past the end of the string. /// /// # Examples /// /// ``` /// # use slicer::AsSlicer; /// let mut slicer = "This is a sentence.".as_slicer(); /// assert_eq!(slicer.slice_until("sentence"), Some("This is a ")); /// ``` /// /// [`Pattern`]: trait.Pattern.html pub fn slice_until_after<P: Pattern>(&mut self, pattern: P) -> Option<&'str str> { let start_pos = self.byte_pos; if start_pos >= self.end_byte_pos() { None } else { self.skip_until_after(pattern); let end_pos = self.byte_pos; Some(&self.string[start_pos..end_pos]) } } /// Skips forward until a non-whitespace character is next. /// /// If a non-whitespace character is already next, nothing is done. /// /// Equivalent to `skip_until(|char: char| !char.is_whitespace())` /// /// # Examples /// /// ``` /// # use slicer::AsSlicer; /// let mut slicer = "This is a flower 🌹.".as_slicer(); /// slicer.skip_over("This"); /// slicer.skip_whitespace(); /// assert_eq!(slicer.is_next("is"), true); /// ``` pub fn skip_whitespace(&mut self) { self.skip_until(|char: char| !char.is_whitespace()); } /// Skips forward until a non-whitespace character is next, and returns the area skipped over as a string slice. /// /// If a non-whitespace character is already next, nothing is done. /// /// Returns `None` if this slicer is past the end of the string. /// /// Equivalent to `slice_until(|char: char| !char.is_whitespace())` /// /// # Examples /// /// ``` /// # use slicer::AsSlicer; /// let mut slicer = "This is a flower 🌹.".as_slicer(); /// slicer.skip_over("This"); /// assert_eq!(slicer.slice_whitespace(), Some(" ")); /// ``` pub fn slice_whitespace(&mut self) -> Option<&'str str> { self.slice_until(|char: char| !char.is_whitespace()) } /// Skips forward until a whitespace character is next. /// /// If a whitespace character is already next, nothing is done. /// /// Opposite of [`skip_whitespace`]. /// /// Equivalent to `skip_until(|char: char| char.is_whitespace())` /// /// # Examples /// /// ``` /// # use slicer::AsSlicer; /// let mut slicer = "This is a sentence.".as_slicer(); /// slicer.skip_non_whitespace(); /// assert_eq!(slicer.is_next(" is"), true); /// ``` /// /// [`skip_whitespace`]: struct.StrSlicer.html#method.skip_whitespace pub fn skip_non_whitespace(&mut self) { self.skip_until(|char: char| char.is_whitespace()); } /// Skips forward until a whitespace character is next, and returns the area skipped over as a string slice. /// /// If a whitespace character is already next, nothing is done. /// /// Returns `None` if this slicer is past the end of the string. /// /// Opposite of [`slice_whitespace`]. /// /// Equivalent to `slice_until(|char: char| char.is_whitespace())` /// /// # Examples /// /// ``` /// # use slicer::AsSlicer; /// let mut slicer = "This is a sentence.".as_slicer(); /// assert_eq!(slicer.slice_non_whitespace(), Some("This")); /// ``` /// /// [`slice_whitespace`]: struct.StrSlicer.html#method.slice_whitespace pub fn slice_non_whitespace(&mut self) -> Option<&'str str> { self.slice_until(|char: char| char.is_whitespace()) } /// Skips past the rest of the line. /// /// Equivalent to `skip_until_after('\n')` /// /// # Examples /// /// ``` /// # use slicer::AsSlicer; /// let mut slicer = "Line 1\nLine 2\nLine 3".as_slicer(); /// slicer.skip_line(); /// slicer.skip_line(); /// assert_eq!(slicer.is_next("Line 3"), true); /// ``` pub fn skip_line(&mut self) { self.skip_until_after('\n'); } /// Skips past the rest of the line, and returns the area skipped over as a string slice. /// /// The returned string slice also has the newline characters removed, regardless of /// whether the line ending is `\r\n` or `\n`. It handles line endings the same way as /// the standard library function [`str::lines()`](https://doc.rust-lang.org/nightly/std/primitive.str.html#method.lines). /// /// # Examples /// /// ``` /// # use slicer::AsSlicer; /// let mut slicer = "Line 1\nLine 2\nLine 3".as_slicer(); /// assert_eq!(slicer.slice_line(), Some("Line 1")); /// assert_eq!(slicer.slice_line(), Some("Line 2")); /// assert_eq!(slicer.slice_line(), Some("Line 3")); /// ``` pub fn slice_line(&mut self) -> Option<&'str str> { let line = self.slice_until_after('\n'); line.map(|line| { line.trim_right_matches(|char: char| char == '\n' || char == '\r') }) } /// Skips to the end of the string. /// /// # Examples /// /// ``` /// # use slicer::AsSlicer; /// let mut slicer = "This is a very long string that we just want to skip over entirely.".as_slicer(); /// slicer.skip_to_end(); /// assert_eq!(slicer.is_at_end(), true); /// ``` pub fn skip_to_end(&mut self) { unsafe { let byte_pos = self.end_byte_pos(); self.jump_to_unchecked(byte_pos); } } /// Skips to the end of the string, and returns the area skipped over as a string slice. /// /// # Examples /// /// ``` /// # use slicer::AsSlicer; /// let mut slicer = "This is a very long string that we just want to skip over entirely.".as_slicer(); /// slicer.skip_until_after("skip over"); /// assert_eq!(slicer.slice_to_end(), Some(" entirely.")); /// ``` pub fn slice_to_end(&mut self) -> Option<&'str str> { let start_pos = self.byte_pos; if start_pos >= self.end_byte_pos() { None } else { self.skip_to_end(); let end_pos = self.byte_pos; Some(&self.string[start_pos..end_pos]) } } /// Checks whether or not the string slicer is at or past the end of the string it is operating on. /// /// # Examples /// /// ``` /// # use slicer::AsSlicer; /// let mut slicer = "This is a very long string that we just want to skip over entirely.".as_slicer(); /// slicer.skip_to_end(); /// assert_eq!(slicer.is_at_end(), true); /// ``` pub fn is_at_end(&self) -> bool { self.byte_pos >= self.end_byte_pos() } } impl<'str, T: Tracker> AsRef<str> for StrSlicer<'str, T> { fn as_ref(&self) -> &str { self.string } } /// Used by `jump_oob_fail` and `jump_char_boundary_fail` //truncate `&str` to length at most equal to `max`, //return `true` if it were truncated, and the new str. //basically copied from the truncate_to_char_boundary function in libcore/str/mod.rs fn truncate_to_char_boundary(s: &str, mut max: usize) -> (bool, &str) { if max >= s.len() { (false, s) } else { while !s.is_char_boundary(max) { max -= 1; } (true, &s[..max]) } } /// Function that panics for out-of-bound errors in [`StrSlicer::jump_to`] /// /// [`StrSlicer::jump_to`]: struct.StrSlicer.html#method.jump_to //basically copied from the slice_error_fail function in libcore/str/mod.rs #[inline(never)] #[cold] fn jump_oob_fail(string: &str, byte_pos: usize) -> ! { const MAX_DISPLAY_LENGTH: usize = 256; let (truncated, s_trunc) = truncate_to_char_boundary(string, MAX_DISPLAY_LENGTH); let ellipsis = if truncated { "[...]" } else { "" }; panic!("byte index {} is out of bounds of `{}`{}", byte_pos, s_trunc, ellipsis); } /// Function that panics for jumping to a position that is not a UTF-8 /// char boundary in [`StrSlicer::jump_to`] /// /// [`StrSlicer::jump_to`]: struct.StrSlicer.html#method.jump_to //basically copied from the slice_error_fail function in libcore/str/mod.rs #[inline(never)] #[cold] fn jump_char_boundary_fail(string: &str, byte_pos: usize) -> ! { const MAX_DISPLAY_LENGTH: usize = 256; let (truncated, s_trunc) = truncate_to_char_boundary(string, MAX_DISPLAY_LENGTH); let ellipsis = if truncated { "[...]" } else { "" }; //find the start index of the character byte_pos is inside of let mut char_start = byte_pos; while !string.is_char_boundary(char_start) { char_start -= 1; } //`char_start` must be less than len and a char boundary let char = string[char_start..].chars().next().unwrap(); let char_byte_range = char_start..(char_start + char.len_utf8()); panic!("byte index {} is not a char boundary; it is inside {:?} (bytes {:?}) of `{}`{}", byte_pos, char, char_byte_range, s_trunc, ellipsis); } /// A module containing various [`Tracker`] types. /// /// [`Tracker`]: trait.Tracker.html pub mod trackers { use ::Tracker; const NEWLINE: char = '\n'; /// A [`Tracker`] that tracks the line number. /// /// # Examples /// /// ``` /// # use slicer::AsSlicer; /// use slicer::trackers::LineTracker; /// /// let mut slicer = "Line 1\nLine 2\nLine 3".as_slicer_with_tracker(LineTracker::new()); /// slicer.skip_line(); //skip over line 0 /// assert_eq!(slicer.tracker_pos(), 1); //it is currently on line 1 /// ``` /// /// [`Tracker`]: ../trait.Tracker.html #[derive(Debug, Clone)] pub struct LineTracker { lines: usize, line_byte_pos: usize } impl LineTracker { pub fn new() -> Self { Self { lines: 0, line_byte_pos: 0 } } /// Returns the line number. The same as this type's implementation of the [`Tracker::pos`] method. /// /// [`Tracker::pos`]: ../trait.Tracker.html#tymethod.pos #[inline] pub fn lines(&self) -> usize { self.lines } /// Returns byte index of the start of the current line. #[inline] pub fn line_byte_pos(&self) -> usize { self.line_byte_pos } } impl Default for LineTracker { fn default() -> Self { Self::new() } } impl Tracker for LineTracker { type Pos = usize; fn pos(&self) -> Self::Pos { self.lines } fn update(&mut self, string: &str, old_byte_pos: usize, new_byte_pos: usize) { //if we're jumping forward, simply add up the newlines in the area we're jumping through if new_byte_pos > old_byte_pos { let mut newline_count = 0; for (index, _) in string[old_byte_pos..new_byte_pos].match_indices(NEWLINE) { newline_count += 1; self.line_byte_pos = index; } self.lines += newline_count; //if we're jumping backwards, we either start over and count the number of newlines //from the beginning, or subtract newlines, depending on how far the point we've jumped to //is from the start } else if new_byte_pos < old_byte_pos { let diff = old_byte_pos - new_byte_pos; let half_len_to_root = old_byte_pos / 2; if diff > half_len_to_root { let mut newline_count = 0; for (index, _) in string[0..new_byte_pos].match_indices(NEWLINE) { newline_count += 1; self.line_byte_pos = index; } self.lines = newline_count; } else { let mut newline_count = 0; for (index, _) in string[new_byte_pos..old_byte_pos].match_indices(NEWLINE) { newline_count += 1; self.line_byte_pos = index; } self.lines -= newline_count; } } } } }
34.807292
190
0.563789
89e3855689afcc209e8645cc5af9dec24e09982b
906
use serde_json::Value; use super::super::helpers; use super::super::schema; use super::super::validators; #[allow(missing_copy_implementations)] pub struct Contains; impl super::Keyword for Contains { fn compile(&self, def: &Value, ctx: &schema::WalkContext<'_>) -> super::KeywordResult { let contains = keyword_key_exists!(def, "contains"); if contains.is_object() || contains.is_boolean() { Ok(Some(Box::new(validators::Contains { url: helpers::alter_fragment_path( ctx.url.clone(), [ctx.escaped_fragment().as_ref(), "contains"].join("/"), ), }))) } else { Err(schema::SchemaError::Malformed { path: ctx.fragment.join("/"), detail: "The value of contains MUST be an object or a boolean".to_string(), }) } } }
32.357143
91
0.562914
3995e0676fd7873963e109660f2fd5ab7f860407
2,066
// This file is part of security-keys-rust. 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/security-keys-rust/master/COPYRIGHT. No part of security-keys-rust, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2021 The developers of security-keys-rust. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/security-keys-rust/master/COPYRIGHT. /// Class-specific AS interface descriptor. #[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)] #[derive(Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub enum Version3AudioStreamingInterfaceExtraDescriptor { #[allow(missing_docs)] General(General), #[allow(missing_docs)] ValidSamplingFrequencyRange(FrequencyRange), } impl Version3AudioStreamingInterfaceExtraDescriptor { pub(super) const AS_DESCRIPTOR_UNDEFINED: u8 = 0x00; pub(super) const AS_GENERAL: u8 = 0x01; pub(super) const AS_VALID_FREQ_RANGE: u8 = 0x02; #[inline(always)] pub(super) fn parse_general(bLength: u8, descriptor_body_followed_by_remaining_bytes: &[u8]) -> Result<Self, Version3AudioStreamingInterfaceExtraDescriptorParseError> { Ok(Version3AudioStreamingInterfaceExtraDescriptor::General(General::parse(bLength, descriptor_body_followed_by_remaining_bytes).map_err(Version3AudioStreamingInterfaceExtraDescriptorParseError::GeneralParse)?)) } #[inline(always)] pub(super) fn parse_valid_sampling_frequency_range(bLength: u8, descriptor_body_followed_by_remaining_bytes: &[u8]) -> Result<Self, Version3AudioStreamingInterfaceExtraDescriptorParseError> { Ok(Version3AudioStreamingInterfaceExtraDescriptor::ValidSamplingFrequencyRange(FrequencyRange::parse(bLength, descriptor_body_followed_by_remaining_bytes).map_err(Version3AudioStreamingInterfaceExtraDescriptorParseError::ValidSamplingFrequencyRangeParse)?)) } }
54.368421
409
0.822846
29d14e665209f51d26e53da020ce53b15f39874a
2,393
use cgmath::Vector2; /// Vertex for textured quads #[repr(C)] #[derive(Default, Debug, Clone, Copy)] pub struct TextVertex { pub position: [f32; 2], pub normal: [f32; 2], pub tex_coords: [f32; 2], pub color: [f32; 4], } vulkano::impl_vertex!(TextVertex, position, normal, tex_coords, color); impl TextVertex { pub fn x(&self) -> f32 { self.position[0] } pub fn y(&self) -> f32 { self.position[1] } pub fn empty() -> TextVertex { TextVertex { position: [0.0; 2], normal: [0.0; 2], tex_coords: [0.0; 2], color: [0.0; 4], } } } pub fn textured_quad(color: [f32; 4], width: f32, height: f32) -> (Vec<TextVertex>, Vec<u32>) { ( vec![ TextVertex { position: [-(width / 2.0), -(height / 2.0)], normal: [0.0, 0.0], tex_coords: [0.0, 1.0], color, }, TextVertex { position: [-(width / 2.0), height / 2.0], normal: [0.0, 0.0], tex_coords: [0.0, 0.0], color, }, TextVertex { position: [width / 2.0, height / 2.0], normal: [0.0, 0.0], tex_coords: [1.0, 0.0], color, }, TextVertex { position: [width / 2.0, -(height / 2.0)], normal: [0.0, 0.0], tex_coords: [1.0, 1.0], color, }, ], vec![0, 2, 1, 0, 3, 2], ) } pub struct Line(pub Vector2<f32>, pub Vector2<f32>, pub [f32; 4]); pub fn line_vertices(lines: &[Line]) -> (Vec<TextVertex>, Vec<u32>) { let mut vertices = Vec::<TextVertex>::with_capacity(lines.len()); let mut indices = Vec::<u32>::with_capacity(lines.len()); let mut i = 0; for line in lines { vertices.push(TextVertex { position: [line.0.x, line.0.y], normal: [0.0, 0.0], tex_coords: [0.0, 0.0], color: line.2, }); vertices.push(TextVertex { position: [line.1.x, line.1.y], normal: [0.0, 0.0], tex_coords: [0.0, 0.0], color: line.2, }); indices.push(i); indices.push(i + 1); i += 2; } (vertices, indices) }
26.588889
95
0.442541
0119e8d6c3a41c4a1ee95e1fdaff5f84fbfc430b
4,142
// @See Build Scripts: // - https://doc.rust-lang.org/cargo/reference/build-scripts.html // - https://doc.rust-lang.org/cargo/reference/build-script-examples.html #![allow(dead_code)] // Avoid false positive warning due to calling members from another module use std::env; use std::{collections::HashMap}; use std::io::Write; use phf::phf_map; use serde::Serialize; use toml; use cryptor_global::io; use cryptor_global::console; use cryptor_global::system; // ----------------------------------------------------------------------------------------------- // C O N F I G U R A T I O N // ----------------------------------------------------------------------------------------------- // @See Cargo Config // - https://doc.rust-lang.org/cargo/reference/config.html // ----------------------------------------------------------------------------------------------- static ANDROID_NDK_ENV_VAR: &str = "ANDROID_NDK_HOME"; static ANDROID_TOOLCHAINS_PATH: &str = "/toolchains/llvm/prebuilt/linux-x86_64/bin/"; /** * Due to Rust limitations on generating a static Map with a custom type, a tuple was * needed with the following value representation: * - Tuple.0 = Archiver to be used to assemble static libraries compiled from C/C++ code. * - Tuple.1 = Linker to be used to link Rust code. */ pub static ANDROID_TARGETS: phf::Map<&'static str, (&'static str, &'static str)> = phf_map! { "armv7-linux-androideabi" => ("arm-linux-androideabi-ar", "armv7a-linux-androideabi21-clang"), "aarch64-linux-android" => ("aarch64-linux-android-ar", "aarch64-linux-android21-clang"), "i686-linux-android" => ("i686-linux-android-ar", "i686-linux-android21-clang"), "x86_64-linux-android" => ("x86_64-linux-android-ar", "x86_64-linux-android21-clang"), }; // ----------------------------------------------------------------------------------------------- struct AndroidConfig; impl AndroidConfig { fn ndk_dir() -> String { env::var(ANDROID_NDK_ENV_VAR).unwrap() } fn toolchains_dir() -> String { format!("{ndk}{toolchains}", ndk=Self::ndk_dir(), toolchains=ANDROID_TOOLCHAINS_PATH) } } #[derive(Serialize)] struct AndroidTargets<'a> { #[serde(rename(serialize = "target"))] targets: HashMap<&'a str, AndroidTargetConfig>, } #[derive(Serialize)] struct AndroidTargetConfig { // Archiver to be used to assemble static // libraries compiled from C/C++ code. ar: String, //Linker to be used to link Rust code. linker: String, } fn build_archiver(archiver_path: &str) -> String { format!("{toolchain}{ar}", toolchain=AndroidConfig::toolchains_dir(), ar=archiver_path) } fn build_linker(linker_path: &str) -> String { format!("{toolchain}{linker}", toolchain=AndroidConfig::toolchains_dir(), linker=linker_path) } fn android_targets<'a>() -> AndroidTargets<'a> { let mut android_targets = AndroidTargets { targets: HashMap::with_capacity(ANDROID_TARGETS.len()) }; for (target, config) in ANDROID_TARGETS.entries() { let target_config = AndroidTargetConfig { ar: build_archiver(config.0), linker: build_linker(config.1) }; android_targets.targets.insert(target, target_config); } AndroidTargets { targets: android_targets.targets } } fn create_android_targets_config_file() { let targets_config = android_targets(); let mut config_file = io::create_cargo_config_file(&env::current_dir().unwrap()); let toml = toml::to_string(&targets_config).unwrap(); match config_file.write_all(toml.as_bytes()) { Err(why) => panic!("Couldn't write Android Configuration: {}", why), Ok(_) => println!("Successfully wrote Android Configuration File."), }; } fn add_android_targets_to_toolchain() { let mut command_args = Vec::new(); command_args.push("target"); command_args.push("add"); for target in ANDROID_TARGETS.keys() { command_args.push(target) } console::run_command("rustup", &command_args.as_slice()); } fn main() { system::rerun_if_changed("build.rs"); create_android_targets_config_file(); add_android_targets_to_toolchain(); }
35.101695
113
0.629889
ac08bfaee7a310c92c13e62a1a3c9a3b9c7b910b
3,731
/* * Copyright 2018-2020 TON DEV SOLUTIONS LTD. * * Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use * this file except in compliance with the License. * * 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 TON DEV software governing permissions and * limitations under the License. */ use ton_types::{Cell, HashmapE, SliceData}; use ton_vm::{ executor::{Engine, BehaviorModifiers, gas::gas_state::Gas}, smart_contract_info::SmartContractInfo, stack::{Stack, StackItem, savelist::SaveList} }; /// Builder for virtual machine engine. Initialises registers, /// stack and code of VM engine. Returns initialized instance of TVM. pub struct VMSetup { vm: Engine, code: SliceData, ctrls: SaveList, stack: Option<Stack>, gas: Option<Gas>, libraries: Vec<HashmapE> } impl VMSetup { /// Creates new instance of VMSetup with contract code. /// Initializes some registers of TVM with predefined values. pub fn new(code: SliceData) -> Self { VMSetup { vm: Engine::new(), code, ctrls: SaveList::new(), stack: None, gas: Some(Gas::empty()), libraries: vec![], } } /// Sets SmartContractInfo for TVM register c7 pub fn set_contract_info(mut self, sci: SmartContractInfo) -> VMSetup { self.ctrls.put(7, &mut sci.into_temp_data()).unwrap(); self } /// Sets persistent data for contract in register c4 pub fn set_data(mut self, data: Cell) -> VMSetup { self.ctrls.put(4, &mut StackItem::Cell(data)).unwrap(); self } /// Sets initial stack for TVM pub fn set_stack(mut self, stack: Stack) -> VMSetup { self.stack = Some(stack); self } /// Sets gas for TVM pub fn set_gas(mut self, gas: Gas) -> VMSetup { self.gas = Some(gas); self } /// Sets libraries for TVM pub fn set_libraries(mut self, libraries: Vec<HashmapE>) -> VMSetup { self.libraries = libraries; self } /// Sets trace flag to TVM for printing stack and commands pub fn set_debug(mut self, enable: bool) -> VMSetup { if enable { self.vm.set_trace(Engine::TRACE_ALL); } else { self.vm.set_trace(0); } self } /// Disables signature check pub fn modify_behavior(mut self, modifiers: BehaviorModifiers) -> VMSetup { self.vm.modify_behavior(modifiers); self } /// Creates new instance of TVM with defined stack, registers and code. pub fn create(self) -> Engine { if cfg!(debug_assertions) { // account balance is duplicated in stack and in c7 - so check let balance_in_smc = self .ctrls .get(7) .unwrap() .as_tuple() .unwrap()[0] .as_tuple() .unwrap()[7] .as_tuple() .unwrap()[0] .as_integer() .unwrap(); let stack_depth = self.stack.as_ref().unwrap().depth(); let balance_in_stack = self .stack .as_ref() .unwrap() .get(stack_depth - 1) .as_integer() .unwrap(); assert_eq!(balance_in_smc, balance_in_stack); } self.vm.setup_with_libraries(self.code, Some(self.ctrls), self.stack, self.gas, self.libraries) } }
31.091667
103
0.585098
5d886701d7ff35896f22192bcc483742b682378b
8,436
use crate::{PCCommitment, PCCommitterKey, PCRandomness, PCVerifierKey, Vec}; use algebra_core::{PairingEngine, ToBytes}; use core::ops::{Add, AddAssign}; use rand_core::RngCore; use crate::kzg10; /// `UniversalParams` are the universal parameters for the KZG10 scheme. pub type UniversalParams<E> = kzg10::UniversalParams<E>; /// `ComitterKey` is used to commit to and create evaluation proofs for a given /// polynomial. #[derive(Derivative)] #[derivative( Default(bound = ""), Hash(bound = ""), Clone(bound = ""), Debug(bound = "") )] pub struct CommitterKey<E: PairingEngine> { /// The key used to commit to polynomials. pub powers: Vec<E::G1Affine>, /// The key used to commit to shifted polynomials. /// This is `None` if `self` does not support enforcing any degree bounds. pub shifted_powers: Option<Vec<E::G1Affine>>, /// The key used to commit to hiding polynomials. pub powers_of_gamma_g: Vec<E::G1Affine>, /// The degree bounds that are supported by `self`. /// In ascending order from smallest to largest. /// This is `None` if `self` does not support enforcing any degree bounds. pub enforced_degree_bounds: Option<Vec<usize>>, /// The maximum degree supported by the `UniversalParams` `self` was derived /// from. pub max_degree: usize, } impl<E: PairingEngine> CommitterKey<E> { /// Obtain powers for the underlying KZG10 construction pub fn powers<'a>(&'a self) -> kzg10::Powers<'a, E> { kzg10::Powers { powers_of_g: self.powers.as_slice().into(), powers_of_gamma_g: self.powers_of_gamma_g.as_slice().into(), } } /// Obtain powers for committing to shifted polynomials. pub fn shifted_powers<'a>( &'a self, degree_bound: impl Into<Option<usize>>, ) -> Option<kzg10::Powers<'a, E>> { self.shifted_powers.as_ref().map(|shifted_powers| { let powers_range = if let Some(degree_bound) = degree_bound.into() { assert!(self .enforced_degree_bounds .as_ref() .unwrap() .contains(&degree_bound)); let max_bound = self .enforced_degree_bounds .as_ref() .unwrap() .last() .unwrap(); (max_bound - degree_bound).. } else { 0.. }; let ck = kzg10::Powers { powers_of_g: (&shifted_powers[powers_range]).into(), powers_of_gamma_g: self.powers_of_gamma_g.as_slice().into(), }; ck }) } } impl<E: PairingEngine> PCCommitterKey for CommitterKey<E> { fn max_degree(&self) -> usize { self.max_degree } fn supported_degree(&self) -> usize { self.powers.len() } } /// `VerifierKey` is used to check evaluation proofs for a given commitment. #[derive(Derivative)] #[derivative(Default(bound = ""), Clone(bound = ""), Debug(bound = ""))] pub struct VerifierKey<E: PairingEngine> { /// The verification key for the underlying KZG10 scheme. pub vk: kzg10::VerifierKey<E>, /// Information required to enforce degree bounds. Each pair /// is of the form `(degree_bound, shifting_advice)`. /// The vector is sorted in ascending order of `degree_bound`. /// This is `None` if `self` does not support enforcing any degree bounds. pub degree_bounds_and_shift_powers: Option<Vec<(usize, E::G1Affine)>>, /// The maximum degree supported by the `UniversalParams` `self` was derived /// from. pub max_degree: usize, /// The maximum degree supported by the trimmed parameters that `self` is /// a part of. pub supported_degree: usize, } impl<E: PairingEngine> VerifierKey<E> { /// Find the appropriate shift for the degree bound. pub fn get_shift_power(&self, bound: usize) -> Option<E::G1Affine> { self.degree_bounds_and_shift_powers.as_ref().and_then(|v| { v.binary_search_by(|(d, _)| d.cmp(&bound)) .ok() .map(|i| v[i].1) }) } } impl<E: PairingEngine> PCVerifierKey for VerifierKey<E> { fn max_degree(&self) -> usize { self.max_degree } fn supported_degree(&self) -> usize { self.supported_degree } } /// Commitment to a polynomial that optionally enforces a degree bound. #[derive(Derivative)] #[derivative( Default(bound = ""), Hash(bound = ""), Clone(bound = ""), Copy(bound = ""), Debug(bound = ""), PartialEq(bound = ""), Eq(bound = "") )] pub struct Commitment<E: PairingEngine> { /// Commitment pub comm: kzg10::Commitment<E>, /// Shifted Commitment pub shifted_comm: Option<kzg10::Commitment<E>>, } impl<E: PairingEngine> ToBytes for Commitment<E> { #[inline] fn write<W: algebra_core::io::Write>(&self, mut writer: W) -> algebra_core::io::Result<()> { self.comm.write(&mut writer)?; let shifted_exists = self.shifted_comm.is_some(); shifted_exists.write(&mut writer)?; self.shifted_comm .as_ref() .unwrap_or(&kzg10::Commitment::empty()) .write(&mut writer) } } impl<E: PairingEngine> PCCommitment for Commitment<E> { #[inline] fn empty() -> Self { Self { comm: kzg10::Commitment::empty(), shifted_comm: Some(kzg10::Commitment::empty()), } } fn has_degree_bound(&self) -> bool { self.shifted_comm.is_some() } fn size_in_bytes(&self) -> usize { self.comm.size_in_bytes() + self.shifted_comm.as_ref().map_or(0, |c| c.size_in_bytes()) } } /// `Randomness` hides the polynomial inside a commitment. It is output by `KZG10::commit`. #[derive(Derivative)] #[derivative( Default(bound = ""), Hash(bound = ""), Clone(bound = ""), Debug(bound = ""), PartialEq(bound = ""), Eq(bound = "") )] pub struct Randomness<E: PairingEngine> { pub rand: kzg10::Randomness<E>, pub(crate) shifted_rand: Option<kzg10::Randomness<E>>, } impl<'a, E: PairingEngine> Add<&'a Self> for Randomness<E> { type Output = Self; fn add(mut self, other: &'a Self) -> Self { self += other; self } } impl<'a, E: PairingEngine> AddAssign<&'a Self> for Randomness<E> { #[inline] fn add_assign(&mut self, other: &'a Self) { self.rand += &other.rand; if let Some(r1) = &mut self.shifted_rand { *r1 += other .shifted_rand .as_ref() .unwrap_or(&kzg10::Randomness::empty()); } else { self.shifted_rand = other.shifted_rand.as_ref().map(|r| r.clone()); } } } impl<'a, E: PairingEngine> Add<(E::Fr, &'a Randomness<E>)> for Randomness<E> { type Output = Self; #[inline] fn add(mut self, other: (E::Fr, &'a Randomness<E>)) -> Self { self += other; self } } impl<'a, E: PairingEngine> AddAssign<(E::Fr, &'a Randomness<E>)> for Randomness<E> { #[inline] fn add_assign(&mut self, (f, other): (E::Fr, &'a Randomness<E>)) { self.rand += (f, &other.rand); let empty = kzg10::Randomness::empty(); if let Some(r1) = &mut self.shifted_rand { *r1 += (f, other.shifted_rand.as_ref().unwrap_or(&empty)); } else { self.shifted_rand = other.shifted_rand.as_ref().map(|r| empty + (f, r)); } } } impl<E: PairingEngine> PCRandomness for Randomness<E> { fn empty() -> Self { Self { rand: kzg10::Randomness::empty(), shifted_rand: None, } } fn rand<R: RngCore>(hiding_bound: usize, has_degree_bound: bool, rng: &mut R) -> Self { let shifted_rand = if has_degree_bound { Some(kzg10::Randomness::rand(hiding_bound, false, rng)) } else { None }; Self { rand: kzg10::Randomness::rand(hiding_bound, false, rng), shifted_rand, } } } /// Evaluation proof output by `MultiPCFromSinglePC::batch_open`. #[derive(Derivative)] #[derivative( Default(bound = ""), Hash(bound = ""), Clone(bound = ""), Debug(bound = ""), PartialEq(bound = ""), Eq(bound = "") )] pub struct BatchProof<E: PairingEngine>(pub(crate) Vec<kzg10::Proof<E>>);
31.014706
96
0.587127
64342d81f3af3bd3141259ed8b1c156cf603ae0b
27,231
//! 型推論・型検査 use super::*; use crate::{ cps::{ k_meta_ty::KMetaTyData, k_ty::{KEnumOrStruct, KTy2, KTyCause}, ty_unification::UnificationContext, }, source::{HaveLoc, Loc}, }; use std::{ cell::RefCell, collections::HashMap, mem::{replace, swap, take}, }; /// Typing context. 型検査の状態 struct Tx<'a> { /// 現在の関数の型環境 ty_env: KTyEnv, /// 現在の関数に含まれるローカル変数の情報 local_vars: KLocalVarArena, /// 現在の関数に含まれるラベルのシグネチャ情報 label_sigs: KLabelSigArena, /// ラベルのパラメータにかかる制約 (下界)。 /// /// ラベルにジャンプする際に制約が増える。 /// ラベルの型検査を始める際に決定する。 param_bounds: HashMap<KLabel, Vec<KTy2>>, /// 現在の関数の return ラベルの型 return_ty_opt: Option<KTy>, /// 検査対象のモジュールのアウトライン mod_outline: &'a KModOutline, logger: Logger, } impl<'a> Tx<'a> { fn new(mod_outline: &'a KModOutline, logger: Logger) -> Self { Self { ty_env: KTyEnv::default(), local_vars: Default::default(), label_sigs: Default::default(), param_bounds: Default::default(), return_ty_opt: None, mod_outline, logger, } } fn take_label_bound(&mut self, label: KLabel, len: usize) -> Vec<KTy2> { replace( self.param_bounds .entry(label) .or_insert_with(|| vec![KTy2::Never; len]), vec![], ) } } /// left 型の変数に right 型の値を代入できるか判定する。 /// 必要に応じて型変数を束縛する。 fn unify2(left: &KTy2, right: &KTy2, loc: Loc, tx: &mut Tx) { #[cfg(skip)] log::trace!( "unify: {} <- {} @{:?}", left.display(&tx.ty_env, tx.mod_outline), right.display(&tx.ty_env, tx.mod_outline), loc, ); UnificationContext::new(loc, &tx.ty_env, tx.mod_outline, &tx.logger).unify(&left, &right); } fn fresh_meta_ty(loc: Loc, tx: &mut Tx) -> KTy2 { let meta_ty = tx.ty_env.alloc(KMetaTyData::new(RefCell::default(), loc)); KTy2::Meta(meta_ty) } fn error_invalid_size_of(loc: Loc, logger: &Logger) { logger.error(loc, "この型のサイズは取得できません。"); } fn get_field_ty(struct_ty: &KTy2, field: KField, loc: Loc, tx: &mut Tx) -> KTy2 { match struct_ty { KTy2::Struct(_) => field.ty(&tx.mod_outline.fields).to_ty2_poly(tx.mod_outline), KTy2::App { ty_args, .. } => field .ty(&tx.mod_outline.fields) .substitute(tx.mod_outline, ty_args), _ => { tx.logger.error(loc, "レコード型が必要です"); KTy2::Unresolved { cause: KTyCause::Loc(loc), } } } } fn get_field_or_variant( #[allow(unused)] hint: &str, field_name: &str, left_ty: &KTy2, k_mut: KMut, loc: Loc, tx: &mut Tx, ) -> (Option<KField>, KTy2) { let mut trial = || -> Option<(Option<KField>, KTy2)> { let (_, ty) = left_ty.as_ptr(&tx.ty_env)?; // ジェネリック構造体のケース if let KTy2::App { k_struct, .. } = ty { let field = *k_struct .of(&tx.mod_outline.structs) .fields .iter() .find(|field| field.name(&tx.mod_outline.fields) == field_name)?; let field_ty = get_field_ty(&ty, field, loc, tx).into_ptr(k_mut); return Some((Some(field), field_ty)); } match ty.as_struct_or_enum(&tx.ty_env)? { KEnumOrStruct::Enum(struct_enum) => { let k_struct = *struct_enum .variants(&tx.mod_outline.struct_enums) .iter() .find(|&k_struct| k_struct.name(&tx.mod_outline.structs) == field_name)?; let ty = KTy2::Struct(k_struct).into_ptr(k_mut); Some((None, ty)) } KEnumOrStruct::Struct(k_struct) => { let field = *k_struct .fields(&tx.mod_outline.structs) .iter() .find(|field| field.name(&tx.mod_outline.fields) == field_name)?; let ty = field .ty(&tx.mod_outline.fields) .to_ty2(tx.mod_outline, &mut tx.ty_env) .into_ptr(k_mut); Some((Some(field), ty)) } } }; trial().unwrap_or_else(|| { log::error!( "{} left_ty={:?}", hint, left_ty.display(&tx.ty_env, tx.mod_outline) ); tx.logger.error(loc, "bad type"); (None, KTy2::Never) }) } fn resolve_var_def(term: &mut KVarTerm, expected_ty_opt: Option<&KTy2>, tx: &mut Tx) { if term.ty(&tx.local_vars).is_unresolved() { let expected_ty = match expected_ty_opt { None => fresh_meta_ty(term.loc(), tx), Some(ty) => ty.clone(), }; *term.ty_mut(&mut tx.local_vars) = expected_ty; return; } if let Some(expected_ty) = expected_ty_opt { let term_ty = term.ty(&tx.local_vars); unify2(&term_ty, expected_ty, term.loc(), tx); } } fn resolve_var_use(term: &mut KVarTerm, tx: &mut Tx) -> KTy2 { let current_ty = term.ty(&tx.local_vars); if current_ty.is_unresolved() { error!("def_ty is unresolved. symbol is undefined? {:?}", term); } current_ty } fn resolve_pat(pat: &mut KTerm, expected_ty: &KTy2, tx: &mut Tx) { match pat { KTerm::Name(term) => { resolve_var_def(term, Some(expected_ty), tx); } _ => { resolve_term(pat, tx); } } } fn resolve_term(term: &mut KTerm, tx: &mut Tx) -> KTy2 { match term { KTerm::Unit { .. } => KTy2::Unit, KTerm::Int { ty, .. } => ty.clone(), KTerm::Float { ty, .. } => ty.clone(), KTerm::Char { ty, .. } => ty.clone(), KTerm::Str { .. } => KTy2::C8.into_ptr(KMut::Const), KTerm::True { .. } | KTerm::False { .. } => KTy2::BOOL, KTerm::Const { k_const, .. } => k_const .ty(&tx.mod_outline.consts) .to_ty2(tx.mod_outline, &mut tx.ty_env), KTerm::StaticVar { static_var, .. } => static_var .ty(&tx.mod_outline.static_vars) .to_ty2(tx.mod_outline, &mut tx.ty_env), KTerm::Fn { ty, .. } => ty.clone(), KTerm::Label { label, .. } => label.ty(&tx.label_sigs), KTerm::Return { .. } => tx .return_ty_opt .clone() .unwrap() .to_ty2(tx.mod_outline, &mut tx.ty_env), KTerm::ExternFn { extern_fn, .. } => extern_fn .ty(&tx.mod_outline.extern_fns) .to_ty2(tx.mod_outline, &mut tx.ty_env), KTerm::Name(term) => resolve_var_use(term, tx), KTerm::RecordTag { k_struct, .. } => k_struct .tag_ty(&tx.mod_outline.structs, &tx.mod_outline.struct_enums) .to_ty2(tx.mod_outline, &mut tx.ty_env), KTerm::FieldTag(_) => unreachable!(), KTerm::TyProperty { kind, ty, loc } => { let value_opt = match kind { KTyProperty::AlignOf => ty.align_of(&tx.ty_env, &tx.mod_outline), KTyProperty::SizeOf => ty.size_of(&tx.ty_env, &tx.mod_outline), }; if value_opt.is_none() { error_invalid_size_of(*loc, &tx.logger); } KTy2::USIZE } } } fn resolve_terms(terms: &mut [KTerm], tx: &mut Tx) -> Vec<KTy2> { terms .iter_mut() .map(|term| resolve_term(term, tx)) .collect() } fn resolve_node(node: &mut KNode, tx: &mut Tx) { match node.prim { KPrim::Stuck => {} KPrim::Jump => match node.args.as_mut_slice() { [callee, args @ ..] => loop { let label = match *callee { KTerm::Label { label, .. } => label, KTerm::Return { .. } => { let callee_ty = resolve_term(callee, tx); let arg_tys = resolve_terms(args, tx); let (param_tys, _) = callee_ty.as_fn(&tx.ty_env).unwrap(); let result_ty = param_tys.first().unwrap(); let arg_ty = arg_tys.first().cloned().unwrap_or(KTy2::Unit); unify2(&result_ty, &arg_ty, node.loc, tx); break; } _ => callee.with_debug( tx.mod_outline, Some(&tx.local_vars), Some(&tx.label_sigs), |callee| unreachable!("{:?}", callee), ), }; let param_tys = label.of_mut(&mut tx.label_sigs).param_tys_mut(); if param_tys.len() > args.len() { tx.logger.error( node.loc, format!("{} 個の引数が必要です。", param_tys.len()), ); } let param_tys = param_tys.clone(); let mut bounds = tx.take_label_bound(label, param_tys.len()); let arg_tys = resolve_terms(args, tx); for (((param_ty, bound), arg), arg_ty) in param_tys.iter().zip(&mut bounds).zip(args).zip(arg_tys) { // 型注釈があるか、シグネチャが確定済みのときは単一化する。 if !param_ty.is_unbound(&tx.ty_env) { unify2(param_ty, &arg_ty, arg.loc(), tx); continue; } let current = replace(bound, KTy2::DEFAULT); *bound = current.join(&arg_ty, &tx.ty_env); } tx.param_bounds.insert(label, bounds); break; }, _ => unimplemented!(), }, KPrim::CallDirect => match (node.args.as_mut_slice(), node.results.as_mut_slice()) { ([callee, args @ ..], [result]) => loop { let def_fn_ty = resolve_term(callee, tx); let arg_tys = resolve_terms(args, tx); let (param_tys, result_ty) = match def_fn_ty.as_fn(&tx.ty_env) { Some(it) => it, None => { tx.logger .error(node.loc(), "関数ではないものは呼び出せません"); break; } }; // FIXME: 引数の個数を検査する for (param_ty, arg_ty) in param_tys.iter().zip(&arg_tys) { unify2(param_ty, arg_ty, node.loc, tx); } resolve_var_def(result, Some(&result_ty), tx); break; }, _ => unimplemented!(), }, KPrim::Record => match (node.tys.as_mut_slice(), node.results.as_mut_slice()) { ([ty], [result]) => { let k_struct = match ty.as_struct(&tx.ty_env) { Some(it) => it, None => { tx.logger.error(node.loc(), "レコード型が必要です。"); return; } }; for (arg, field) in node .args .iter_mut() .zip(k_struct.fields(&tx.mod_outline.structs)) { let arg_ty = resolve_term(arg, tx); unify2( &get_field_ty(ty, *field, node.loc, tx), &arg_ty, node.loc, tx, ); } let result_ty = match k_struct.of(&tx.mod_outline.structs).parent { KStructParent::Enum { struct_enum, .. } => KTy2::StructEnum(struct_enum), KStructParent::Struct { .. } => ty.clone(), }; resolve_var_def(result, Some(&result_ty), tx); if !ty.is_struct_or_enum(&tx.ty_env) { // FIXME: DebugWithContext を使う tx.logger .error(result, format!("struct or enum type required")); } } _ => unimplemented!(), }, KPrim::GetField => match (node.args.as_mut_slice(), node.results.as_mut_slice()) { ([left, KTerm::FieldTag(field_tag)], [result]) => { let left_ty = resolve_term(left, tx); let (field_opt, result_ty) = get_field_or_variant( "KPrim::GetField", &field_tag.name, &left_ty, KMut::Const, field_tag.loc, tx, ); field_tag.ty = result_ty.clone(); field_tag.field_opt = field_opt; resolve_var_def(result, Some(&result_ty), tx); } _ => unimplemented!(), }, KPrim::GetFieldMut => match (node.args.as_mut_slice(), node.results.as_mut_slice()) { ([left, KTerm::FieldTag(field_tag)], [result]) => { let loc = field_tag.loc; let left_ty = resolve_term(left, tx); let (field_opt, result_ty) = get_field_or_variant( "KPrim::GetFieldMut", &field_tag.name, &left_ty, KMut::Mut, loc, tx, ); field_tag.ty = result_ty.clone(); field_tag.field_opt = field_opt; resolve_var_def(result, Some(&result_ty), tx); } _ => unimplemented!(), }, KPrim::If => match node.args.as_mut_slice() { [cond] => { let cond_ty = resolve_term(cond, tx); unify2(&KTy2::BOOL, &cond_ty, node.loc, tx); } _ => unimplemented!(), }, KPrim::Switch => match node.args.as_mut_slice() { [cond, pats @ ..] => { let cond_ty = resolve_term(cond, tx); for pat in pats { resolve_pat(pat, &cond_ty, tx); } } _ => unimplemented!(), }, KPrim::Let => match (node.args.as_mut_slice(), node.results.as_mut_slice()) { ([init], [result]) => { let init_ty = resolve_term(init, tx); // 型注釈と単一化する。 let result_ty = { let expected_ty = result.ty(&tx.local_vars); if expected_ty.is_unresolved() { init_ty } else { unify2(&expected_ty, &init_ty, node.loc, tx); expected_ty } }; resolve_var_def(result, Some(&result_ty), tx); } _ => unimplemented!(), }, KPrim::Deref => match (node.args.as_mut_slice(), node.results.as_mut_slice()) { ([arg], [result]) => { let arg_ty = resolve_term(arg, tx); let result_ty_opt = arg_ty.as_ptr(&tx.ty_env).map(|(_, ty)| ty); if result_ty_opt.is_none() { tx.logger.error(&result.loc(), "expected a reference"); } resolve_var_def(result, result_ty_opt.as_ref(), tx); } _ => unimplemented!(), }, KPrim::Ref => match (node.args.as_mut_slice(), node.results.as_mut_slice()) { ([arg], [result]) => { let arg_ty = resolve_term(arg, tx); resolve_var_def(result, Some(&arg_ty.into_ptr(KMut::Const)), tx); } _ => unimplemented!(), }, // FIXME: ref の実装と重複 KPrim::RefMut => match (node.args.as_mut_slice(), node.results.as_mut_slice()) { ([arg], [result]) => { let arg_ty = resolve_term(arg, tx); resolve_var_def(result, Some(&arg_ty.into_ptr(KMut::Mut)), tx); } _ => unimplemented!(), }, KPrim::Cast => match ( node.tys.as_mut_slice(), node.args.as_mut_slice(), node.results.as_mut_slice(), ) { ([ty], [arg], [result]) => { let arg_ty = resolve_term(arg, tx); let target_ty = take(ty); resolve_var_def(result, Some(&target_ty), tx); // FIXME: 同じ型へのキャストは警告? if let KTy2::Unresolved { .. } | KTy2::Never = arg_ty { // Skip. } else if !arg_ty.is_primitive(&tx.ty_env) { // FIXME: DebugWithContext を使う tx.logger .error(&node, format!("can't cast from non-primitive type")); } else if !target_ty.is_primitive(&tx.ty_env) { // FIXME: DebugWithContext を使う let msg = format!("can't cast to non-primitive type"); tx.logger.error(&node, msg); } } _ => unimplemented!(), }, KPrim::Minus => match (node.args.as_mut_slice(), node.results.as_mut_slice()) { ([arg], [result]) => { let arg_ty = resolve_term(arg, tx); // FIXME: bool or iNN resolve_var_def(result, Some(&arg_ty), tx); } _ => unimplemented!(), }, KPrim::Not => match (node.args.as_mut_slice(), node.results.as_mut_slice()) { ([arg], [result]) => { let arg_ty = resolve_term(arg, tx); // FIXME: bool or iNN or uNN resolve_var_def(result, Some(&arg_ty), tx); } _ => unimplemented!(), }, KPrim::Add | KPrim::Sub => match (node.args.as_mut_slice(), node.results.as_mut_slice()) { ([left, right], [result]) => { let left_ty = resolve_term(left, tx); let right_ty = resolve_term(right, tx); if left_ty.is_ptr(&tx.ty_env) { unify2(&KTy2::USIZE, &right_ty, node.loc, tx); } else { // FIXME: iNN or uNN unify2(&left_ty, &right_ty, node.loc, tx); } resolve_var_def(result, Some(&left_ty), tx); } _ => unimplemented!(), }, KPrim::Mul | KPrim::Div | KPrim::Modulo | KPrim::BitAnd | KPrim::BitOr | KPrim::BitXor | KPrim::LeftShift | KPrim::RightShift => match (node.args.as_mut_slice(), node.results.as_mut_slice()) { ([left, right], [result]) => { let left_ty = resolve_term(left, tx); let right_ty = resolve_term(right, tx); // FIXME: iNN or uNN unify2(&left_ty, &right_ty, node.loc, tx); resolve_var_def(result, Some(&left_ty), tx); } _ => unimplemented!(), }, KPrim::Equal | KPrim::NotEqual | KPrim::LessThan | KPrim::LessEqual | KPrim::GreaterThan | KPrim::GreaterEqual => { match (node.args.as_mut_slice(), node.results.as_mut_slice()) { ([left, right], [result]) => { let left_ty = resolve_term(left, tx); let right_ty = resolve_term(right, tx); // FIXME: Eq/Ord only unify2(&left_ty, &right_ty, node.loc, tx); resolve_var_def(result, Some(&KTy2::BOOL), tx); } _ => unimplemented!(), } } KPrim::Assign => match node.args.as_mut_slice() { [left, right] => { let left_ty = resolve_term(left, tx); let right_ty = resolve_term(right, tx); // 左辺は lval なのでポインタ型のはず let left_ty = match left_ty.as_ptr(&tx.ty_env) { Some((KMut::Mut, left_ty)) => left_ty, Some((KMut::Const, left_ty)) => { tx.logger.error(&left.loc(), "expected mutable reference"); left_ty } None => KTy2::Never, }; unify2(&left_ty, &right_ty, node.loc, tx); } _ => unimplemented!(), }, KPrim::AddAssign | KPrim::SubAssign => { match node.args.as_mut_slice() { [left, right] => { let left_ty = resolve_term(left, tx); let right_ty = resolve_term(right, tx); // 左辺は lval なのでポインタ型のはず。ただし不正なコードだと unresolved/never になることもある。 let (k_mut, left_ty) = match left_ty.as_ptr(&tx.ty_env) { Some(it) => it, None => { log::error!( "AddAssign etc. left={}", left_ty.display(&tx.ty_env, &tx.mod_outline) ); ( KMut::Mut, KTy2::Unresolved { cause: KTyCause::Loc(node.loc), }, ) } }; if let KMut::Const = k_mut { tx.logger.error(&left.loc(), "unexpected const reference"); } // FIXME: add/sub と同じ if left_ty.is_ptr(&tx.ty_env) { unify2(&KTy2::USIZE, &right_ty, node.loc, tx); } else { // FIXME: iNN or uNN unify2(&left_ty, &right_ty, node.loc, tx); } } _ => unimplemented!(), } } KPrim::MulAssign | KPrim::DivAssign | KPrim::ModuloAssign | KPrim::BitAndAssign | KPrim::BitOrAssign | KPrim::BitXorAssign | KPrim::LeftShiftAssign | KPrim::RightShiftAssign => { match node.args.as_mut_slice() { [left, right] => { let left_ty = resolve_term(left, tx); let right_ty = resolve_term(right, tx); // 左辺は lval なのでポインタ型のはず let (k_mut, left_ty) = match left_ty.as_ptr(&tx.ty_env) { Some(it) => it, None => { log::error!( "MulAssign etc. left={}", left_ty.display(&tx.ty_env, &tx.mod_outline) ); ( KMut::Mut, KTy2::Unresolved { cause: KTyCause::Loc(node.loc), }, ) } }; if let KMut::Const = k_mut { tx.logger.error(&left.loc(), "unexpected const reference"); } // FIXME: mul/div/etc. と同じ // FIXME: iNN or uNN unify2(&left_ty, &right_ty, node.loc, tx); } _ => unimplemented!(), } } } for cont in &mut node.conts { resolve_node(cont, tx); } } fn prepare_fn(k_fn: KFn, fn_data: &mut KFnData, tx: &mut Tx) { assert!(tx.ty_env.is_empty()); swap(&mut tx.ty_env, &mut fn_data.ty_env); for i in 0..fn_data.params.len() { let param = &mut fn_data.params[i]; let param_ty = &k_fn.param_tys(&tx.mod_outline.fns)[i].to_ty2_poly(tx.mod_outline); resolve_var_def(param, Some(param_ty), tx); } // いまから生成するところなので空のはず。 assert!(fn_data.label_sigs.is_empty()); for label_data in fn_data.labels.iter_mut() { for param in &mut label_data.params { resolve_var_def(param, None, tx); } let label_sig = { let name = label_data.name.to_string(); let param_tys = label_data .params .iter() .map(|param| param.ty(&tx.local_vars)) .collect(); KLabelSig::new(name, param_tys) }; fn_data.label_sigs.alloc(label_sig); } assert_eq!(fn_data.label_sigs.len(), fn_data.labels.len()); swap(&mut tx.ty_env, &mut fn_data.ty_env); } fn prepare_extern_fn(extern_fn: KExternFn, data: &mut KExternFnData, tx: &mut Tx) { for i in 0..data.params.len() { let param = &mut data.params[i]; let param_ty = &extern_fn.param_tys(&tx.mod_outline.extern_fns)[i].to_ty2_poly(tx.mod_outline); resolve_var_def(param, Some(&param_ty), tx); } } fn resolve_root(root: &mut KModData, tx: &mut Tx) { for (extern_fn, extern_fn_data) in root.extern_fns.enumerate_mut() { swap(&mut tx.local_vars, &mut extern_fn_data.local_vars); prepare_extern_fn(extern_fn, extern_fn_data, tx); swap(&mut tx.local_vars, &mut extern_fn_data.local_vars); } // HACK: label_sigs が空でない関数はすでに型検査済みなので無視する。応急処置 for (k_fn, fn_data) in root .fns .enumerate_mut() .filter(|(_, fn_data)| fn_data.label_sigs.is_empty()) { swap(&mut tx.local_vars, &mut fn_data.local_vars); prepare_fn(k_fn, fn_data, tx); swap(&mut tx.local_vars, &mut fn_data.local_vars); } // 項の型を解決する。 for (k_fn, fn_data) in root.fns.enumerate_mut() { #[cfg(skip)] log::trace!("type res fn {}", k_fn.of(&tx.mod_outline.fns).name); tx.return_ty_opt = Some(k_fn.return_ty(&tx.mod_outline.fns)); swap(&mut tx.local_vars, &mut fn_data.local_vars); swap(&mut tx.label_sigs, &mut fn_data.label_sigs); swap(&mut tx.ty_env, &mut fn_data.ty_env); for (label, label_data) in fn_data.labels.enumerate_mut() { #[cfg(skip)] log::trace!("type res label {}", label_data.name); let bounds = tx.take_label_bound(label, label_data.params.len()); for (bound, param) in bounds.iter().zip(label_data.params.iter()) { unify2(&bound, &param.ty(&tx.local_vars), param.loc(), tx); } resolve_node(&mut label_data.body, tx); } for local_var_data in tx.local_vars.iter_mut() { if local_var_data.ty.is_unbound(&tx.ty_env) { local_var_data.ty = KTy2::Never; } } swap(&mut tx.local_vars, &mut fn_data.local_vars); swap(&mut tx.label_sigs, &mut fn_data.label_sigs); swap(&mut tx.ty_env, &mut fn_data.ty_env); tx.return_ty_opt.take(); } } pub(crate) fn resolve_types(mod_outline: &KModOutline, mod_data: &mut KModData, logger: Logger) { KModOutline::given_for_debug(mod_outline, || { let mut tx = Tx::new(mod_outline, logger); resolve_root(mod_data, &mut tx); }); }
35.182171
98
0.471338
16d9ca220dfae0a5a3f7627675a83def6043e837
12,191
use buffer::{Buffer, Direction, Mark}; use input::Input; use uibuf::{UIBuffer, CharColor}; use frontends::Frontend; use overlay::{Overlay, OverlayType}; use std::cmp; /// A View is an abstract Window (into a Buffer). /// /// It draws a portion of a Buffer to a UIBuffer which in turn is drawn to the /// screen. It maintains the status bar for the current view, the "dirty status" /// which is whether the buffer has been modified or not and a number of other /// pieces of information. pub struct View<'v> { pub buffer: Buffer, //Text buffer top_line: Mark, //First character of the top line to be displayed. left_col: uint, //Index into the top line to set the left column to. cursor: Mark, //Cursor displayed by this buffer. uibuf: UIBuffer, //UIBuffer pub overlay: Overlay, threshold: uint, } impl<'v> View<'v> { //----- CONSTRUCTORS --------------------------------------------------------------------------- pub fn new(source: Input, width: uint, height: uint) -> View<'v> { let mut buffer = match source { Input::Filename(path) => { match path { Some(s) => Buffer::new_from_file(Path::new(s)), None => Buffer::new(), } }, Input::Stdin(reader) => { Buffer::new_from_reader(reader) }, }; // NOTE(greg): this may not play well with resizing let uibuf = UIBuffer::new(width, height); let cursor = Mark::Cursor(0); buffer.set_mark(cursor, 0); let top_line = Mark::DisplayMark(0); buffer.set_mark(top_line, 0); View { buffer: buffer, top_line: top_line, left_col: 0, cursor: cursor, uibuf: uibuf, overlay: Overlay::None, threshold: 5, } } pub fn get_height(&self) -> uint { // NOTE(greg): when the status bar needs to move up, this value should be changed self.uibuf.get_height() -1 } pub fn get_width(&self) -> uint { self.uibuf.get_width() } //----- DRAWING METHODS ------------------------------------------------------------------------ /// Clear the buffer /// /// Fills every cell in the UIBuffer with the space (' ') char. pub fn clear<T: Frontend>(&mut self, frontend: &mut T) { self.uibuf.fill(' '); self.uibuf.draw_everything(frontend); } pub fn draw<T: Frontend>(&mut self, frontend: &mut T) { for (index,line) in self.buffer .lines_from(self.top_line) .unwrap() .take(self.get_height()) .enumerate() { draw_line(&mut self.uibuf, line, index, self.left_col); if index == self.get_height() { break; } } match self.overlay { Overlay::None => self.draw_cursor(frontend), _ => { self.overlay.draw(frontend, &mut self.uibuf); self.overlay.draw_cursor(frontend); } } self.draw_status(frontend); self.uibuf.draw_everything(frontend); } fn draw_status<T: Frontend>(&mut self, frontend: &mut T) { let buffer_status = self.buffer.status_text(); let mut cursor_status = self.buffer.get_mark_coords(self.cursor).unwrap_or((0,0)); cursor_status = (cursor_status.0 + 1, cursor_status.1 + 1); let status_text = format!("{} {}", buffer_status, cursor_status).into_bytes(); let status_text_len = status_text.len(); let width = self.get_width(); let height = self.get_height() - 1; for index in range(0, width) { let mut ch: char = ' '; if index < status_text_len { ch = status_text[index] as char; } self.uibuf.update_cell(index, height, ch, CharColor::Black, CharColor::Blue); } self.uibuf.draw_range(frontend, height, height+1); } fn draw_cursor<T: Frontend>(&mut self, frontend: &mut T) { if let Some(top_line) = self.buffer.get_mark_coords(self.top_line) { if let Some((x, y)) = self.buffer.get_mark_coords(self.cursor) { frontend.draw_cursor((x - self.left_col) as int, y as int - top_line.1 as int); } } } pub fn set_overlay(&mut self, overlay_type: OverlayType) { match overlay_type { OverlayType::Prompt => { self.overlay = Overlay::Prompt { cursor_x: 1, prefix: ":", data: String::new(), }; } } } pub fn move_cursor(&mut self, direction: Direction, amount: uint) { self.buffer.shift_mark(self.cursor, direction, amount); self.move_screen(); } pub fn move_cursor_to_line_end(&mut self) { self.buffer.shift_mark(self.cursor, Direction::LineEnd, 0); self.move_screen(); } pub fn move_cursor_to_line_start(&mut self) { self.buffer.shift_mark(self.cursor, Direction::LineStart, 0); self.move_screen(); } //Update the top_line mark if necessary to keep the cursor on the screen. fn move_screen(&mut self) { if let (Some(cursor), Some((_, top_line))) = (self.buffer.get_mark_coords(self.cursor), self.buffer.get_mark_coords(self.top_line)) { let width = (self.get_width() - self.threshold) as int; let height = (self.get_height() - self.threshold) as int; //left-right shifting self.left_col = match cursor.0 as int - self.left_col as int { x_offset if x_offset < self.threshold as int => { cmp::max(0, self.left_col as int - (self.threshold as int - x_offset)) as uint } x_offset if x_offset >= width => { self.left_col + (x_offset - width + 1) as uint } _ => { self.left_col } }; //up-down shifting match cursor.1 as int - top_line as int { y_offset if y_offset < self.threshold as int && top_line > 0 => { self.buffer.shift_mark(self.top_line, Direction::Up, (self.threshold as int - y_offset) as uint); } y_offset if y_offset >= height => { self.buffer.shift_mark(self.top_line, Direction::Down, (y_offset - height + 1) as uint); } _ => { } } } } pub fn delete_chars(&mut self, direction: Direction, num_chars: uint) { let chars = self.buffer.remove_chars(self.cursor, direction, num_chars); match (chars, direction) { (Some(chars), Direction::Left) => { self.move_cursor(Direction::Left, chars.len()); } (Some(chars), Direction::LeftWord(..)) => { self.move_cursor(Direction::Left, chars.len()); } _ => {} } } pub fn insert_tab(&mut self) { // A tab is just 4 spaces for _ in range(0i, 4) { self.insert_char(' '); } } pub fn insert_char(&mut self, ch: char) { self.buffer.insert_char(self.cursor, ch as u8); self.move_cursor(Direction::Right, 1) } pub fn undo(&mut self) { let point = if let Some(transaction) = self.buffer.undo() { transaction.end_point } else { return; }; self.buffer.set_mark(self.cursor, point); self.move_screen(); } pub fn redo(&mut self) { let point = if let Some(transaction) = self.buffer.redo() { transaction.end_point } else { return; }; self.buffer.set_mark(self.cursor, point + 1); self.move_screen(); } } pub fn draw_line(buf: &mut UIBuffer, line: &[u8], idx: uint, left: uint) { let width = buf.get_width() - 1; let mut wide_chars = 0; for line_idx in range(left, left + width) { if line_idx < line.len() { match line[line_idx] { b'\t' => { let w = 4 - line_idx % 4; for _ in range(0, w) { buf.update_cell_content(line_idx + wide_chars - left, idx, ' '); } } b'\n' => buf.update_cell_content(line_idx + wide_chars - left, idx, ' '), _ => buf.update_cell_content(line_idx + wide_chars - left, idx, line[line_idx] as char), } wide_chars += (line[line_idx] as char).width(false).unwrap_or(1) - 1; } else { buf.update_cell_content(line_idx + wide_chars - left, idx, ' '); } } if line.len() >= width { buf.update_cell_content(width + wide_chars, idx, '→'); } } #[cfg(test)] mod tests { use buffer::Direction; use view::View; use input::Input; fn setup_view<'v>(testcase: &'static str) -> View<'v> { let mut view = View::new(Input::Filename(None), 50, 50); for ch in testcase.chars() { view.insert_char(ch); } view.buffer.set_mark(view.cursor, 0); view } #[test] fn test_move_cursor_down() { let mut view = setup_view("test\nsecond"); view.move_cursor(Direction::Down, 1); assert_eq!(view.buffer.get_mark_coords(view.cursor).unwrap().1, 1); assert_eq!(view.buffer.lines_from(view.cursor).unwrap().next().unwrap(), b"second"[]); } #[test] fn test_move_cursor_up() { let mut view = setup_view("test\nsecond"); view.move_cursor(Direction::Down, 1); view.move_cursor(Direction::Up, 1); assert_eq!(view.buffer.get_mark_coords(view.cursor).unwrap().1, 0); assert_eq!(view.buffer.lines_from(view.cursor).unwrap().next().unwrap(), b"test\n"[]); } #[test] fn test_insert_line() { let mut view = setup_view("test\nsecond"); view.move_cursor(Direction::Right, 1); view.insert_char('\n'); assert_eq!(view.buffer.get_mark_coords(view.cursor).unwrap(), (0, 1)) } #[test] fn test_insert_char() { let mut view = setup_view("test\nsecond"); view.insert_char('t'); assert_eq!(view.buffer.lines().next().unwrap(), b"ttest\n"[]); } #[test] fn test_delete_char_to_right() { let mut view = setup_view("test\nsecond"); view.delete_chars(Direction::Right, 1); assert_eq!(view.buffer.lines().next().unwrap(), b"est\n"[]); } #[test] fn test_delete_char_to_left() { let mut view = setup_view("test\nsecond"); view.move_cursor(Direction::Right, 1); view.delete_chars(Direction::Left, 1); assert_eq!(view.buffer.lines().next().unwrap(), b"est\n"[]); } #[test] fn test_delete_char_at_start_of_line() { let mut view = setup_view("test\nsecond"); view.move_cursor(Direction::Down, 1); view.delete_chars(Direction::Left, 1); assert_eq!(view.buffer.lines().next().unwrap(), b"testsecond"[]); } #[test] fn test_delete_char_at_end_of_line() { let mut view = setup_view("test\nsecond"); view.move_cursor(Direction::Right, 4); view.delete_chars(Direction::Right, 1); assert_eq!(view.buffer.lines().next().unwrap(), b"testsecond"[]); } #[test] fn deleting_backward_at_start_of_first_line_does_nothing() { let mut view = setup_view("test\nsecond"); view.delete_chars(Direction::Left, 1); let lines: Vec<&[u8]> = view.buffer.lines().collect(); assert_eq!(lines.len(), 2); assert_eq!(view.buffer.lines().next().unwrap(), b"test\n"); } }
34.340845
100
0.532196
14e7a67d7d343693d0cc82dee4d274241c7d00b0
967
/* Copyright 2019 Takahiro Yamashita 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. */ extern crate libc; #[link(name = "float")] extern "C" { static C_pi: libc::c_double; } pub fn main() { unsafe { println!("C_pi = {}", C_pi); } } #[cfg(test)] mod tests { use super::libc; #[test] fn test_cmp_double_val() { let rust_pi = 3.141592; unsafe { assert_eq!(super::C_pi, rust_pi); } } }
23.02381
75
0.654602
14529bbe94b086c5d7d4cbae3f7a9ec86f9e3f15
3,687
// {{{ Lints #![deny(missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unstable_features, unused_import_braces, unused_qualifications )] // }}} // {{{ Crates use std::fs::File; use std::io::Read; // }}} // {{{ Compress mod compress { /// A compression marker. #[derive(Debug)] struct Marker { length: usize, repeat: usize, } /// Parses an usize value from a stream of bytes. fn parse_usize(stream: &mut Iterator<Item=&u8>) -> usize { stream.map(|&b| b as char).collect::<String>().parse().unwrap() } /// Extracts a marker from the stream. fn extract_marker(stream: &mut Iterator<Item=&u8>) -> Marker { let mut bytes = stream.take_while(|&b| *b != b')'); let length = parse_usize(&mut bytes.by_ref() .take_while(|&b| *b != b'x')); let repeat = parse_usize(&mut bytes); assert!(bytes.next().is_none()); Marker { length: length, repeat: repeat } } /// Computes the size of the string after decompression. fn compute_final_size(mut bytes : &mut Iterator<Item=&u8>, do_recursive_expand: bool) -> u64 { let mut size = 0; while let Some(&b) = bytes.next() { if b == b'(' { let marker = extract_marker(&mut bytes); let mut data = bytes.take(marker.length); let len = if do_recursive_expand { compute_final_size(&mut data, true) } else { // Consumes the iterator. let _ = data.last(); marker.length as u64 }; size += len * (marker.repeat as u64); } else { size += 1; } } size } /// Computes the size of the string after decompression (algorithm v1). pub fn compute_final_size_v1(s : &str) -> u64 { compute_final_size(&mut s.as_bytes().iter(), false) } /// Computes the size of the string after decompression (algorithm v2). /// /// The v2 of the algorithm use recursive expansion of the markers. pub fn compute_final_size_v2(s : &str) -> u64 { compute_final_size(&mut s.as_bytes().iter(), true) } } // }}} use compress::{compute_final_size_v1,compute_final_size_v2}; fn main() { let mut file = File::open("input.txt").unwrap(); let mut input = String::new(); file.read_to_string(&mut input).unwrap(); let input = input.trim(); println!("The decompressed length of the file is {} bytes.", compute_final_size_v1(input)); println!("The real decompressed length of the file is {} bytes.", compute_final_size_v2(input)); } // {{{ Tests #[test] fn examples_part1() { assert_eq!(compute_final_size_v1("ADVENT"), 6); assert_eq!(compute_final_size_v1("A(1x5)BC"), 7); assert_eq!(compute_final_size_v1("(3x3)XYZ"), 9); assert_eq!(compute_final_size_v1("A(2x2)BCD(2x2)EFG"), 11); assert_eq!(compute_final_size_v1("(6x1)(1x3)A"), 6); assert_eq!(compute_final_size_v1("X(8x2)(3x3)ABCY"), 18); } #[test] fn examples_part2() { assert_eq!(compute_final_size_v2("(3x3)XYZ"), 9); assert_eq!(compute_final_size_v2("X(8x2)(3x3)ABCY"), 20); assert_eq!(compute_final_size_v2( "(27x12)(20x12)(13x14)(7x10)(1x12)A"), 241920); assert_eq!(compute_final_size_v2( "(25x3)(3x3)ABC(2x3)XY(5x2)PQRSTX(18x9)(3x2)TWO(5x7)SEVEN"), 445); } // }}}
30.221311
78
0.565229
38898d297c04d15f06e9639bf7a34ed4f084f0ee
952
#![warn(clippy::all, clippy::pedantic)] mod commands; mod config; mod console; mod document; mod editor; mod mode; mod navigator; mod row; mod terminal; mod utils; use editor::Editor; use structopt::StructOpt; pub use config::Config; pub use console::{Console, Size}; pub use document::Document; pub use editor::Position; pub use mode::Mode; pub use navigator::{Boundary, Navigator}; pub use row::Row; pub use terminal::Terminal; pub use utils::{bo_version, log}; #[derive(Debug, StructOpt)] #[structopt(name = "bo", about = "An opinionated text editor")] struct Opt { /// Version flag #[structopt(long)] version: bool, /// File name #[structopt(name = "FILE")] file_name: Option<String>, } fn main() { let opt = Opt::from_args(); if opt.version { println!("{}", bo_version()); } else { let term = Box::new(Terminal::default().unwrap()); Editor::new(opt.file_name, term).run(); } }
19.833333
63
0.648109
21241e26f53faa11d17af2a77f5720598a23e19e
894
// impl Deserialize for parquet::data_type::Decimal { // type Schema = DecimalSchema; // type Reader = Reader; // fn placeholder() -> Self::Schema { // // } // fn parse(schema: &Type) -> Result<(String,Self::Schema),ParquetError> { // unimplemented!() // } // fn render(name: &str, schema: &Self::Schema) -> Type { // Type::primitive_type_builder(name, PhysicalType::DOUBLE) // .with_repetition(Repetition::REQUIRED) // .with_logical_type(LogicalType::NONE) // .with_length(-1) // .with_precision(-1) // .with_scale(-1) // .build().unwrap() // Type::PrimitiveType { // basic_info: BasicTypeInfo { // name: String::from(schema), // repetition: Some(Repetition::REQUIRED), // logical_type: LogicalType::DECIMAL, // id: None, // } // physical_type: PhysicalType:: // } // } // struct DecimalSchema { // scale: u32, // precision: u32, // }
27.9375
74
0.621924
648feb1e49296f852017a19b831f2761a272a1bd
2,039
// Copyright (c) Microsoft. All rights reserved. #![deny(rust_2018_idioms)] #![warn(clippy::all, clippy::pedantic)] use serde::{Deserialize, Serialize}; #[derive(Debug, PartialEq, Serialize, Deserialize)] pub struct Config { /// Map of service names to endpoint URIs. /// /// Only configurable in debug builds for the sake of tests. #[serde(default, skip_serializing)] #[cfg_attr(not(debug_assertions), serde(skip_deserializing))] pub endpoints: Endpoints, } /// Map of service names to endpoint URIs. #[derive(Debug, PartialEq, Serialize, Deserialize)] pub struct Endpoints { /// The endpoint that the tpmd service binds to. pub aziot_tpmd: http_common::Connector, } impl Default for Endpoints { fn default() -> Self { Endpoints { aziot_tpmd: http_common::Connector::Unix { socket_path: std::path::Path::new("/run/aziot/tpmd.sock").into(), }, } } } #[cfg(test)] mod tests { #[test] fn parse_config() { let actual = r#""#; let actual: super::Config = toml::from_str(actual).unwrap(); assert_eq!( actual, super::Config { endpoints: super::Endpoints { aziot_tpmd: http_common::Connector::Unix { socket_path: std::path::Path::new("/run/aziot/tpmd.sock").into() }, }, } ); } #[cfg(debug_assertions)] #[test] fn parse_config_with_explicit_endpoints() { let actual = r#" [endpoints] aziot_tpmd = "unix:///custom/path/tpmd.sock" "#; let actual: super::Config = toml::from_str(actual).unwrap(); assert_eq!( actual, super::Config { endpoints: super::Endpoints { aziot_tpmd: http_common::Connector::Unix { socket_path: std::path::Path::new("/custom/path/tpmd.sock").into() }, }, } ); } }
27.186667
90
0.551741
9b1a8913822092a002b957a7a97e509500c06a01
19,306
//! Type-checking for the rust-intrinsic and platform-intrinsic //! intrinsics that the compiler exposes. use rustc::traits::{ObligationCause, ObligationCauseCode}; use rustc::ty::{self, TyCtxt, Ty}; use rustc::ty::subst::Subst; use crate::require_same_types; use rustc_target::spec::abi::Abi; use syntax::symbol::InternedString; use rustc::hir; use std::iter; fn equate_intrinsic_type<'tcx>( tcx: TyCtxt<'tcx>, it: &hir::ForeignItem, n_tps: usize, abi: Abi, safety: hir::Unsafety, inputs: Vec<Ty<'tcx>>, output: Ty<'tcx>, ) { let def_id = tcx.hir().local_def_id_from_hir_id(it.hir_id); match it.node { hir::ForeignItemKind::Fn(..) => {} _ => { struct_span_err!(tcx.sess, it.span, E0622, "intrinsic must be a function") .span_label(it.span, "expected a function") .emit(); return; } } let i_n_tps = tcx.generics_of(def_id).own_counts().types; if i_n_tps != n_tps { let span = match it.node { hir::ForeignItemKind::Fn(_, _, ref generics) => generics.span, _ => bug!() }; struct_span_err!(tcx.sess, span, E0094, "intrinsic has wrong number of type \ parameters: found {}, expected {}", i_n_tps, n_tps) .span_label(span, format!("expected {} type parameter", n_tps)) .emit(); return; } let fty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig( inputs.into_iter(), output, false, safety, abi ))); let cause = ObligationCause::new(it.span, it.hir_id, ObligationCauseCode::IntrinsicType); require_same_types(tcx, &cause, tcx.mk_fn_ptr(tcx.fn_sig(def_id)), fty); } /// Returns `true` if the given intrinsic is unsafe to call or not. pub fn intrisic_operation_unsafety(intrinsic: &str) -> hir::Unsafety { match intrinsic { "size_of" | "min_align_of" | "needs_drop" | "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" | "overflowing_add" | "overflowing_sub" | "overflowing_mul" | "saturating_add" | "saturating_sub" | "rotate_left" | "rotate_right" | "ctpop" | "ctlz" | "cttz" | "bswap" | "bitreverse" | "minnumf32" | "minnumf64" | "maxnumf32" | "maxnumf64" => hir::Unsafety::Normal, _ => hir::Unsafety::Unsafe, } } /// Remember to add all intrinsics here, in librustc_codegen_llvm/intrinsic.rs, /// and in libcore/intrinsics.rs pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem) { let param = |n| tcx.mk_ty_param(n, InternedString::intern(&format!("P{}", n))); let name = it.ident.as_str(); let mk_va_list_ty = |mutbl| { tcx.lang_items().va_list().map(|did| { let region = tcx.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BrAnon(0))); let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv); let va_list_ty = tcx.type_of(did).subst(tcx, &[region.into()]); (tcx.mk_ref(tcx.mk_region(env_region), ty::TypeAndMut { ty: va_list_ty, mutbl }), va_list_ty) }) }; let (n_tps, inputs, output, unsafety) = if name.starts_with("atomic_") { let split : Vec<&str> = name.split('_').collect(); assert!(split.len() >= 2, "Atomic intrinsic in an incorrect format"); //We only care about the operation here let (n_tps, inputs, output) = match split[1] { "cxchg" | "cxchgweak" => (1, vec![tcx.mk_mut_ptr(param(0)), param(0), param(0)], tcx.intern_tup(&[param(0), tcx.types.bool])), "load" => (1, vec![tcx.mk_imm_ptr(param(0))], param(0)), "store" => (1, vec![tcx.mk_mut_ptr(param(0)), param(0)], tcx.mk_unit()), "xchg" | "xadd" | "xsub" | "and" | "nand" | "or" | "xor" | "max" | "min" | "umax" | "umin" => { (1, vec![tcx.mk_mut_ptr(param(0)), param(0)], param(0)) } "fence" | "singlethreadfence" => { (0, Vec::new(), tcx.mk_unit()) } op => { struct_span_err!(tcx.sess, it.span, E0092, "unrecognized atomic operation function: `{}`", op) .span_label(it.span, "unrecognized atomic operation") .emit(); return; } }; (n_tps, inputs, output, hir::Unsafety::Unsafe) } else if &name[..] == "abort" || &name[..] == "unreachable" { (0, Vec::new(), tcx.types.never, hir::Unsafety::Unsafe) } else { let unsafety = intrisic_operation_unsafety(&name[..]); let (n_tps, inputs, output) = match &name[..] { "breakpoint" => (0, Vec::new(), tcx.mk_unit()), "size_of" | "pref_align_of" | "min_align_of" => (1, Vec::new(), tcx.types.usize), "size_of_val" | "min_align_of_val" => { (1, vec![ tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BrAnon(0))), param(0)) ], tcx.types.usize) } "rustc_peek" => (1, vec![param(0)], param(0)), "panic_if_uninhabited" => (1, Vec::new(), tcx.mk_unit()), "init" => (1, Vec::new(), param(0)), "uninit" => (1, Vec::new(), param(0)), "forget" => (1, vec![param(0)], tcx.mk_unit()), "transmute" => (2, vec![ param(0) ], param(1)), "move_val_init" => { (1, vec![ tcx.mk_mut_ptr(param(0)), param(0) ], tcx.mk_unit()) } "prefetch_read_data" | "prefetch_write_data" | "prefetch_read_instruction" | "prefetch_write_instruction" => { (1, vec![tcx.mk_ptr(ty::TypeAndMut { ty: param(0), mutbl: hir::MutImmutable }), tcx.types.i32], tcx.mk_unit()) } "drop_in_place" => { (1, vec![tcx.mk_mut_ptr(param(0))], tcx.mk_unit()) } "needs_drop" => (1, Vec::new(), tcx.types.bool), "type_name" => (1, Vec::new(), tcx.mk_static_str()), "type_id" => (1, Vec::new(), tcx.types.u64), "offset" | "arith_offset" => { (1, vec![ tcx.mk_ptr(ty::TypeAndMut { ty: param(0), mutbl: hir::MutImmutable }), tcx.types.isize ], tcx.mk_ptr(ty::TypeAndMut { ty: param(0), mutbl: hir::MutImmutable })) } "copy" | "copy_nonoverlapping" => { (1, vec![ tcx.mk_ptr(ty::TypeAndMut { ty: param(0), mutbl: hir::MutImmutable }), tcx.mk_ptr(ty::TypeAndMut { ty: param(0), mutbl: hir::MutMutable }), tcx.types.usize, ], tcx.mk_unit()) } "volatile_copy_memory" | "volatile_copy_nonoverlapping_memory" => { (1, vec![ tcx.mk_ptr(ty::TypeAndMut { ty: param(0), mutbl: hir::MutMutable }), tcx.mk_ptr(ty::TypeAndMut { ty: param(0), mutbl: hir::MutImmutable }), tcx.types.usize, ], tcx.mk_unit()) } "write_bytes" | "volatile_set_memory" => { (1, vec![ tcx.mk_ptr(ty::TypeAndMut { ty: param(0), mutbl: hir::MutMutable }), tcx.types.u8, tcx.types.usize, ], tcx.mk_unit()) } "sqrtf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), "sqrtf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), "powif32" => { (0, vec![ tcx.types.f32, tcx.types.i32 ], tcx.types.f32) } "powif64" => { (0, vec![ tcx.types.f64, tcx.types.i32 ], tcx.types.f64) } "sinf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), "sinf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), "cosf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), "cosf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), "powf32" => { (0, vec![ tcx.types.f32, tcx.types.f32 ], tcx.types.f32) } "powf64" => { (0, vec![ tcx.types.f64, tcx.types.f64 ], tcx.types.f64) } "expf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), "expf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), "exp2f32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), "exp2f64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), "logf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), "logf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), "log10f32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), "log10f64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), "log2f32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), "log2f64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), "fmaf32" => { (0, vec![ tcx.types.f32, tcx.types.f32, tcx.types.f32 ], tcx.types.f32) } "fmaf64" => { (0, vec![ tcx.types.f64, tcx.types.f64, tcx.types.f64 ], tcx.types.f64) } "fabsf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), "fabsf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), "minnumf32" => (0, vec![ tcx.types.f32, tcx.types.f32 ], tcx.types.f32), "minnumf64" => (0, vec![ tcx.types.f64, tcx.types.f64 ], tcx.types.f64), "maxnumf32" => (0, vec![ tcx.types.f32, tcx.types.f32 ], tcx.types.f32), "maxnumf64" => (0, vec![ tcx.types.f64, tcx.types.f64 ], tcx.types.f64), "copysignf32" => (0, vec![ tcx.types.f32, tcx.types.f32 ], tcx.types.f32), "copysignf64" => (0, vec![ tcx.types.f64, tcx.types.f64 ], tcx.types.f64), "floorf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), "floorf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), "ceilf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), "ceilf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), "truncf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), "truncf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), "rintf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), "rintf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), "nearbyintf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), "nearbyintf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), "roundf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32), "roundf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64), "volatile_load" | "unaligned_volatile_load" => (1, vec![ tcx.mk_imm_ptr(param(0)) ], param(0)), "volatile_store" | "unaligned_volatile_store" => (1, vec![ tcx.mk_mut_ptr(param(0)), param(0) ], tcx.mk_unit()), "ctpop" | "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "bswap" | "bitreverse" => (1, vec![param(0)], param(0)), "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => (1, vec![param(0), param(0)], tcx.intern_tup(&[param(0), tcx.types.bool])), "unchecked_div" | "unchecked_rem" | "exact_div" => (1, vec![param(0), param(0)], param(0)), "unchecked_shl" | "unchecked_shr" | "rotate_left" | "rotate_right" => (1, vec![param(0), param(0)], param(0)), "unchecked_add" | "unchecked_sub" | "unchecked_mul" => (1, vec![param(0), param(0)], param(0)), "overflowing_add" | "overflowing_sub" | "overflowing_mul" => (1, vec![param(0), param(0)], param(0)), "saturating_add" | "saturating_sub" => (1, vec![param(0), param(0)], param(0)), "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => (1, vec![param(0), param(0)], param(0)), "assume" => (0, vec![tcx.types.bool], tcx.mk_unit()), "likely" => (0, vec![tcx.types.bool], tcx.types.bool), "unlikely" => (0, vec![tcx.types.bool], tcx.types.bool), "discriminant_value" => (1, vec![ tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BrAnon(0))), param(0))], tcx.types.u64), "try" => { let mut_u8 = tcx.mk_mut_ptr(tcx.types.u8); let fn_ty = ty::Binder::bind(tcx.mk_fn_sig( iter::once(mut_u8), tcx.mk_unit(), false, hir::Unsafety::Normal, Abi::Rust, )); (0, vec![tcx.mk_fn_ptr(fn_ty), mut_u8, mut_u8], tcx.types.i32) } "va_start" | "va_end" => { match mk_va_list_ty(hir::MutMutable) { Some((va_list_ref_ty, _)) => (0, vec![va_list_ref_ty], tcx.mk_unit()), None => bug!("`va_list` language item needed for C-variadic intrinsics") } } "va_copy" => { match mk_va_list_ty(hir::MutImmutable) { Some((va_list_ref_ty, va_list_ty)) => { let va_list_ptr_ty = tcx.mk_mut_ptr(va_list_ty); (0, vec![va_list_ptr_ty, va_list_ref_ty], tcx.mk_unit()) } None => bug!("`va_list` language item needed for C-variadic intrinsics") } } "va_arg" => { match mk_va_list_ty(hir::MutMutable) { Some((va_list_ref_ty, _)) => (1, vec![va_list_ref_ty], param(0)), None => bug!("`va_list` language item needed for C-variadic intrinsics") } } "nontemporal_store" => { (1, vec![ tcx.mk_mut_ptr(param(0)), param(0) ], tcx.mk_unit()) } ref other => { struct_span_err!(tcx.sess, it.span, E0093, "unrecognized intrinsic function: `{}`", *other) .span_label(it.span, "unrecognized intrinsic") .emit(); return; } }; (n_tps, inputs, output, unsafety) }; equate_intrinsic_type(tcx, it, n_tps, Abi::RustIntrinsic, unsafety, inputs, output) } /// Type-check `extern "platform-intrinsic" { ... }` functions. pub fn check_platform_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem) { let param = |n| { let name = InternedString::intern(&format!("P{}", n)); tcx.mk_ty_param(n, name) }; let name = it.ident.as_str(); let (n_tps, inputs, output) = match &*name { "simd_eq" | "simd_ne" | "simd_lt" | "simd_le" | "simd_gt" | "simd_ge" => { (2, vec![param(0), param(0)], param(1)) } "simd_add" | "simd_sub" | "simd_mul" | "simd_rem" | "simd_div" | "simd_shl" | "simd_shr" | "simd_and" | "simd_or" | "simd_xor" | "simd_fmin" | "simd_fmax" | "simd_fpow" | "simd_saturating_add" | "simd_saturating_sub" => { (1, vec![param(0), param(0)], param(0)) } "simd_fsqrt" | "simd_fsin" | "simd_fcos" | "simd_fexp" | "simd_fexp2" | "simd_flog2" | "simd_flog10" | "simd_flog" | "simd_fabs" | "simd_floor" | "simd_ceil" => { (1, vec![param(0)], param(0)) } "simd_fpowi" => { (1, vec![param(0), tcx.types.i32], param(0)) } "simd_fma" => { (1, vec![param(0), param(0), param(0)], param(0)) } "simd_gather" => { (3, vec![param(0), param(1), param(2)], param(0)) } "simd_scatter" => { (3, vec![param(0), param(1), param(2)], tcx.mk_unit()) } "simd_insert" => (2, vec![param(0), tcx.types.u32, param(1)], param(0)), "simd_extract" => (2, vec![param(0), tcx.types.u32], param(1)), "simd_cast" => (2, vec![param(0)], param(1)), "simd_bitmask" => (2, vec![param(0)], param(1)), "simd_select" | "simd_select_bitmask" => (2, vec![param(0), param(1), param(1)], param(1)), "simd_reduce_all" | "simd_reduce_any" => (1, vec![param(0)], tcx.types.bool), "simd_reduce_add_ordered" | "simd_reduce_mul_ordered" => (2, vec![param(0), param(1)], param(1)), "simd_reduce_add_unordered" | "simd_reduce_mul_unordered" | "simd_reduce_and" | "simd_reduce_or" | "simd_reduce_xor" | "simd_reduce_min" | "simd_reduce_max" | "simd_reduce_min_nanless" | "simd_reduce_max_nanless" => (2, vec![param(0)], param(1)), name if name.starts_with("simd_shuffle") => { match name["simd_shuffle".len()..].parse() { Ok(n) => { let params = vec![param(0), param(0), tcx.mk_array(tcx.types.u32, n)]; (2, params, param(1)) } Err(_) => { span_err!(tcx.sess, it.span, E0439, "invalid `simd_shuffle`, needs length: `{}`", name); return } } } _ => { let msg = format!("unrecognized platform-specific intrinsic function: `{}`", name); tcx.sess.span_err(it.span, &msg); return; } }; equate_intrinsic_type(tcx, it, n_tps, Abi::PlatformIntrinsic, hir::Unsafety::Unsafe, inputs, output) }
41.787879
95
0.459702
1e376e91080794c5543c743cdca957e1675a22c3
26,683
// 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. //! This Rust crate allows you to easily and safely serialize/deserialize //! data structures into the byte format specified in [section 3][1] //! of the [Spinel Protocol Documentation][2]. This documentation assumes //! some familiarity with that documentation. The behavior of this crate was //! inspired by the [`spinel_datatype_pack`/`spinel_datatype_unpack`][3] methods //! from [OpenThread][4]. //! //! [1]: https://tools.ietf.org/html/draft-rquattle-spinel-unified-00#section-3 //! [2]: https://tools.ietf.org/html/draft-rquattle-spinel-unified-00 //! [3]: https://github.com/openthread/openthread/blob/5b622e690e6dd441498b57e4cafe034937f43629/src/lib/spinel/spinel.h#L4042..L4111 //! [4]: https://github.com/openthread/openthread/ //! //! # Key Features //! //! * Ability to deserialize to borrowed types (like `&str`) in addition to owned types. //! * Convenient attribute macro (`#[spinel_packed("...")]`) for automatically implementing //! pack/unpack traits on datatypes, including structs with borrowed references and nested //! Spinel data types. //! * Convenient in-line macros (`spinel_read!(...)`/`spinel_write!(...)`) for parsing arbitrary //! Spinel data immediately in place without the need to define new types. //! * All macros check the format strings against the types being serialized/deserialized at //! compile-time, generating compiler errors whenever there is a mismatch. //! //! # Packing/Serialization //! //! Serialization is performed via two traits: //! //! * [`TryPack`] for serializing to the natural Spinel byte format //! for the given type. The key method on the trait is `try_pack()`. //! * [`TryPackAs<MarkerType>`][TryPackAs] for serializing to one of the specific //! Spinel format types. Since this trait is generic, a given type can //! have multiple implementations of this trait for serializing to the //! byte format specified by `MarkerType`. The key method on the trait //! is `try_pack_as()`. //! //! The `TryPack`/`TryPackAs` traits operate on types that implement `std::io::Write`, //! which includes `Vec<u8>` and `&mut&mut[u8]`. //! //! # Unpacking/Deserialization //! //! Deserialization is performed via three traits: //! //! * [`TryUnpack`] for deserializing bytes into an instance of the //! associated type `Self::Unpacked` (which is usually `Self`), inferring //! the byte format from the type. //! This trait supports deserializing to both borrowed types (like `&str`) //! and owned types (like `String`), and thus has a lifetime parameter. //! The key method on the trait is `try_unpack()`. //! * [`TryUnpackAs<MarkerType>`][TryUnpackAs] for deserializing a spinel //! field that is encoded as a `MarkerType` into an instance of the //! associated type `Self::Unpacked` (which is usually `Self`). //! This trait supports deserializing to both borrowed types (like `&str`) //! and owned types (like `String`), and thus has a lifetime parameter. //! The key method on the trait is `try_unpack_as()`. //! * [`TryOwnedUnpack`], which is similar to [`TryUnpack`] except that //! it supports *owned* types only (like `String`). The key method on the //! trait is `try_owned_unpack()`. //! //! The `TryUnpack`/`TryOwnedUnpack` traits operate on byte slices (`&[u8]`) and //! byte slice iterators (`std::slice::Iter<u8>`). //! //! # Supported Primitive Types //! //! This crate supports the following raw Spinel types: //! //! Char | Name | Type | Marker Type (if different) //! -----|-------------|-------------------|------------------- //! `.` | VOID | `()` //! `b` | BOOL | `bool` //! `C` | UINT8 | `u8` //! `c` | INT8 | `i8` //! `S` | UINT16 | `u16` //! `s` | INT16 | `i16` //! `L` | UINT32 | `u32` //! `l` | INT32 | `i32` //! `i` | UINT_PACKED | `u32` | [`SpinelUint`] //! `6` | IPv6ADDR | `std::net::Ipv6Addr` //! `E` | EUI64 | [`EUI64`] //! `e` | EUI48 | [`EUI48`] //! `D` | DATA | `&[u8]`/`Vec<u8>` | `[u8]` //! `d` | DATA_WLEN | `&[u8]`/`Vec<u8>` | [`SpinelDataWlen`] //! `U` | UTF8 | `&str`/`String` | `str` //! //! The Spinel *struct* (`t(...)`) and *array* (`A(...)`) types are not //! directly supported and will result in a compiler error if used //! in a Spinel format string. However, you can emulate the behavior of //! spinel structs by replacing the `t(...)` with a `d` and using another //! Spinel datatype (like one created with the `spinel_packed` attribute) //! instead of `&[u8]` or `Vec<u8>`. //! //! # How Format Strings Work //! //! The macro `spinel_write!(...)` can be used to directly unpack Spinel-encoded //! data into individual fields, with the encoded type being defined by a //! *format string*. This macro will parse the *format string*, associating each //! character in the string with a specific *Marker Type* and field argument. For each //! of the fields in the format, the macro will make a call into //! `TryPackAs<MarkerType>::try_pack_as(...)` for the given field's argument. //! If there is no implementation of `TryPackAs<MarkerType>` for the type of //! the field's argument, a compile-time error is generated. //! //! # Examples //! //! Struct example: //! //! ``` //! use spinel_pack::prelude::*; //! //! #[spinel_packed("CiiLUE")] //! #[derive(Debug, Eq, PartialEq)] //! pub struct SomePackedData<'a> { //! foo: u8, //! bar: u32, //! blah: u32, //! bleh: u32, //! name: &'a str, //! addr: spinel_pack::EUI64, //! } //! ``` //! //! Packing into a new `Vec`: //! //! ``` //! # use spinel_pack::prelude::*; //! # //! # #[spinel_packed("CiiLUE")] //! # #[derive(Debug)] //! # pub struct SomePackedData<'a> { //! # foo: u8, //! # bar: u32, //! # blah: u32, //! # bleh: u32, //! # name: &'a str, //! # addr: spinel_pack::EUI64, //! # } //! # //! # fn main() -> std::io::Result<()> { //! let data = SomePackedData { //! foo: 10, //! bar: 20, //! blah: 30, //! bleh: 40, //! name: "This is a string", //! addr: spinel_pack::EUI64([0,0,0,0,0,0,0,0]), //! }; //! //! let packed: Vec<u8> = data.try_packed()?; //! # let _ = packed; //! # Ok(()) //! # } //! ``` //! //! Packing into an existing array: //! //! ``` //! # use spinel_pack::prelude::*; //! # //! # #[spinel_packed("CiiLUE")] //! # #[derive(Debug)] //! # pub struct SomePackedData<'a> { //! # foo: u8, //! # bar: u32, //! # blah: u32, //! # bleh: u32, //! # name: &'a str, //! # addr: spinel_pack::EUI64, //! # } //! # //! # fn main() -> std::io::Result<()> { //! let data = SomePackedData { //! foo: 10, //! bar: 20, //! blah: 30, //! bleh: 40, //! name: "This is a string", //! addr: spinel_pack::EUI64([0,0,0,0,0,0,0,0]), //! }; //! //! let mut bytes = [0u8; 500]; //! let length = data.try_pack(&mut &mut bytes[..])?; //! # let _ = length; //! # Ok(()) //! # } //! ``` //! //! Unpacking: //! //! ``` //! # use spinel_pack::prelude::*; //! # //! # #[spinel_packed("CiiLUE")] //! # #[derive(Debug)] //! # pub struct SomePackedData<'a> { //! # foo: u8, //! # bar: u32, //! # blah: u32, //! # bleh: u32, //! # name: &'a str, //! # addr: spinel_pack::EUI64, //! # } //! # //! # fn main() -> anyhow::Result<()> { //! let bytes: &[u8] = &[0x01, 0x02, 0x03, 0xef, 0xbe, 0xad, 0xde, 0x31, 0x32, 0x33, 0x00, 0x02, //! 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]; //! //! let data = SomePackedData::try_unpack(&mut bytes.iter())?; //! //! assert_eq!(data.foo, 1); //! assert_eq!(data.bar, 2); //! assert_eq!(data.blah, 3); //! assert_eq!(data.bleh, 0xdeadbeef); //! assert_eq!(data.name, "123"); //! assert_eq!(data.addr, spinel_pack::EUI64([0x02,0xff,0xff,0xff,0xff,0xff,0xff,0xff])); //! # Ok(()) //! # } //! ``` //! //! Spinel packed structs can be nested: //! //! ``` //! # use spinel_pack::prelude::*; //! # //! # #[spinel_packed("CiiLUE")] //! # #[derive(Debug, Eq, PartialEq)] //! # pub struct SomePackedData<'a> { //! # foo: u8, //! # bar: u32, //! # blah: u32, //! # bleh: u32, //! # name: &'a str, //! # addr: spinel_pack::EUI64, //! # } //! # //! #[spinel_packed("idU")] //! #[derive(Debug, Eq, PartialEq)] //! pub struct SomeNestedData<'a> { //! foo: u32, //! test_struct_1: SomePackedData<'a>, //! name: String, //! } //! ``` //! //! Each field of a struct must have an associated format type indicator: //! //! ```compile_fail //! # use spinel_pack::prelude::*; //! #[spinel_packed("i")] //! #[derive(Debug, Eq, PartialEq)] //! pub struct SomePackedData { //! foo: u32, //! data: &'a [u8], // Compiler error, no format type //! } //! ``` //! //! Likewise, each format type indicator must have a field: //! //! ```compile_fail //! # use spinel_pack::prelude::*; //! #[spinel_packed("id")] //! #[derive(Debug, Eq, PartialEq)] //! pub struct SomePackedData { //! foo: u32, //! } // Compiler error, missing field for 'd' //! ``` //! //! ```compile_fail //! #use spinel_pack::prelude::*; //! #[spinel_packed("id")] //! #[derive(Debug, Eq, PartialEq)] //! pub struct SomePackedData; // Compiler error, no fields at all //! ``` //! //! Using `spinel_write!()`: //! //! ``` //! # use spinel_pack::prelude::*; //! let mut target: Vec<u8> = vec![]; //! //! spinel_write!(&mut target, "isc", 1, 2, 3) //! .expect("spinel_write failed"); //! //! assert_eq!(target, vec![1u8,2u8,0u8,3u8]); //! ``` //! //! Using `spinel_read!()`: //! //! ``` //! # use spinel_pack::prelude::*; //! // The data to parse. //! let bytes: &[u8] = &[ //! 0x01, 0x02, 0x83, 0x03, 0xef, 0xbe, 0xad, 0xde, //! 0x31, 0x32, 0x33, 0x00, 0x02, 0xf1, 0xf2, 0xf3, //! 0xf4, 0xf5, 0xf6, 0xf7, //! ]; //! //! // The variables that we will place //! // the parsed values into. Note that //! // currently these need to be initialized //! // before they can be used with `spinel_read`. //! let mut foo: u8 = 0; //! let mut bar: u32 = 0; //! let mut blah: u32 = 0; //! let mut bleh: u32 = 0; //! let mut name: String = Default::default(); //! let mut addr: spinel_pack::EUI64 = Default::default(); //! //! // Parse the data. //! spinel_read!(&mut bytes.iter(), "CiiLUE", foo, bar, blah, bleh, name, addr) //! .expect("spinel_read failed"); //! //! // Verify that the variables match //! // the values we expect. //! assert_eq!(foo, 1); //! assert_eq!(bar, 2); //! assert_eq!(blah, 387); //! assert_eq!(bleh, 0xdeadbeef); //! assert_eq!(name, "123"); //! assert_eq!(addr, spinel_pack::EUI64([0x02, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7])); //! ``` #![warn(missing_docs)] #![warn(missing_debug_implementations)] #![warn(rust_2018_idioms)] #![warn(clippy::all)] // TODO(fxbug.dev/49842): Remove #![allow(elided_lifetimes_in_paths)] #![allow(unused_mut)] mod eui; mod primitives; use proc_macro_hack::proc_macro_hack; use std::fmt::Debug; use std::io; pub use eui::{EUI48, EUI64}; /// Attribute macro which takes a Spinel format string as an argument /// and automatically defines the `TryPack`/`TryUnpack` traits for the /// given struct. /// /// The full list of traits implemented by this macro include: /// /// * `TryPack`/`TryUnpack` /// * `TryPackAs<SpinelDataWlen>`/`TryUnpackAs<SpinelDataWlen>` /// * `TryPackAs<[u8]>`/`TryUnpackAs<[u8]>` /// /// Additionally, if no lifetimes are specified, the following trait is /// also implemented: /// /// * `TryOwnedUnpack` /// pub use spinel_pack_macros::spinel_packed; /// In-line proc macro for writing spinel-formatted data fields to a type /// implementing `std::io::Write`. /// /// ## Example ## /// /// ``` /// # use spinel_pack::prelude::*; /// let mut target: Vec<u8> = vec![]; /// /// spinel_write!(&mut target, "isc", 1, 2, 3) /// .expect("spinel_write failed"); /// /// assert_eq!(target, vec![1u8,2u8,0u8,3u8]); /// ``` #[proc_macro_hack] pub use spinel_pack_macros::spinel_write; /// In-line proc macro for determining the written length of spinel-formatted /// data fields. /// /// ## Example ## /// /// ``` /// # use spinel_pack::prelude::*; /// let len = spinel_write_len!("isc", 1, 2, 3) /// .expect("spinel_write_len failed"); /// /// assert_eq!(len, 4); /// ``` #[proc_macro_hack] pub use spinel_pack_macros::spinel_write_len; /// In-line proc macro for parsing spinel-formatted data fields from /// a byte slice iterator. /// /// ## Example ## /// /// ``` /// # use spinel_pack::prelude::*; /// // The data to parse. /// let bytes: &[u8] = &[ /// 0x01, 0x02, 0x83, 0x03, 0xef, 0xbe, 0xad, 0xde, /// 0x31, 0x32, 0x33, 0x00, 0x02, 0xf1, 0xf2, 0xf3, /// 0xf4, 0xf5, 0xf6, 0xf7, /// ]; /// /// // The variables that we will place /// // the parsed values into. Note that /// // currently these need to be initialized /// // before they can be used with `spinel_read`. /// let mut foo: u8 = 0; /// let mut bar: u32 = 0; /// let mut blah: u32 = 0; /// let mut bleh: u32 = 0; /// let mut name: String = Default::default(); /// let mut addr: spinel_pack::EUI64 = Default::default(); /// /// // Parse the data. /// spinel_read!(&mut bytes.iter(), "CiiLUE", foo, bar, blah, bleh, name, addr) /// .expect("spinel_read failed"); /// /// // Verify that the variables match /// // the values we expect. /// assert_eq!(foo, 1); /// assert_eq!(bar, 2); /// assert_eq!(blah, 387); /// assert_eq!(bleh, 0xdeadbeef); /// assert_eq!(name, "123"); /// assert_eq!(addr, spinel_pack::EUI64([0x02, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7])); /// ``` #[proc_macro_hack] pub use spinel_pack_macros::spinel_read; /// Error type for unpacking operations. /// /// These errors end up being wrapped in an `anyhow::Error` type. #[derive(Debug, Eq, PartialEq, Hash, thiserror::Error)] pub enum UnpackingError { /// A length field in the data overflowed the length of its container. #[error("InvalidInternalLength")] InvalidInternalLength, /// One or more of the encoded fields contained an invalid value. #[error("InvalidValue")] InvalidValue, /// The text string was not zero terminated. #[error("UnterminatedString")] UnterminatedString, } /// Marker trait for types which always serialize to the same length. pub trait SpinelFixedLen { /// The length of the type, in bytes. const FIXED_LEN: usize; } /// Trait implemented by data types that support being serialized /// to a spinel-based byte encoding. pub trait TryPack { /// Uses Spinel encoding to serialize to a given `std::io::Write` reference. fn try_pack<T: std::io::Write + ?Sized>(&self, buffer: &mut T) -> io::Result<usize>; /// Calculates how many bytes this type will use when serialized. fn pack_len(&self) -> io::Result<usize>; /// Convenience method which serializes to a new `Vec<u8>`. fn try_packed(&self) -> io::Result<Vec<u8>> { let mut packed = Vec::with_capacity(self.pack_len()?); self.try_pack(&mut packed)?; Ok(packed) } } /// Trait implemented by data types that support being serialized /// to a specific spinel-based byte encoding, based on the marker type. /// /// The generic parameter `Marker` is effectiely a part of the name of the /// trait and is not used directly by the trait. Types may implement more than /// one instance of this trait, each with a different marker type. /// For example, structs that use the `spinel_packed` attribute macro /// will implement both `TryPackAs<[u8]>` and `TryPackAs<SpinelDataWlen>` /// for handling the `D` and `d` Spinel field formats respectively when /// serializing. pub trait TryPackAs<Marker: ?Sized> { /// Uses Spinel encoding to serialize to a given `std::io::Write` reference as the /// Spinel type identified by `Marker`. fn try_pack_as<T: std::io::Write + ?Sized>(&self, buffer: &mut T) -> io::Result<usize>; /// Calculates how many bytes this type will use when serialized. fn pack_as_len(&self) -> io::Result<usize>; } /// Trait for unpacking a spinel-encoded buffer to a specific type. /// /// Similar to `TryOwnedUnpack`, except that it can also unpack into borrowed /// types, like `&[u8]` and `&str`. pub trait TryUnpack<'a> { /// The type of the unpacked result. This can be the same as `Self`, /// but in some cases it can be different. This is because `Self` is /// a *marker type*, and may not even be `Sized`. For example, if `Self` is /// `SpinelUint`, then `Unpacked` would be `u32` (because `SpinelUint` is just /// a marker trait indicating a variably-sized unsigned integer). type Unpacked: Send + Sized + Debug; /// Attempts to decode the data at the given iterator into an instance /// of `Self`. fn try_unpack(iter: &mut std::slice::Iter<'a, u8>) -> anyhow::Result<Self::Unpacked>; /// Convenience method for unpacking directly from a borrowed slice. fn try_unpack_from_slice(slice: &'a [u8]) -> anyhow::Result<Self::Unpacked> { Self::try_unpack(&mut slice.iter()) } } /// Trait for unpacking only into owned types, like `Vec<u8>` or `String`. /// /// Similar to `TryUnpack`, except that this trait cannot unpack into borrowed /// types like `&[u8]` or `&str`. /// /// If you have a `TryOwnedUnpack` implementation, you can automatically implement /// `TryUnpack` using the `impl_try_unpack_for_owned!` macro. pub trait TryOwnedUnpack: Send { /// The type of the unpacked result. This can be the same as `Self`, /// but in some cases it can be different. This is because `Self` is /// a *marker type*, and may not even be `Sized`. For example, if `Self` is /// `SpinelUint`, then `Unpacked` would be `u32` (because `SpinelUint` is just /// a marker trait indicating a variably-sized unsigned integer). type Unpacked: Send + Sized + Debug; /// Attempts to decode the data at the given iterator into an instance /// of `Self`, where `Self` must be an "owned" type. fn try_owned_unpack(iter: &mut std::slice::Iter<'_, u8>) -> anyhow::Result<Self::Unpacked>; /// Convenience method for unpacking directly from a borrowed slice. fn try_owned_unpack_from_slice(slice: &'_ [u8]) -> anyhow::Result<Self::Unpacked> { Self::try_owned_unpack(&mut slice.iter()) } } /// Trait for unpacking a spinel-encoded buffer to a specific type when the field /// type is known. /// /// The generic parameter `Marker` is effectiely a part of the name of the /// trait and is not used directly by the trait. Types may implement more than /// one instance of this trait, each with a different marker type. /// For example, structs that use the `spinel_packed` attribute macro /// will implement both `TryUnpackAs<[u8]>` and `TryUnpackAs<SpinelDataWlen>` /// for handling the `D` and `d` Spinel field formats respectively when /// deserializing. pub trait TryUnpackAs<'a, Marker: ?Sized>: Sized { /// Attempts to decode the data (with a format determined by `Marker`) at the given /// iterator into an instance of `Self`. fn try_unpack_as(iter: &mut std::slice::Iter<'a, u8>) -> anyhow::Result<Self>; /// Convenience method for unpacking directly from a borrowed slice. fn try_unpack_as_from_slice(slice: &'a [u8]) -> anyhow::Result<Self> { Self::try_unpack_as(&mut slice.iter()) } } /// Provides an automatic implementation of [`TryUnpack`] when /// wrapped around an implementation of [`TryOwnedUnpack`]. /// /// ## Example ## /// /// The following usage will create an implementation of the `TryUnpack` /// trait for `Vec<u8>` that uses the given implementation of `TryOwnedUnpack`: /// /// ```no_compile /// # use spinel_pack::{TryOwnedUnpack, prelude::*}; /// impl_try_unpack_for_owned! { /// impl TryOwnedUnpack for Vec<u8> { /// type Unpacked = Self; /// fn try_owned_unpack(iter: &mut std::slice::Iter<'_, u8>) -> anyhow::Result<Self::Unpacked> { /// Ok(<&[u8]>::try_unpack(iter)?.to_owned()) /// } /// } /// } /// ``` #[macro_export] macro_rules! impl_try_unpack_for_owned( (impl TryOwnedUnpack for $t:ty { $($rest:tt)* }) => { impl_try_unpack_for_owned!($t); impl TryOwnedUnpack for $t { $($rest)* } }; ($t:ty) => { impl<'a> TryUnpack<'a> for $t { type Unpacked = <$t as TryOwnedUnpack>::Unpacked; fn try_unpack(iter: &mut std::slice::Iter<'a, u8>) -> anyhow::Result<Self::Unpacked> { <$t as TryOwnedUnpack>::try_owned_unpack(iter) } } }; ); /// Marker type used to specify integers encoded with Spinel's variable-length unsigned /// integer encoding. /// /// This type is necessary because `u32` is defined to mean a fixed-length /// encoding, whereas this type can be encoded with a variable length. /// /// This type has no size and is used only with the [`TryPackAs`]/[`TryUnpackAs`] traits /// and in the base type for [`TryUnpack`]/[`TryOwnedUnpack`]. #[derive(Debug)] pub enum SpinelUint {} /// Marker type used to specify data fields that are prepended with its length. /// /// This type is necessary because `[u8]` is already defined to assume the /// remaining length of the buffer. /// /// This type has no size and is used only with the [`TryPackAs`]/[`TryUnpackAs`] traits /// and in the base type for [`TryUnpack`]/[`TryOwnedUnpack`]. #[derive(Debug)] pub enum SpinelDataWlen {} /// Prelude module intended for blanket inclusion to make the crate /// easier to use. /// /// ``` /// # #[allow(unused)] /// use spinel_pack::prelude::*; /// ``` pub mod prelude { pub use super::TryOwnedUnpack as _; pub use super::TryPack as _; pub use super::TryPackAs as _; pub use super::TryUnpack as _; pub use super::TryUnpackAs as _; pub use impl_try_unpack_for_owned; pub use spinel_pack_macros::spinel_packed; pub use spinel_read; pub use spinel_write; pub use spinel_write_len; } #[cfg(test)] use crate as spinel_pack; #[cfg(test)] mod tests { use super::*; #[spinel_packed("CiiLUE")] #[derive(Debug, Eq, PartialEq)] pub struct TestStruct1<'a> { foo: u8, bar: u32, blah: u32, bleh: u32, name: &'a str, addr: spinel_pack::EUI64, } #[test] fn test_spinel_write_1() { let bytes: &[u8] = &[ 0x01, 0x02, 0x83, 0x03, 0xef, 0xbe, 0xad, 0xde, 0x31, 0x32, 0x33, 0x00, 0x02, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, ]; let mut target: Vec<u8> = vec![]; let _x = spinel_write!( &mut target, "CiiLUE", 1, 2, 387, 0xdeadbeef, "123", spinel_pack::EUI64([0x02, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7]) ) .unwrap(); assert_eq!(bytes, target.as_slice()); } #[test] fn test_spinel_read_1() { let bytes: &[u8] = &[ 0x01, 0x02, 0x83, 0x03, 0xef, 0xbe, 0xad, 0xde, 0x31, 0x32, 0x33, 0x00, 0x02, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, ]; let mut foo: u8 = 0; let mut bar: u32 = 0; let mut blah: u32 = 0; let mut bleh: u32 = 0; let mut name: String = Default::default(); let mut addr: EUI64 = Default::default(); spinel_read!(&mut bytes.iter(), "CiiLUE", foo, bar, blah, bleh, name, addr).unwrap(); assert_eq!(foo, 1); assert_eq!(bar, 2); assert_eq!(blah, 387); assert_eq!(bleh, 0xdeadbeef); assert_eq!(name, "123"); assert_eq!(addr, spinel_pack::EUI64([0x02, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7])); } #[test] fn test_struct_1() { let bytes: &[u8] = &[ 0x01, 0x02, 0x83, 0x03, 0xef, 0xbe, 0xad, 0xde, 0x31, 0x32, 0x33, 0x00, 0x02, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, ]; let data = TestStruct1::try_unpack(&mut bytes.iter()).expect("unpack failed"); assert_eq!(data.foo, 1); assert_eq!(data.bar, 2); assert_eq!(data.blah, 387); assert_eq!(data.bleh, 0xdeadbeef); assert_eq!(data.name, "123"); assert_eq!(data.addr, spinel_pack::EUI64([0x02, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7])); } #[spinel_packed("idU")] #[derive(Debug, Eq, PartialEq)] pub struct TestStruct2<'a> { foo: u32, test_struct_1: TestStruct1<'a>, name: String, } #[test] fn test_struct_2() { let struct_2 = TestStruct2 { foo: 31337, test_struct_1: TestStruct1 { foo: 100, bar: 200, blah: 300, bleh: 400, name: "Test Struct 1", addr: spinel_pack::EUI64([0x02, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), }, name: "Test Struct 2".to_string(), }; let packed = struct_2.try_packed().unwrap(); println!("packed: {:?}", packed); let unpacked = TestStruct2::try_unpack(&mut packed.iter()).unwrap(); assert_eq!(struct_2, unpacked); } #[spinel_packed("idU")] #[derive(Debug, Eq, PartialEq)] pub struct TestStruct3<'a>(pub u32, pub TestStruct1<'a>, pub String); #[test] fn test_struct_3() { let struct_3 = TestStruct3( 31337, TestStruct1 { foo: 100, bar: 200, blah: 300, bleh: 400, name: "Test Struct 1", addr: spinel_pack::EUI64([0x02, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), }, "Test Struct 2".to_string(), ); let packed = struct_3.try_packed().unwrap(); println!("packed: {:?}", packed); let unpacked = TestStruct3::try_unpack(&mut packed.iter()).unwrap(); assert_eq!(struct_3, unpacked); } #[spinel_packed("bCcSsLlXxidD")] #[derive(Debug, Eq, PartialEq)] pub struct TestStruct4(bool, u8, i8, u16, i16, u32, i32, u64, i64, u32, Vec<u8>, Vec<u8>); #[test] fn test_struct_4() { let struct_4 = TestStruct4( false, 123, -123, 1337, -1337, 41337, -41337, 123123123123, -123123123123, 31337, vec![0xde, 0xad, 0xbe, 0xef], vec![0xba, 0xdc, 0x0f, 0xfe], ); let packed = struct_4.try_packed().unwrap(); println!("packed: {:?}", packed); let unpacked = TestStruct4::try_unpack(&mut packed.iter()).unwrap(); assert_eq!(struct_4, unpacked); } }
32.982695
132
0.602668
1dda129a232824bf458977b592be6707c271eb55
963
// This file is part of bearssl-sys. 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/bearssl-sys/master/COPYRIGHT. No part of bearssl-sys, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2016 The developers of bearssl-sys. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/bearssl-sys/master/COPYRIGHT. extern "C" { pub fn br_md5_init(ctx: *mut br_md5_context); pub fn br_md5_out(ctx: *const br_md5_context, out: *mut c_void); pub fn br_md5_set_state(ctx: *mut br_md5_context, stb: *const c_void, count: u64); pub fn br_md5_state(ctx: *const br_md5_context, out: *mut c_void) -> u64; pub fn br_md5_update(ctx: *mut br_md5_context, data: *const c_void, len: usize); }
74.076923
388
0.775701
23b146868448583a8fc27ab00fea6cdc7c73d0b3
2,028
use atomic::Atomic; use once_cell::sync::{Lazy, OnceCell}; use std::ffi::c_void; use std::{ path::PathBuf, sync::{ atomic::{AtomicBool, AtomicPtr}, Arc, Mutex, }, }; // ---------------- Configs ---------------- // pub static HOME_DIR: Lazy<PathBuf> = Lazy::new(|| home::home_dir().expect("Couldn't get your home directory!")); pub static SAUTORUN_DIR: Lazy<PathBuf> = Lazy::new(|| HOME_DIR.join("sautorun-rs")); #[cfg(feature = "logging")] pub static SAUTORUN_LOG_DIR: Lazy<PathBuf> = Lazy::new(|| SAUTORUN_DIR.join("logs")); pub static SAUTORUN_SCRIPT_DIR: Lazy<PathBuf> = Lazy::new(|| SAUTORUN_DIR.join("scripts")); // This location is run right before autorun. pub static AUTORUN_SCRIPT_PATH: Lazy<PathBuf> = Lazy::new(|| (*SAUTORUN_DIR).join("autorun.lua")); // Basically ROC, whenever a lua script is ran, run this and pass the code. If it returns true or nil, run the code, else don't pub static HOOK_SCRIPT_PATH: Lazy<PathBuf> = Lazy::new(|| (*SAUTORUN_DIR).join("hook.lua")); // ---------------- Configs ---------------- // // No more static mut! 🥳 // AtomicPtr automatically attaches *mut to the type given. That's why we give CVoid instead of LuaState, because we'll end up with *mut CVoid aka LuaState pub static CLIENT_STATE: AtomicPtr<c_void> = AtomicPtr::new(std::ptr::null_mut()); // Not using AtomicPtr::default() because it isn't a static function pub static CURRENT_SERVER_IP: Atomic<&'static str> = Atomic::new("unknown_ip"); // Using Atomic crate because there is no official way to get an atomic str / string. pub static HAS_AUTORAN: AtomicBool = AtomicBool::new(false); // Whether an autorun script has been run and detected already. pub static MENU_STATE: OnceCell<AtomicPtr<c_void>> = OnceCell::new(); type LuaScript = Vec<(bool, String)>; // Scripts waiting to be ran in painttraverse pub static LUA_SCRIPTS: Lazy<Arc<Mutex<LuaScript>>> = Lazy::new(|| Arc::new(Mutex::new(Vec::new()))); pub type Realm = bool; pub const REALM_MENU: Realm = true; pub const REALM_CLIENT: Realm = false;
45.066667
165
0.696746
bfbf171c311eb1798b8488671d474c2627e2d1da
983
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. #![cfg_attr(feature = "strict", deny(warnings))] #![feature(allocator_api)] #![feature(alloc_layout_extra)] #![feature(const_panic, const_alloc_layout)] #![feature(const_mut_refs, const_type_name)] #![feature(generators, generator_trait)] #![feature(new_uninit)] #![feature(maybe_uninit_uninit_array, maybe_uninit_extra, maybe_uninit_ref)] #![feature(never_type)] #![feature(raw)] #![feature(try_blocks)] #![deny(clippy::all)] #![recursion_limit = "512"] #![feature(test)] #![feature(min_type_alias_impl_trait)] #[macro_use] extern crate num_derive; #[macro_use] extern crate log; #[macro_use] extern crate derive_more; pub mod collections; pub mod engine; pub mod fail; pub mod file_table; mod futures_utility; pub mod interop; pub mod libos; pub mod logging; pub mod operations; pub mod options; pub mod protocols; pub mod runtime; pub mod scheduler; pub mod sync; pub mod test_helpers; pub mod timer;
22.340909
76
0.756867
79f558034e4814766c1d41b027db4c36aea50576
930
use fltk::*; fn main() { let app = app::App::default().with_scheme(app::Scheme::Gtk); let mut win = window::Window::new(100, 100, 400, 300, ""); let mut but = button::Button::new(160, 200, 80, 40, "Click"); win.end(); win.show(); but.set_callback2(|widget| { let mut printer = printer::Printer::default(); if printer.begin_job(1).is_ok() { printer.begin_page(); let (width, height) = printer.printable_rect(); draw::set_draw_color(Color::Black); draw::set_line_style(draw::LineStyle::Solid, 2); draw::draw_rect(0, 0, width, height); draw::set_font(Font::Courier, 12); printer.set_origin(width / 2, height / 2); printer.print_widget(widget, -widget.width() / 2, -widget.height() / 2); printer.end_page(); printer.end_job(); } }); app.run().unwrap(); }
33.214286
84
0.550538
91ce9f9ebcd9325b75c9fdcec6894f3c8ffde465
15,071
use crate::base::element_defs::ElementDef; #[allow(unused_imports)] use crate::base::parser::{ BoundTo, ElementReader, ElementState, IntoReader, NextStateNavigation, ReaderError, SkipStateNavigation, StateDataParser, StateError, }; #[allow(unused_imports)] use crate::base::stream::{parse, serialize, stream_diff}; use crate::core::element_defs; #[allow(unused_imports)] use crate::{ impl_from_readers_for_states, impl_from_subreaders_for_readers, impl_from_substates_for_states, impl_into_reader, impl_next_state_navigation, impl_skip_state_navigation, }; use enum_dispatch::enum_dispatch; use core::convert::{From, TryInto}; use core::marker::PhantomData; use std::io::BufRead; // Top-Level Reader/State Enums ######################################################################### #[enum_dispatch(FilesNextStates)] #[enum_dispatch(FilesNextReaders<R>)] #[enum_dispatch(FileNextStates)] #[enum_dispatch(FileNextReaders<R>)] #[enum_dispatch(_DocumentNextStates)] #[enum_dispatch(_DocumentNextReaders<R>)] #[enum_dispatch(VoidPrevStates)] #[enum_dispatch(VoidPrevReaders<R>)] #[enum_dispatch(States)] #[enum_dispatch(Readers<R>)] trait BlankTrait {} #[enum_dispatch] pub enum States { Void(VoidState),Files(FilesState),FileName(FileNameState),MimeType(MimeTypeState),ModificationTimestamp(ModificationTimestampState),Data(DataState),File(FileState),_Document(_DocumentState), } #[enum_dispatch] pub enum Readers<R> { Void(VoidReader<R>),Files(FilesReader<R>),FileName(FileNameReader<R>),MimeType(MimeTypeReader<R>),ModificationTimestamp(ModificationTimestampReader<R>),Data(DataReader<R>),File(FileReader<R>),_Document(_DocumentReader<R>), } impl_into_reader!( States, Readers, [Void, Files, FileName, MimeType, ModificationTimestamp, Data, File, _Document] ); impl_from_readers_for_states!( Readers, States, [Void, Files, FileName, MimeType, ModificationTimestamp, Data, File, _Document] ); // _Document Objects ######################################################################### #[derive(Debug, Clone, PartialEq)] pub struct _DocumentState; pub type _DocumentReader<R> = ElementReader<R, _DocumentState>; impl<R: BufRead> _DocumentReader<R> { pub fn new(reader: R) -> Self { Self { reader, state: _DocumentState, } } } impl<R: BufRead> IntoReader<R> for _DocumentState { type Reader = _DocumentReader<R>; fn into_reader(self, reader: R) -> _DocumentReader<R> { _DocumentReader::new(reader) } } impl_next_state_navigation!( _DocumentState, _DocumentNextStates, [(Files, FilesState), (Void, VoidState)] ); #[derive(Debug, Clone, PartialEq)] #[enum_dispatch] pub enum _DocumentNextStates { Files(FilesState),Void(VoidState), } #[derive(Debug, PartialEq)] #[enum_dispatch] pub enum _DocumentNextReaders<R> { Files(FilesReader<R>),Void(VoidReader<R>), } impl_from_substates_for_states!(_DocumentNextStates, States, [Files, Void]); impl_from_subreaders_for_readers!(_DocumentNextReaders, Readers, [Files, Void]); impl_into_reader!(_DocumentNextStates, _DocumentNextReaders, [Files, Void]); impl_from_readers_for_states!(_DocumentNextReaders, _DocumentNextStates, [Files, Void]); // Void Objects ######################################################################### pub type VoidState = ElementState<element_defs::VoidDef, VoidPrevStates>; pub type VoidReader<R> = ElementReader<R, VoidState>; impl VoidState { pub fn new(bytes_left: usize, parent_state: VoidPrevStates) -> Self { Self { bytes_left, parent_state, _phantom: PhantomData::<_>, } } } impl<R: BufRead> VoidReader<R> { pub fn new(reader: R, state: VoidState) -> Self { Self { reader, state } } } impl_skip_state_navigation!(VoidState, VoidPrevStates); impl_next_state_navigation!(VoidState, VoidPrevStates, []); #[derive(Debug, Clone, PartialEq)] #[enum_dispatch] pub enum VoidPrevStates { _Document(_DocumentState),File(FileState),Files(FilesState), } #[derive(Debug, PartialEq)] #[enum_dispatch] pub enum VoidPrevReaders<R> { _Document(_DocumentReader<R>),File(FileReader<R>),Files(FilesReader<R>), } impl_from_substates_for_states!(VoidPrevStates, States, [_Document, Files, File]); impl_from_subreaders_for_readers!(VoidPrevReaders, Readers, [_Document, Files, File]); impl_into_reader!(VoidPrevStates, VoidPrevReaders, [_Document, Files, File]); impl_from_readers_for_states!(VoidPrevReaders, VoidPrevStates, [_Document, Files, File]); // Files Objects ######################################################################### pub type FilesState = ElementState<element_defs::FilesDef, _DocumentState>; pub type FilesReader<R> = ElementReader<R, FilesState>; impl FilesState { pub fn new(bytes_left: usize, parent_state: _DocumentState) -> Self { Self { bytes_left, parent_state, _phantom: PhantomData::<_>, } } } impl<R: BufRead> FilesReader<R> { pub fn new(reader: R, state: FilesState) -> Self { Self { reader, state } } } impl_skip_state_navigation!(FilesState, _DocumentState); impl_next_state_navigation!(FilesState, FilesNextStates, [(Void, VoidState), (File, FileState)]); #[derive(Debug, Clone, PartialEq)] #[enum_dispatch] pub enum FilesNextStates { Void(VoidState),File(FileState), Parent(_DocumentState), } #[derive(Debug, PartialEq)] #[enum_dispatch] pub enum FilesNextReaders<R> { Void(VoidReader<R>),File(FileReader<R>), Parent(_DocumentReader<R>), } impl_from_substates_for_states!(FilesNextStates, States, [Void, File, Parent]); impl_from_subreaders_for_readers!(FilesNextReaders, Readers, [Void, File, Parent]); impl_into_reader!(FilesNextStates, FilesNextReaders, [Void, File, Parent]); impl_from_readers_for_states!(FilesNextReaders, FilesNextStates, [Void, File, Parent]); // FileName Objects ######################################################################### pub type FileNameState = ElementState<element_defs::FileNameDef, FileState>; pub type FileNameReader<R> = ElementReader<R, FileNameState>; impl FileNameState { pub fn new(bytes_left: usize, parent_state: FileState) -> Self { Self { bytes_left, parent_state, _phantom: PhantomData::<_>, } } } impl<R: BufRead> FileNameReader<R> { pub fn new(reader: R, state: FileNameState) -> Self { Self { reader, state } } } impl_skip_state_navigation!(FileNameState, FileState); impl_next_state_navigation!(FileNameState, FileState, []); // MimeType Objects ######################################################################### pub type MimeTypeState = ElementState<element_defs::MimeTypeDef, FileState>; pub type MimeTypeReader<R> = ElementReader<R, MimeTypeState>; impl MimeTypeState { pub fn new(bytes_left: usize, parent_state: FileState) -> Self { Self { bytes_left, parent_state, _phantom: PhantomData::<_>, } } } impl<R: BufRead> MimeTypeReader<R> { pub fn new(reader: R, state: MimeTypeState) -> Self { Self { reader, state } } } impl_skip_state_navigation!(MimeTypeState, FileState); impl_next_state_navigation!(MimeTypeState, FileState, []); // ModificationTimestamp Objects ######################################################################### pub type ModificationTimestampState = ElementState<element_defs::ModificationTimestampDef, FileState>; pub type ModificationTimestampReader<R> = ElementReader<R, ModificationTimestampState>; impl ModificationTimestampState { pub fn new(bytes_left: usize, parent_state: FileState) -> Self { Self { bytes_left, parent_state, _phantom: PhantomData::<_>, } } } impl<R: BufRead> ModificationTimestampReader<R> { pub fn new(reader: R, state: ModificationTimestampState) -> Self { Self { reader, state } } } impl_skip_state_navigation!(ModificationTimestampState, FileState); impl_next_state_navigation!(ModificationTimestampState, FileState, []); // Data Objects ######################################################################### pub type DataState = ElementState<element_defs::DataDef, FileState>; pub type DataReader<R> = ElementReader<R, DataState>; impl DataState { pub fn new(bytes_left: usize, parent_state: FileState) -> Self { Self { bytes_left, parent_state, _phantom: PhantomData::<_>, } } } impl<R: BufRead> DataReader<R> { pub fn new(reader: R, state: DataState) -> Self { Self { reader, state } } } impl_skip_state_navigation!(DataState, FileState); impl_next_state_navigation!(DataState, FileState, []); // File Objects ######################################################################### pub type FileState = ElementState<element_defs::FileDef, FilesState>; pub type FileReader<R> = ElementReader<R, FileState>; impl FileState { pub fn new(bytes_left: usize, parent_state: FilesState) -> Self { Self { bytes_left, parent_state, _phantom: PhantomData::<_>, } } } impl<R: BufRead> FileReader<R> { pub fn new(reader: R, state: FileState) -> Self { Self { reader, state } } } impl_skip_state_navigation!(FileState, FilesState); impl_next_state_navigation!(FileState, FileNextStates, [(Void, VoidState), (Data, DataState), (FileName, FileNameState), (ModificationTimestamp, ModificationTimestampState), (MimeType, MimeTypeState)]); #[derive(Debug, Clone, PartialEq)] #[enum_dispatch] pub enum FileNextStates { Void(VoidState),Data(DataState),FileName(FileNameState),ModificationTimestamp(ModificationTimestampState),MimeType(MimeTypeState), Parent(FilesState), } #[derive(Debug, PartialEq)] #[enum_dispatch] pub enum FileNextReaders<R> { Void(VoidReader<R>),Data(DataReader<R>),FileName(FileNameReader<R>),ModificationTimestamp(ModificationTimestampReader<R>),MimeType(MimeTypeReader<R>), Parent(FilesReader<R>), } impl_from_substates_for_states!(FileNextStates, States, [Void, Data, FileName, ModificationTimestamp, MimeType, Parent]); impl_from_subreaders_for_readers!(FileNextReaders, Readers, [Void, Data, FileName, ModificationTimestamp, MimeType, Parent]); impl_into_reader!(FileNextStates, FileNextReaders, [Void, Data, FileName, ModificationTimestamp, MimeType, Parent]); impl_from_readers_for_states!(FileNextReaders, FileNextStates, [Void, Data, FileName, ModificationTimestamp, MimeType, Parent]);
44.854167
238
0.476412
eb9ca8135945cb4913ae9be9605a7c6e84c756b4
3,920
use seq_io::{fasta, fastq, fastx}; use simple_reader::{compare_simple, compare_readers, compare_recset}; mod simple_reader; pub fn evaluate(data: &[u8]) { // FASTA // normal let reader = fasta::Reader::with_capacity(data, 3); let simple_rdr = simple_reader::Reader::new_fasta(data, true); compare_simple(reader, simple_rdr, false); compare_readers( fasta::Reader::with_capacity(data, 3).set_store::<fasta::LineStore>(), fasta::Reader::with_capacity(data, 3).set_store::<fastx::LineStore>(), ); compare_readers( // TODO: line numbers not correct fasta::Reader::with_capacity(data, 3).set_store::<fasta::LineStore>(), fasta::Reader::with_capacity(data, 3).set_store::<fastq::RangeStore>(), ); compare_readers( fasta::Reader::with_capacity(data, 3).set_store::<fasta::LineStore>(), fasta::Reader::with_capacity(data, 3).set_store::<fastq::multiline::MultiRangeStore>(), ); compare_recset( fasta::Reader::with_capacity(data, 3), fasta::Reader::with_capacity(data, 3) ); // single-line let reader = fasta::single_line::Reader::with_capacity(data, 3); let simple_rdr = simple_reader::Reader::new_fasta(data, false); compare_simple(reader, simple_rdr, false); compare_readers( fasta::single_line::Reader::with_capacity(data, 3).set_store::<fasta::single_line::RangeStore>(), fasta::single_line::Reader::with_capacity(data, 3).set_store::<fasta::LineStore>(), ); compare_readers( fasta::single_line::Reader::with_capacity(data, 3).set_store::<fasta::single_line::RangeStore>(), fasta::single_line::Reader::with_capacity(data, 3).set_store::<fastx::LineStore>(), ); compare_readers( fasta::single_line::Reader::with_capacity(data, 3).set_store::<fasta::single_line::RangeStore>(), fasta::single_line::Reader::with_capacity(data, 3).set_store::<fastq::RangeStore>(), ); compare_readers( fasta::single_line::Reader::with_capacity(data, 3).set_store::<fasta::single_line::RangeStore>(), fasta::single_line::Reader::with_capacity(data, 3).set_store::<fastq::multiline::MultiRangeStore>(), ); compare_recset( fasta::single_line::Reader::with_capacity(data, 3), fasta::single_line::Reader::with_capacity(data, 3) ); // FASTX <-> FASTA // normal let reader = fasta::Reader::with_capacity(data, 3); let simple_rdr = simple_reader::Reader::new_fastx(data, true, false); compare_simple(reader, simple_rdr, true); // FASTX <-> FASTX // normal let reader = fastx::Reader::with_capacity(data, 3); let simple_rdr = simple_reader::Reader::new_fastx(data, true, false); compare_simple(reader, simple_rdr, false); compare_readers( fastx::Reader::with_capacity(data, 3).set_store::<fastx::LineStore>(), fastx::Reader::with_capacity(data, 3).set_store::<fastq::RangeStore>(), ); compare_readers( fastx::Reader::with_capacity(data, 3).set_store::<fastx::LineStore>(), fastx::Reader::with_capacity(data, 3).set_store::<fastq::multiline::MultiRangeStore>(), ); compare_recset( fastx::Reader::with_capacity(data, 3), fastx::Reader::with_capacity(data, 3) ); // multi-line quality let reader = fastx::multiline_qual::Reader::with_capacity(data, 3); let simple_rdr = simple_reader::Reader::new_fastx(data, true, true); compare_simple(reader, simple_rdr, false); compare_readers( fastx::multiline_qual::Reader::with_capacity(data, 3).set_store::<fastx::LineStore>(), fastx::multiline_qual::Reader::with_capacity(data, 3).set_store::<fastq::multiline::MultiRangeStore>(), ); compare_recset( fastx::multiline_qual::Reader::with_capacity(data, 3), fastx::multiline_qual::Reader::with_capacity(data, 3) ); }
42.150538
111
0.667347
d51c27fd189f6782a457a948153c4bcaa39c9e9f
41,222
// Copyright 2019 The Grin Developers // // 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. //! Grin wallet command-line function implementations use crate::api::TLSConfig; use crate::apiwallet::{try_slatepack_sync_workflow, Owner}; use crate::config::{TorConfig, WalletConfig, WALLET_CONFIG_FILE_NAME}; use crate::core::{core, global}; use crate::error::{Error, ErrorKind}; use crate::impls::SlateGetter as _; use crate::impls::{HttpSlateSender, PathToSlate, PathToSlatepack, SlatePutter}; use crate::keychain; use crate::libwallet::IssueTokenArgs; use crate::libwallet::{ self, InitTxArgs, IssueInvoiceTxArgs, NodeClient, PaymentProof, Slate, SlateVersion, Slatepack, SlatepackAddress, Slatepacker, SlatepackerArgs, WalletLCProvider, }; use crate::util::secp::key::SecretKey; use crate::util::{Mutex, ZeroingString}; use crate::{controller, display}; use grin_wallet_util::OnionV3Address; use serde_json as json; use std::convert::TryFrom; use std::fs::File; use std::io::{Read, Write}; use std::sync::atomic::Ordering; use std::sync::Arc; use std::thread; use std::time::Duration; use uuid::Uuid; fn show_recovery_phrase(phrase: ZeroingString) { println!("Your recovery phrase is:"); println!(); println!("{}", &*phrase); println!(); println!("Please back-up these words in a non-digital format."); } /// Arguments common to all wallet commands #[derive(Clone)] pub struct GlobalArgs { pub account: String, pub api_secret: Option<String>, pub node_api_secret: Option<String>, pub show_spent: bool, pub password: Option<ZeroingString>, pub tls_conf: Option<TLSConfig>, } /// Arguments for init command pub struct InitArgs { /// BIP39 recovery phrase length pub list_length: usize, pub password: ZeroingString, pub config: WalletConfig, pub recovery_phrase: Option<ZeroingString>, pub restore: bool, } pub fn init<L, C, K>( owner_api: &mut Owner<L, C, K>, _g_args: &GlobalArgs, args: InitArgs, test_mode: bool, ) -> Result<(), Error> where L: WalletLCProvider<'static, C, K> + 'static, C: NodeClient + 'static, K: keychain::Keychain + 'static, { // Assume global chain type has already been initialized. let chain_type = global::get_chain_type(); let mut w_lock = owner_api.wallet_inst.lock(); let p = w_lock.lc_provider()?; p.create_config(&chain_type, WALLET_CONFIG_FILE_NAME, None, None, None)?; p.create_wallet( None, args.recovery_phrase, args.list_length, args.password.clone(), test_mode, )?; let m = p.get_mnemonic(None, args.password)?; show_recovery_phrase(m); Ok(()) } /// Argument for recover pub struct RecoverArgs { pub passphrase: ZeroingString, } pub fn recover<L, C, K>(owner_api: &mut Owner<L, C, K>, args: RecoverArgs) -> Result<(), Error> where L: WalletLCProvider<'static, C, K> + 'static, C: NodeClient + 'static, K: keychain::Keychain + 'static, { let mut w_lock = owner_api.wallet_inst.lock(); let p = w_lock.lc_provider()?; let m = p.get_mnemonic(None, args.passphrase)?; show_recovery_phrase(m); Ok(()) } /// Arguments for listen command pub struct ListenArgs {} pub fn listen<L, C, K>( owner_api: &mut Owner<L, C, K>, keychain_mask: Arc<Mutex<Option<SecretKey>>>, config: &WalletConfig, tor_config: &TorConfig, _args: &ListenArgs, g_args: &GlobalArgs, cli_mode: bool, test_mode: bool, ) -> Result<(), Error> where L: WalletLCProvider<'static, C, K> + 'static, C: NodeClient + 'static, K: keychain::Keychain + 'static, { let wallet_inst = owner_api.wallet_inst.clone(); let config = config.clone(); let tor_config = tor_config.clone(); let g_args = g_args.clone(); let api_thread = thread::Builder::new() .name("wallet-http-listener".to_string()) .spawn(move || { let res = controller::foreign_listener( wallet_inst, keychain_mask, &config.api_listen_addr(), g_args.tls_conf.clone(), tor_config.use_tor_listener, test_mode, Some(tor_config.clone()), ); if let Err(e) = res { error!("Error starting listener: {}", e); } }); if let Ok(t) = api_thread { if !cli_mode { let r = t.join(); if let Err(_) = r { error!("Error starting listener"); return Err(ErrorKind::ListenerError.into()); } } } Ok(()) } pub fn owner_api<L, C, K>( owner_api: &mut Owner<L, C, K>, keychain_mask: Option<SecretKey>, config: &WalletConfig, tor_config: &TorConfig, g_args: &GlobalArgs, test_mode: bool, ) -> Result<(), Error> where L: WalletLCProvider<'static, C, K> + Send + Sync + 'static, C: NodeClient + 'static, K: keychain::Keychain + 'static, { // keychain mask needs to be a sinlge instance, in case the foreign API is // also being run at the same time let km = Arc::new(Mutex::new(keychain_mask)); let res = controller::owner_listener( owner_api.wallet_inst.clone(), km, config.owner_api_listen_addr().as_str(), g_args.api_secret.clone(), g_args.tls_conf.clone(), config.owner_api_include_foreign.clone(), Some(tor_config.clone()), test_mode, ); if let Err(e) = res { return Err(ErrorKind::LibWallet(e.kind(), e.cause_string()).into()); } Ok(()) } /// Arguments for account command pub struct AccountArgs { pub create: Option<String>, } pub fn account<L, C, K>( owner_api: &mut Owner<L, C, K>, keychain_mask: Option<&SecretKey>, args: AccountArgs, ) -> Result<(), Error> where L: WalletLCProvider<'static, C, K> + 'static, C: NodeClient + 'static, K: keychain::Keychain + 'static, { if args.create.is_none() { let res = controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { let acct_mappings = api.accounts(m)?; // give logging thread a moment to catch up thread::sleep(Duration::from_millis(200)); display::accounts(acct_mappings); Ok(()) }); if let Err(e) = res { error!("Error listing accounts: {}", e); return Err(ErrorKind::LibWallet(e.kind(), e.cause_string()).into()); } } else { let label = args.create.unwrap(); let res = controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { api.create_account_path(m, &label)?; thread::sleep(Duration::from_millis(200)); info!("Account: '{}' Created!", label); Ok(()) }); if let Err(e) = res { thread::sleep(Duration::from_millis(200)); error!("Error creating account '{}': {}", label, e); return Err(ErrorKind::LibWallet(e.kind(), e.cause_string()).into()); } } Ok(()) } /// Arguments for account command pub struct IssueTokenTxArgs { pub amount: u64, } pub fn issue_token<L, C, K>( owner_api: &mut Owner<L, C, K>, keychain_mask: Option<&SecretKey>, args: IssueTokenTxArgs, ) -> Result<(), Error> where L: WalletLCProvider<'static, C, K> + 'static, C: NodeClient + 'static, K: keychain::Keychain + 'static, { controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { let args = IssueTokenArgs { acct_name: None, amount: args.amount, }; let result = api.init_issue_token_tx(m, args); let slate = match result { Ok(s) => { info!( "Issue token tx created: {} of {} created! fee:{})", core::amount_to_hr_string(s.amount, false), s.token_type.clone().unwrap(), s.fee, ); s } Err(e) => { info!("Tx not created: {}", e); return Err(e); } }; let result = api.post_tx(m, &slate, false); match result { Ok(_) => { info!("Tx sent ok",); return Ok(()); } Err(e) => { error!("Tx sent fail: {}", e); return Err(e); } } })?; Ok(()) } /// Arguments for the send command #[derive(Clone)] pub struct SendArgs { pub amount: u64, pub token_type: Option<String>, pub minimum_confirmations: u64, pub selection_strategy: String, pub estimate_selection_strategies: bool, pub dest: String, pub change_outputs: usize, pub fluff: bool, pub max_outputs: usize, pub target_slate_version: Option<u16>, pub payment_proof_address: Option<SlatepackAddress>, pub ttl_blocks: Option<u64>, pub skip_tor: bool, pub outfile: Option<String>, //TODO: Remove HF3 pub output_v4_slate: bool, } pub fn send<L, C, K>( owner_api: &mut Owner<L, C, K>, keychain_mask: Option<&SecretKey>, tor_config: Option<TorConfig>, args: SendArgs, dark_scheme: bool, test_mode: bool, ) -> Result<(), Error> where L: WalletLCProvider<'static, C, K> + 'static, C: NodeClient + 'static, K: keychain::Keychain + 'static, { let wallet_inst = owner_api.wallet_inst.clone(); // Check other version, and if it only supports 3 set the target slate // version to 3 to avoid removing the transaction object // TODO: This block is temporary, for the period between the release of v4.0.0 and HF3, // after which this should be removable let mut args = args; //TODO: Remove block post HF3 // All this block does is determine whether the slate should be // output as a V3 Slate for the receiver let mut tor_sender = None; let is_pre_fork; { is_pre_fork = { let cur_height = { libwallet::wallet_lock!(wallet_inst, w); w.w2n_client().get_chain_tip()?.0 }; match global::get_chain_type() { global::ChainTypes::Mainnet => { if cur_height < 80640 && !args.output_v4_slate { true } else { false } } global::ChainTypes::Floonet => { if cur_height < 864 && !args.output_v4_slate { true } else { false } } _ => false, } }; if is_pre_fork { let trailing = match args.dest.ends_with('/') { true => "", false => "/", }; let mut address_found = false; // For sync methods, derive intended endpoint from dest match SlatepackAddress::try_from(args.dest.as_str()) { Ok(address) => { let tor_addr = OnionV3Address::try_from(&address).unwrap(); // Try pinging the destination via TOR debug!("Version ping: TOR address is: {}", tor_addr); match HttpSlateSender::with_socks_proxy( &tor_addr.to_http_str(), &tor_config.as_ref().unwrap().socks_proxy_addr, &tor_config.as_ref().unwrap().send_config_dir, ) { Ok(mut sender) => { let url_str = format!("{}{}v2/foreign", tor_addr.to_http_str(), trailing); if let Ok(v) = sender.check_other_version(&url_str) { if v == SlateVersion::V3 { args.target_slate_version = Some(3); } address_found = true; } tor_sender = Some(sender); } Err(e) => { debug!( "Version ping: Couldn't create slate sender for TOR: {:?}", e ); } } } Err(e) => { debug!("Version ping: Address is not SlatepackAddress: {:?}", e); } } // now try http if !address_found { // Try pinging the destination via TOR match HttpSlateSender::new(&args.dest) { Ok(mut sender) => { let url_str = format!("{}{}v2/foreign", args.dest, trailing); match sender.check_other_version(&url_str) { Ok(v) => { if v == SlateVersion::V3 { args.target_slate_version = Some(3); } address_found = true; } Err(e) => { debug!( "Version ping: Couldn't get other version for HTTP: {:?}", e ); } } } Err(e) => { debug!( "Version ping: Couldn't create slate sender for HTTP: {:?}", e ); } } } if !address_found { // otherwise, determine slate format based on block height // For files spit out a V3 Slate if we're before HF3, // Or V4 slate otherwise if is_pre_fork { args.target_slate_version = Some(3); } } } } // end pre HF3 Block let mut slate = Slate::blank(2, false); controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { if args.estimate_selection_strategies { let strategies = vec!["smallest", "all"] .into_iter() .map(|strategy| { let init_args = InitTxArgs { src_acct_name: None, amount: args.amount, token_type: args.token_type.clone(), minimum_confirmations: args.minimum_confirmations, max_outputs: args.max_outputs as u32, num_change_outputs: args.change_outputs as u32, selection_strategy_is_use_all: strategy == "all", estimate_only: Some(true), ..Default::default() }; let slate = api.init_send_tx(m, init_args).unwrap(); (strategy, slate.amount, slate.fee) }) .collect(); display::estimate(args.amount, strategies, dark_scheme); return Ok(()); } else { let init_args = InitTxArgs { src_acct_name: None, amount: args.amount, token_type: args.token_type.clone(), minimum_confirmations: args.minimum_confirmations, max_outputs: args.max_outputs as u32, num_change_outputs: args.change_outputs as u32, selection_strategy_is_use_all: args.selection_strategy == "all", target_slate_version: args.target_slate_version, payment_proof_recipient_address: args.payment_proof_address.clone(), ttl_blocks: args.ttl_blocks, send_args: None, ..Default::default() }; let result = api.init_send_tx(m, init_args); slate = match result { Ok(s) => { info!( "Tx created: {} grin to {} (strategy '{}')", core::amount_to_hr_string(args.amount, false), args.dest, args.selection_strategy, ); s } Err(e) => { info!("Tx not created: {}", e); return Err(e); } }; } Ok(()) })?; let tor_config = match tor_config { Some(mut c) => { c.skip_send_attempt = Some(args.skip_tor); Some(c) } None => None, }; let res = try_slatepack_sync_workflow(&slate, &args.dest, tor_config, tor_sender, false, test_mode); match res { Ok(Some(s)) => { controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { api.tx_lock_outputs(m, &s)?; let ret_slate = api.finalize_tx(m, &s)?; let result = api.post_tx(m, &ret_slate, args.fluff); match result { Ok(_) => { println!("Tx sent successfully",); Ok(()) } Err(e) => { error!("Tx sent fail: {}", e); Err(e.into()) } } })?; } Ok(None) => { output_slatepack( owner_api, keychain_mask, &slate, args.dest.as_str(), args.outfile, true, false, is_pre_fork, )?; } Err(e) => return Err(e.into()), } Ok(()) } pub fn output_slatepack<L, C, K>( owner_api: &mut Owner<L, C, K>, keychain_mask: Option<&SecretKey>, slate: &Slate, dest: &str, out_file_override: Option<String>, lock: bool, finalizing: bool, is_pre_fork: bool, ) -> Result<(), libwallet::Error> where L: WalletLCProvider<'static, C, K> + 'static, C: NodeClient + 'static, K: keychain::Keychain + 'static, { // Output the slatepack file to stdout and to a file let mut message = String::from(""); let mut address = None; let mut tld = String::from(""); controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { address = match SlatepackAddress::try_from(dest) { Ok(a) => Some(a), Err(_) => None, }; // encrypt for recipient by default let recipients = match address.clone() { Some(a) => vec![a], None => vec![], }; message = api.create_slatepack_message(m, &slate, Some(0), recipients)?; tld = api.get_top_level_directory()?; Ok(()) })?; // create a directory to which files will be output let slate_dir = format!("{}/{}", tld, "slatepack"); let _ = std::fs::create_dir_all(slate_dir.clone()); let out_file_name = match out_file_override { None => format!("{}/{}.{}.slatepack", slate_dir, slate.id, slate.state), Some(f) => f, }; if lock { controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { api.tx_lock_outputs(m, &slate)?; Ok(()) })?; } // TODO: Remove HF3 if is_pre_fork { PathToSlate((&out_file_name).into()).put_tx(&slate, false)?; println!(); println!("Transaction file was output to:"); println!(); println!("{}", out_file_name); println!(); if !finalizing { println!("Please send this file to the other party manually"); } return Ok(()); } println!("{}", out_file_name); let mut output = File::create(out_file_name.clone())?; output.write_all(&message.as_bytes())?; output.sync_all()?; println!(); if !finalizing { println!("Slatepack data follows. Please provide this output to the other party"); } else { println!("Slatepack data follows."); } println!(); println!("--- CUT BELOW THIS LINE ---"); println!(); println!("{}", message); println!("--- CUT ABOVE THIS LINE ---"); println!(); println!("Slatepack data was also output to"); println!(); println!("{}", out_file_name); println!(); if address.is_some() { println!("The slatepack data is encrypted for the recipient only"); } else { println!("The slatepack data is NOT encrypted"); } println!(); Ok(()) } // Parse a slate and slatepack from a message pub fn parse_slatepack<L, C, K>( owner_api: &mut Owner<L, C, K>, keychain_mask: Option<&SecretKey>, filename: Option<String>, message: Option<String>, ) -> Result<(Slate, Option<SlatepackAddress>), Error> where L: WalletLCProvider<'static, C, K>, C: NodeClient + 'static, K: keychain::Keychain + 'static, { let mut ret_address = None; let slate = match filename { Some(f) => { // first try regular slate - remove HF3 let mut sl = match PathToSlate((&f).into()).get_tx() { Ok(s) => Some(s.0), //pre HF3, regular slate Err(_) => None, }; // otherwise, get slate from slatepack if sl.is_none() { controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { let dec_key = api.get_slatepack_secret_key(m, 0)?; let packer = Slatepacker::new(SlatepackerArgs { sender: None, recipients: vec![], dec_key: Some(&dec_key), }); let pts = PathToSlatepack::new(f.into(), &packer, true); sl = Some(pts.get_tx()?.0); ret_address = pts.get_slatepack(true)?.sender; Ok(()) })?; } sl } None => None, }; let slate = match slate { Some(s) => s, None => { // try and parse directly from input_slatepack_message let mut slate = Slate::blank(2, false); match message { Some(message) => { controller::owner_single_use( None, keychain_mask, Some(owner_api), |api, m| { slate = api.slate_from_slatepack_message(m, message.clone(), vec![0])?; let slatepack = api.decode_slatepack_message(m, message.clone(), vec![0])?; ret_address = slatepack.sender; Ok(()) }, )?; } None => { let msg = "No slate provided via file or direct input"; return Err(ErrorKind::GenericError(msg.into()).into()); } } slate } }; Ok((slate, ret_address)) } /// Receive command argument #[derive(Clone)] pub struct ReceiveArgs { pub input_file: Option<String>, pub input_slatepack_message: Option<String>, pub skip_tor: bool, pub outfile: Option<String>, } pub fn receive<L, C, K>( owner_api: &mut Owner<L, C, K>, keychain_mask: Option<&SecretKey>, g_args: &GlobalArgs, args: ReceiveArgs, tor_config: Option<TorConfig>, test_mode: bool, ) -> Result<(), Error> where L: WalletLCProvider<'static, C, K>, C: NodeClient + 'static, K: keychain::Keychain + 'static, { let (mut slate, ret_address) = parse_slatepack( owner_api, keychain_mask, args.input_file, args.input_slatepack_message, )?; let km = match keychain_mask.as_ref() { None => None, Some(&m) => Some(m.to_owned()), }; let tor_config = match tor_config { Some(mut c) => { c.skip_send_attempt = Some(args.skip_tor); Some(c) } None => None, }; controller::foreign_single_use(owner_api.wallet_inst.clone(), km, |api| { slate = api.receive_tx(&slate, Some(&g_args.account), None)?; Ok(()) })?; let dest = match ret_address { Some(a) => String::try_from(&a).unwrap(), None => String::from(""), }; let res = try_slatepack_sync_workflow(&slate, &dest, tor_config, None, true, test_mode); match res { Ok(Some(_)) => { println!(); println!( "Transaction recieved and sent back to sender at {} for finalization.", dest ); println!(); Ok(()) } Ok(None) => { output_slatepack( owner_api, keychain_mask, &slate, &dest, args.outfile, false, false, slate.version_info.version < 4, )?; Ok(()) } Err(e) => Err(e.into()), } } pub fn unpack<L, C, K>( owner_api: &mut Owner<L, C, K>, keychain_mask: Option<&SecretKey>, args: ReceiveArgs, ) -> Result<(), Error> where L: WalletLCProvider<'static, C, K> + 'static, C: NodeClient + 'static, K: keychain::Keychain + 'static, { let mut slatepack = match args.input_file { Some(f) => { let packer = Slatepacker::new(SlatepackerArgs { sender: None, recipients: vec![], dec_key: None, }); PathToSlatepack::new(f.into(), &packer, true).get_slatepack(false)? } None => match args.input_slatepack_message { Some(mes) => { let mut sp = Slatepack::default(); controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { sp = api.decode_slatepack_message(m, mes, vec![])?; Ok(()) })?; sp } None => { return Err(ErrorKind::ArgumentError("Invalid Slatepack Input".into()).into()); } }, }; println!(); println!("SLATEPACK CONTENTS"); println!("------------------"); println!("{}", slatepack); println!("------------------"); let packer = Slatepacker::new(SlatepackerArgs { sender: None, recipients: vec![], dec_key: None, }); if slatepack.mode == 1 { controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { let dec_key = api.get_slatepack_secret_key(m, 0)?; match slatepack.try_decrypt_payload(Some(&dec_key)) { Ok(_) => { println!("Slatepack is encrypted for this wallet"); println!(); println!("DECRYPTED SLATEPACK"); println!("-------------------"); println!("{}", slatepack); let slate = packer.get_slate(&slatepack)?; println!(); println!("DECRYPTED SLATE"); println!("---------------"); println!("{}", slate); } Err(_) => { println!("Slatepack payload cannot be decrypted by this wallet"); } } Ok(()) })?; } else { let slate = packer.get_slate(&slatepack)?; println!("Slatepack is not encrypted"); println!(); println!("SLATE"); println!("-----"); println!("{}", slate); } Ok(()) } /// Finalize command args #[derive(Clone)] pub struct FinalizeArgs { pub input_file: Option<String>, pub input_slatepack_message: Option<String>, pub fluff: bool, pub nopost: bool, pub outfile: Option<String>, } pub fn finalize<L, C, K>( owner_api: &mut Owner<L, C, K>, keychain_mask: Option<&SecretKey>, args: FinalizeArgs, ) -> Result<(), Error> where L: WalletLCProvider<'static, C, K> + 'static, C: NodeClient + 'static, K: keychain::Keychain + 'static, { let (mut slate, _ret_address) = parse_slatepack( owner_api, keychain_mask, args.input_file.clone(), args.input_slatepack_message.clone(), )?; // Rather than duplicating the entire command, we'll just // try to determine what kind of finalization this is // based on the slate contents // for now, we can tell this is an invoice transaction // if the receipient (participant 1) hasn't completed sigs let mut is_invoice = false; controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { is_invoice = api.context_is_invoice(m, &slate)?; Ok(()) })?; if is_invoice { let km = match keychain_mask.as_ref() { None => None, Some(&m) => Some(m.to_owned()), }; controller::foreign_single_use(owner_api.wallet_inst.clone(), km, |api| { slate = api.finalize_tx(&slate, false)?; Ok(()) })?; } else { controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { slate = api.finalize_tx(m, &slate)?; Ok(()) })?; } if !&args.nopost { controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { let result = api.post_tx(m, &slate, args.fluff); match result { Ok(_) => { info!( "Transaction sent successfully, check the wallet again for confirmation." ); println!("Transaction posted"); Ok(()) } Err(e) => { error!("Tx not sent: {}", e); Err(e) } } })?; } println!("Transaction finalized successfully"); output_slatepack( owner_api, keychain_mask, &slate, "", args.outfile, false, true, slate.version_info.version < 4, )?; Ok(()) } /// Issue Invoice Args pub struct IssueInvoiceArgs { /// Slatepack address pub dest: String, /// issue invoice tx args pub issue_args: IssueInvoiceTxArgs, /// whether to output a V4 slate pub output_v4_slate: bool, /// output file override pub outfile: Option<String>, } pub fn issue_invoice_tx<L, C, K>( owner_api: &mut Owner<L, C, K>, keychain_mask: Option<&SecretKey>, args: IssueInvoiceArgs, ) -> Result<(), Error> where L: WalletLCProvider<'static, C, K> + 'static, C: NodeClient + 'static, K: keychain::Keychain + 'static, { //TODO: Remove block HF3 let is_pre_fork = { let cur_height = { let wallet_inst = owner_api.wallet_inst.clone(); libwallet::wallet_lock!(wallet_inst, w); w.w2n_client().get_chain_tip()?.0 }; match global::get_chain_type() { global::ChainTypes::Mainnet => { if cur_height < 80640 && !&args.output_v4_slate { true } else { false } } global::ChainTypes::Floonet => { if cur_height < 864 && !&args.output_v4_slate { true } else { false } } _ => false, } }; let mut issue_args = args.issue_args.clone(); if is_pre_fork { issue_args.target_slate_version = Some(3); } let mut slate = Slate::blank(2, false); controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { slate = api.issue_invoice_tx(m, issue_args)?; Ok(()) })?; output_slatepack( owner_api, keychain_mask, &slate, args.dest.as_str(), args.outfile, false, false, is_pre_fork, )?; Ok(()) } /// Arguments for the process_invoice command pub struct ProcessInvoiceArgs { pub minimum_confirmations: u64, pub selection_strategy: String, pub ret_address: Option<SlatepackAddress>, pub max_outputs: usize, pub slate: Slate, pub estimate_selection_strategies: bool, pub ttl_blocks: Option<u64>, pub skip_tor: bool, pub outfile: Option<String>, } /// Process invoice pub fn process_invoice<L, C, K>( owner_api: &mut Owner<L, C, K>, keychain_mask: Option<&SecretKey>, tor_config: Option<TorConfig>, args: ProcessInvoiceArgs, dark_scheme: bool, test_mode: bool, ) -> Result<(), Error> where L: WalletLCProvider<'static, C, K> + 'static, C: NodeClient + 'static, K: keychain::Keychain + 'static, { let mut slate = args.slate.clone(); let dest = match args.ret_address.clone() { Some(a) => String::try_from(&a).unwrap(), None => String::from(""), }; controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { if args.estimate_selection_strategies { let strategies = vec!["smallest", "all"] .into_iter() .map(|strategy| { let init_args = InitTxArgs { src_acct_name: None, amount: slate.amount, minimum_confirmations: args.minimum_confirmations, max_outputs: args.max_outputs as u32, num_change_outputs: 1u32, selection_strategy_is_use_all: strategy == "all", estimate_only: Some(true), ..Default::default() }; let slate = api.init_send_tx(m, init_args).unwrap(); (strategy, slate.amount, slate.fee) }) .collect(); display::estimate(slate.amount, strategies, dark_scheme); return Ok(()); } else { let init_args = InitTxArgs { src_acct_name: None, amount: 0, minimum_confirmations: args.minimum_confirmations, max_outputs: args.max_outputs as u32, num_change_outputs: 1u32, selection_strategy_is_use_all: args.selection_strategy == "all", ttl_blocks: args.ttl_blocks, send_args: None, ..Default::default() }; let result = api.process_invoice_tx(m, &slate, init_args); slate = match result { Ok(s) => { info!( "Invoice processed: {} grin (strategy '{}')", core::amount_to_hr_string(slate.amount, false), args.selection_strategy, ); s } Err(e) => { info!("Tx not created: {}", e); return Err(e); } }; } Ok(()) })?; let tor_config = match tor_config { Some(mut c) => { c.skip_send_attempt = Some(args.skip_tor); Some(c) } None => None, }; let res = try_slatepack_sync_workflow(&slate, &dest, tor_config, None, true, test_mode); match res { Ok(Some(_)) => { println!(); println!( "Transaction paid and sent back to initiator at {} for finalization.", dest ); println!(); Ok(()) } Ok(None) => { output_slatepack( owner_api, keychain_mask, &slate, &dest, args.outfile, true, false, slate.version_info.version < 4, )?; Ok(()) } Err(e) => Err(e.into()), } } /// Info command args pub struct InfoArgs { pub minimum_confirmations: u64, } pub fn info<L, C, K>( owner_api: &mut Owner<L, C, K>, keychain_mask: Option<&SecretKey>, g_args: &GlobalArgs, args: InfoArgs, dark_scheme: bool, ) -> Result<(), Error> where L: WalletLCProvider<'static, C, K> + 'static, C: NodeClient + 'static, K: keychain::Keychain + 'static, { let updater_running = owner_api.updater_running.load(Ordering::Relaxed); controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { let (validated, wallet_info) = api.retrieve_summary_info(m, true, args.minimum_confirmations)?; display::info( &g_args.account, &wallet_info, validated || updater_running, dark_scheme, ); Ok(()) })?; Ok(()) } pub fn outputs<L, C, K>( owner_api: &mut Owner<L, C, K>, keychain_mask: Option<&SecretKey>, g_args: &GlobalArgs, dark_scheme: bool, ) -> Result<(), Error> where L: WalletLCProvider<'static, C, K> + 'static, C: NodeClient + 'static, K: keychain::Keychain + 'static, { let updater_running = owner_api.updater_running.load(Ordering::Relaxed); controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { let res = api.node_height(m)?; let (validated, outputs) = api.retrieve_outputs(m, g_args.show_spent, true, None)?; display::outputs( &g_args.account, res.height, validated || updater_running, outputs, dark_scheme, )?; let (token_validated, token_outputs) = api.retrieve_token_outputs(m, g_args.show_spent, true, None)?; display::token_outputs( &g_args.account, res.height, token_validated || updater_running, token_outputs, dark_scheme, )?; Ok(()) })?; Ok(()) } /// Txs command args pub struct TxsArgs { pub id: Option<u32>, pub tx_slate_id: Option<Uuid>, } pub fn txs<L, C, K>( owner_api: &mut Owner<L, C, K>, keychain_mask: Option<&SecretKey>, g_args: &GlobalArgs, args: TxsArgs, dark_scheme: bool, ) -> Result<(), Error> where L: WalletLCProvider<'static, C, K> + 'static, C: NodeClient + 'static, K: keychain::Keychain + 'static, { let updater_running = owner_api.updater_running.load(Ordering::Relaxed); controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { let res = api.node_height(m)?; let (validated, txs) = api.retrieve_txs(m, true, args.id, args.tx_slate_id)?; let include_status = !args.id.is_some() && !args.tx_slate_id.is_some(); display::txs( &g_args.account, res.height, validated || updater_running, &txs, include_status, dark_scheme, )?; let (token_validated, token_txs) = api.retrieve_token_txs(m, true, args.id, args.tx_slate_id)?; let include_status = !args.id.is_some() && !args.tx_slate_id.is_some(); display::token_txs( &g_args.account, res.height, token_validated || updater_running, &token_txs, include_status, dark_scheme, )?; // if given a particular transaction id or uuid, also get and display associated // inputs/outputs and messages let id = if args.id.is_some() { args.id } else if args.tx_slate_id.is_some() { if let Some(tx) = txs.iter().find(|t| t.tx_slate_id == args.tx_slate_id) { Some(tx.id) } else { if let Some(tx) = token_txs.iter().find(|t| t.tx_slate_id == args.tx_slate_id) { Some(tx.id) } else { println!("Could not find a transaction matching given txid.\n"); None } } } else { None }; if id.is_some() { let (_, outputs) = api.retrieve_outputs(m, true, false, id)?; display::outputs( &g_args.account, res.height, validated || updater_running, outputs, dark_scheme, )?; // should only be one here, but just in case for tx in txs { display::payment_proof(&tx)?; } let (_, token_outputs) = api.retrieve_token_outputs(m, true, false, id)?; display::token_outputs( &g_args.account, res.height, validated, token_outputs, dark_scheme, )?; // should only be one here, but just in case for tx in token_txs { display::token_payment_proof(&tx)?; } } Ok(()) })?; Ok(()) } /// Post #[derive(Clone)] pub struct PostArgs { pub input_file: Option<String>, pub input_slatepack_message: Option<String>, pub fluff: bool, } pub fn post<L, C, K>( owner_api: &mut Owner<L, C, K>, keychain_mask: Option<&SecretKey>, args: PostArgs, ) -> Result<(), Error> where L: WalletLCProvider<'static, C, K> + 'static, C: NodeClient + 'static, K: keychain::Keychain + 'static, { let (slate, _ret_address) = parse_slatepack( owner_api, keychain_mask, args.input_file, args.input_slatepack_message, )?; let fluff = args.fluff; controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { api.post_tx(m, &slate, fluff)?; info!("Posted transaction"); return Ok(()); })?; Ok(()) } /// Repost pub struct RepostArgs { pub id: u32, pub dump_file: Option<String>, pub fluff: bool, } pub fn repost<L, C, K>( owner_api: &mut Owner<L, C, K>, keychain_mask: Option<&SecretKey>, args: RepostArgs, ) -> Result<(), Error> where L: WalletLCProvider<'static, C, K> + 'static, C: NodeClient + 'static, K: keychain::Keychain + 'static, { controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { let stored_tx_slate = match api.get_stored_tx(m, Some(args.id), None)? { None => { error!( "Transaction with id {} does not have transaction data. Not reposting.", args.id ); return Ok(()); } Some(s) => s, }; let (_, txs) = api.retrieve_txs(m, true, Some(args.id), None)?; let (_, token_txs) = api.retrieve_token_txs(m, true, Some(args.id), None)?; match args.dump_file { None => { if txs.len() > 0 && txs[0].confirmed { error!( "Transaction with id {} is confirmed. Not reposting.", args.id ); return Ok(()); } if token_txs.len() > 0 && token_txs[0].confirmed { error!( "Transaction with id {} is confirmed. Not reposting.", args.id ); return Ok(()); } if libwallet::sig_is_blank( &stored_tx_slate.tx.as_ref().unwrap().kernels()[0].excess_sig, ) { error!("Transaction at {} has not been finalized.", args.id); return Ok(()); } match api.post_tx(m, &stored_tx_slate, args.fluff) { Ok(_) => info!("Reposted transaction at {}", args.id), Err(e) => error!("Could not repost transaction at {}. Reason: {}", args.id, e), } return Ok(()); } Some(f) => { let mut tx_file = File::create(f.clone())?; tx_file.write_all( json::to_string(&stored_tx_slate.tx.unwrap()) .unwrap() .as_bytes(), )?; tx_file.sync_all()?; info!("Dumped transaction data for tx {} to {}", args.id, f); return Ok(()); } } })?; Ok(()) } /// Cancel pub struct CancelArgs { pub tx_id: Option<u32>, pub tx_slate_id: Option<Uuid>, pub tx_id_string: String, } pub fn cancel<L, C, K>( owner_api: &mut Owner<L, C, K>, keychain_mask: Option<&SecretKey>, args: CancelArgs, ) -> Result<(), Error> where L: WalletLCProvider<'static, C, K> + 'static, C: NodeClient + 'static, K: keychain::Keychain + 'static, { controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { let result = api.cancel_tx(m, args.tx_id, args.tx_slate_id); match result { Ok(_) => { info!("Transaction {} Cancelled", args.tx_id_string); Ok(()) } Err(e) => { error!("TX Cancellation failed: {}", e); Err(e) } } })?; Ok(()) } /// wallet check pub struct CheckArgs { pub delete_unconfirmed: bool, pub start_height: Option<u64>, pub backwards_from_tip: Option<u64>, } pub fn scan<L, C, K>( owner_api: &mut Owner<L, C, K>, keychain_mask: Option<&SecretKey>, args: CheckArgs, ) -> Result<(), Error> where L: WalletLCProvider<'static, C, K> + 'static, C: NodeClient + 'static, K: keychain::Keychain + 'static, { controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { let tip_height = api.node_height(m)?.height; let start_height = match args.backwards_from_tip { Some(b) => tip_height.saturating_sub(b), None => match args.start_height { Some(s) => s, None => 1, }, }; warn!("Starting output scan from height {} ...", start_height); let result = api.scan(m, Some(start_height), args.delete_unconfirmed); match result { Ok(_) => { warn!("Wallet check complete",); Ok(()) } Err(e) => { error!("Wallet check failed: {}", e); error!("Backtrace: {}", e.backtrace().unwrap()); Err(e) } } })?; Ok(()) } /// Payment Proof Address pub fn address<L, C, K>( owner_api: &mut Owner<L, C, K>, g_args: &GlobalArgs, keychain_mask: Option<&SecretKey>, ) -> Result<(), Error> where L: WalletLCProvider<'static, C, K> + 'static, C: NodeClient + 'static, K: keychain::Keychain + 'static, { controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { // Just address at derivation index 0 for now let address = api.get_slatepack_address(m, 0)?; println!(); println!("Address for account - {}", g_args.account); println!("-------------------------------------"); println!("{}", address); println!(); Ok(()) })?; Ok(()) } /// Proof Export Args pub struct ProofExportArgs { pub output_file: String, pub id: Option<u32>, pub tx_slate_id: Option<Uuid>, } pub fn proof_export<L, C, K>( owner_api: &mut Owner<L, C, K>, keychain_mask: Option<&SecretKey>, args: ProofExportArgs, ) -> Result<(), Error> where L: WalletLCProvider<'static, C, K> + 'static, C: NodeClient + 'static, K: keychain::Keychain + 'static, { controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { let result = api.retrieve_payment_proof(m, true, args.id, args.tx_slate_id); match result { Ok(p) => { // actually export proof let mut proof_file = File::create(args.output_file.clone())?; proof_file.write_all(json::to_string_pretty(&p).unwrap().as_bytes())?; proof_file.sync_all()?; warn!("Payment proof exported to {}", args.output_file); Ok(()) } Err(e) => { error!("Proof export failed: {}", e); Err(e) } } })?; Ok(()) } /// Proof Verify Args pub struct ProofVerifyArgs { pub input_file: String, } pub fn proof_verify<L, C, K>( owner_api: &mut Owner<L, C, K>, keychain_mask: Option<&SecretKey>, args: ProofVerifyArgs, ) -> Result<(), Error> where L: WalletLCProvider<'static, C, K> + 'static, C: NodeClient + 'static, K: keychain::Keychain + 'static, { controller::owner_single_use(None, keychain_mask, Some(owner_api), |api, m| { let mut proof_f = match File::open(&args.input_file) { Ok(p) => p, Err(e) => { let msg = format!("{}", e); error!( "Unable to open payment proof file at {}: {}", args.input_file, e ); return Err(libwallet::ErrorKind::PaymentProofParsing(msg).into()); } }; let mut proof = String::new(); proof_f.read_to_string(&mut proof)?; // read let proof: PaymentProof = match json::from_str(&proof) { Ok(p) => p, Err(e) => { let msg = format!("{}", e); error!("Unable to parse payment proof file: {}", e); return Err(libwallet::ErrorKind::PaymentProofParsing(msg).into()); } }; let result = api.verify_payment_proof(m, &proof); match result { Ok((iam_sender, iam_recipient)) => { println!("Payment proof's signatures are valid."); if iam_sender { println!("The proof's sender address belongs to this wallet."); } if iam_recipient { println!("The proof's recipient address belongs to this wallet."); } if !iam_recipient && !iam_sender { println!( "Neither the proof's sender nor recipient address belongs to this wallet." ); } Ok(()) } Err(e) => { error!("Proof not valid: {}", e); Err(e) } } })?; Ok(()) }
25.166056
96
0.63927
b95502fdffc7a6390777b33a9f0ca9f400e42942
1,384
use crate::builders::CrateBuilder; use crate::util::{RequestHelper, TestApp}; use crate::OkBool; #[test] fn diesel_not_found_results_in_404() { let (_, _, user) = TestApp::init().with_user(); user.get("/api/v1/crates/foo_following/following") .assert_not_found(); } #[test] fn following() { // TODO: Test anon requests as well? let (app, _, user) = TestApp::init().with_user(); app.db(|conn| { CrateBuilder::new("foo_following", user.as_model().id).expect_build(conn); }); let is_following = || -> bool { #[derive(Deserialize)] struct F { following: bool, } user.get::<F>("/api/v1/crates/foo_following/following") .good() .following }; let follow = || { assert!( user.put::<OkBool>("/api/v1/crates/foo_following/follow", b"") .good() .ok ); }; let unfollow = || { assert!( user.delete::<OkBool>("api/v1/crates/foo_following/follow") .good() .ok ); }; assert!(!is_following()); follow(); follow(); assert!(is_following()); assert_eq!(user.search("following=1").crates.len(), 1); unfollow(); unfollow(); assert!(!is_following()); assert_eq!(user.search("following=1").crates.len(), 0); }
23.066667
82
0.53396
ac8e30a535afc6d11332afc3a06701ffb7c0a257
237,581
//! Program state processor use crate::{ amount_to_ui_amount_string_trimmed, error::TokenError, instruction::{is_valid_signer_index, AuthorityType, TokenInstruction, MAX_SIGNERS}, state::{Account, AccountState, Mint, Multisig}, try_ui_amount_into_amount, }; use num_traits::FromPrimitive; use solana_program::{ account_info::{next_account_info, AccountInfo}, decode_error::DecodeError, entrypoint::ProgramResult, msg, program::set_return_data, program_error::{PrintProgramError, ProgramError}, program_memory::{sol_memcmp, sol_memset}, program_option::COption, program_pack::{IsInitialized, Pack}, pubkey::{Pubkey, PUBKEY_BYTES}, sysvar::{rent::Rent, Sysvar}, }; /// Program state handler. pub struct Processor {} impl Processor { fn _process_initialize_mint( accounts: &[AccountInfo], decimals: u8, mint_authority: Pubkey, freeze_authority: COption<Pubkey>, rent_sysvar_account: bool, ) -> ProgramResult { let account_info_iter = &mut accounts.iter(); let mint_info = next_account_info(account_info_iter)?; let mint_data_len = mint_info.data_len(); let rent = if rent_sysvar_account { Rent::from_account_info(next_account_info(account_info_iter)?)? } else { Rent::get()? }; let mut mint = Mint::unpack_unchecked(&mint_info.data.borrow())?; if mint.is_initialized { return Err(TokenError::AlreadyInUse.into()); } if !rent.is_exempt(mint_info.lamports(), mint_data_len) { return Err(TokenError::NotRentExempt.into()); } mint.mint_authority = COption::Some(mint_authority); mint.decimals = decimals; mint.is_initialized = true; mint.freeze_authority = freeze_authority; Mint::pack(mint, &mut mint_info.data.borrow_mut())?; Ok(()) } /// Processes an [InitializeMint](enum.TokenInstruction.html) instruction. pub fn process_initialize_mint( accounts: &[AccountInfo], decimals: u8, mint_authority: Pubkey, freeze_authority: COption<Pubkey>, ) -> ProgramResult { Self::_process_initialize_mint(accounts, decimals, mint_authority, freeze_authority, true) } /// Processes an [InitializeMint2](enum.TokenInstruction.html) instruction. pub fn process_initialize_mint2( accounts: &[AccountInfo], decimals: u8, mint_authority: Pubkey, freeze_authority: COption<Pubkey>, ) -> ProgramResult { Self::_process_initialize_mint(accounts, decimals, mint_authority, freeze_authority, false) } fn _process_initialize_account( program_id: &Pubkey, accounts: &[AccountInfo], owner: Option<&Pubkey>, rent_sysvar_account: bool, ) -> ProgramResult { let account_info_iter = &mut accounts.iter(); let new_account_info = next_account_info(account_info_iter)?; let mint_info = next_account_info(account_info_iter)?; let owner = if let Some(owner) = owner { owner } else { next_account_info(account_info_iter)?.key }; let new_account_info_data_len = new_account_info.data_len(); let rent = if rent_sysvar_account { Rent::from_account_info(next_account_info(account_info_iter)?)? } else { Rent::get()? }; let mut account = Account::unpack_unchecked(&new_account_info.data.borrow())?; if account.is_initialized() { return Err(TokenError::AlreadyInUse.into()); } if !rent.is_exempt(new_account_info.lamports(), new_account_info_data_len) { return Err(TokenError::NotRentExempt.into()); } let is_native_mint = Self::cmp_pubkeys(mint_info.key, &crate::native_mint::id()); if !is_native_mint { Self::check_account_owner(program_id, mint_info)?; let _ = Mint::unpack(&mint_info.data.borrow_mut()) .map_err(|_| Into::<ProgramError>::into(TokenError::InvalidMint))?; } account.mint = *mint_info.key; account.owner = *owner; account.close_authority = COption::None; account.delegate = COption::None; account.delegated_amount = 0; account.state = AccountState::Initialized; if is_native_mint { let rent_exempt_reserve = rent.minimum_balance(new_account_info_data_len); account.is_native = COption::Some(rent_exempt_reserve); account.amount = new_account_info .lamports() .checked_sub(rent_exempt_reserve) .ok_or(TokenError::Overflow)?; } else { account.is_native = COption::None; account.amount = 0; }; Account::pack(account, &mut new_account_info.data.borrow_mut())?; Ok(()) } /// Processes an [InitializeAccount](enum.TokenInstruction.html) instruction. pub fn process_initialize_account( program_id: &Pubkey, accounts: &[AccountInfo], ) -> ProgramResult { Self::_process_initialize_account(program_id, accounts, None, true) } /// Processes an [InitializeAccount2](enum.TokenInstruction.html) instruction. pub fn process_initialize_account2( program_id: &Pubkey, accounts: &[AccountInfo], owner: Pubkey, ) -> ProgramResult { Self::_process_initialize_account(program_id, accounts, Some(&owner), true) } /// Processes an [InitializeAccount3](enum.TokenInstruction.html) instruction. pub fn process_initialize_account3( program_id: &Pubkey, accounts: &[AccountInfo], owner: Pubkey, ) -> ProgramResult { Self::_process_initialize_account(program_id, accounts, Some(&owner), false) } fn _process_initialize_multisig( accounts: &[AccountInfo], m: u8, rent_sysvar_account: bool, ) -> ProgramResult { let account_info_iter = &mut accounts.iter(); let multisig_info = next_account_info(account_info_iter)?; let multisig_info_data_len = multisig_info.data_len(); let rent = if rent_sysvar_account { Rent::from_account_info(next_account_info(account_info_iter)?)? } else { Rent::get()? }; let mut multisig = Multisig::unpack_unchecked(&multisig_info.data.borrow())?; if multisig.is_initialized { return Err(TokenError::AlreadyInUse.into()); } if !rent.is_exempt(multisig_info.lamports(), multisig_info_data_len) { return Err(TokenError::NotRentExempt.into()); } let signer_infos = account_info_iter.as_slice(); multisig.m = m; multisig.n = signer_infos.len() as u8; if !is_valid_signer_index(multisig.n as usize) { return Err(TokenError::InvalidNumberOfProvidedSigners.into()); } if !is_valid_signer_index(multisig.m as usize) { return Err(TokenError::InvalidNumberOfRequiredSigners.into()); } for (i, signer_info) in signer_infos.iter().enumerate() { multisig.signers[i] = *signer_info.key; } multisig.is_initialized = true; Multisig::pack(multisig, &mut multisig_info.data.borrow_mut())?; Ok(()) } /// Processes a [InitializeMultisig](enum.TokenInstruction.html) instruction. pub fn process_initialize_multisig(accounts: &[AccountInfo], m: u8) -> ProgramResult { Self::_process_initialize_multisig(accounts, m, true) } /// Processes a [InitializeMultisig2](enum.TokenInstruction.html) instruction. pub fn process_initialize_multisig2(accounts: &[AccountInfo], m: u8) -> ProgramResult { Self::_process_initialize_multisig(accounts, m, false) } /// Processes a [Transfer](enum.TokenInstruction.html) instruction. pub fn process_transfer( program_id: &Pubkey, accounts: &[AccountInfo], amount: u64, expected_decimals: Option<u8>, ) -> ProgramResult { let account_info_iter = &mut accounts.iter(); let source_account_info = next_account_info(account_info_iter)?; let expected_mint_info = if let Some(expected_decimals) = expected_decimals { Some((next_account_info(account_info_iter)?, expected_decimals)) } else { None }; let destination_account_info = next_account_info(account_info_iter)?; let authority_info = next_account_info(account_info_iter)?; let mut source_account = Account::unpack(&source_account_info.data.borrow())?; let mut destination_account = Account::unpack(&destination_account_info.data.borrow())?; if source_account.is_frozen() || destination_account.is_frozen() { return Err(TokenError::AccountFrozen.into()); } if source_account.amount < amount { return Err(TokenError::InsufficientFunds.into()); } if !Self::cmp_pubkeys(&source_account.mint, &destination_account.mint) { return Err(TokenError::MintMismatch.into()); } if let Some((mint_info, expected_decimals)) = expected_mint_info { if !Self::cmp_pubkeys(mint_info.key, &source_account.mint) { return Err(TokenError::MintMismatch.into()); } let mint = Mint::unpack(&mint_info.data.borrow_mut())?; if expected_decimals != mint.decimals { return Err(TokenError::MintDecimalsMismatch.into()); } } let self_transfer = Self::cmp_pubkeys(source_account_info.key, destination_account_info.key); match source_account.delegate { COption::Some(ref delegate) if Self::cmp_pubkeys(authority_info.key, delegate) => { Self::validate_owner( program_id, delegate, authority_info, account_info_iter.as_slice(), )?; if source_account.delegated_amount < amount { return Err(TokenError::InsufficientFunds.into()); } if !self_transfer { source_account.delegated_amount = source_account .delegated_amount .checked_sub(amount) .ok_or(TokenError::Overflow)?; if source_account.delegated_amount == 0 { source_account.delegate = COption::None; } } } _ => Self::validate_owner( program_id, &source_account.owner, authority_info, account_info_iter.as_slice(), )?, }; if self_transfer || amount == 0 { Self::check_account_owner(program_id, source_account_info)?; Self::check_account_owner(program_id, destination_account_info)?; } // This check MUST occur just before the amounts are manipulated // to ensure self-transfers are fully validated if self_transfer { return Ok(()); } source_account.amount = source_account .amount .checked_sub(amount) .ok_or(TokenError::Overflow)?; destination_account.amount = destination_account .amount .checked_add(amount) .ok_or(TokenError::Overflow)?; if source_account.is_native() { let source_starting_lamports = source_account_info.lamports(); **source_account_info.lamports.borrow_mut() = source_starting_lamports .checked_sub(amount) .ok_or(TokenError::Overflow)?; let destination_starting_lamports = destination_account_info.lamports(); **destination_account_info.lamports.borrow_mut() = destination_starting_lamports .checked_add(amount) .ok_or(TokenError::Overflow)?; } Account::pack(source_account, &mut source_account_info.data.borrow_mut())?; Account::pack( destination_account, &mut destination_account_info.data.borrow_mut(), )?; Ok(()) } /// Processes an [Approve](enum.TokenInstruction.html) instruction. pub fn process_approve( program_id: &Pubkey, accounts: &[AccountInfo], amount: u64, expected_decimals: Option<u8>, ) -> ProgramResult { let account_info_iter = &mut accounts.iter(); let source_account_info = next_account_info(account_info_iter)?; let expected_mint_info = if let Some(expected_decimals) = expected_decimals { Some((next_account_info(account_info_iter)?, expected_decimals)) } else { None }; let delegate_info = next_account_info(account_info_iter)?; let owner_info = next_account_info(account_info_iter)?; let mut source_account = Account::unpack(&source_account_info.data.borrow())?; if source_account.is_frozen() { return Err(TokenError::AccountFrozen.into()); } if let Some((mint_info, expected_decimals)) = expected_mint_info { if !Self::cmp_pubkeys(mint_info.key, &source_account.mint) { return Err(TokenError::MintMismatch.into()); } let mint = Mint::unpack(&mint_info.data.borrow_mut())?; if expected_decimals != mint.decimals { return Err(TokenError::MintDecimalsMismatch.into()); } } Self::validate_owner( program_id, &source_account.owner, owner_info, account_info_iter.as_slice(), )?; source_account.delegate = COption::Some(*delegate_info.key); source_account.delegated_amount = amount; Account::pack(source_account, &mut source_account_info.data.borrow_mut())?; Ok(()) } /// Processes an [Revoke](enum.TokenInstruction.html) instruction. pub fn process_revoke(program_id: &Pubkey, accounts: &[AccountInfo]) -> ProgramResult { let account_info_iter = &mut accounts.iter(); let source_account_info = next_account_info(account_info_iter)?; let mut source_account = Account::unpack(&source_account_info.data.borrow())?; let owner_info = next_account_info(account_info_iter)?; if source_account.is_frozen() { return Err(TokenError::AccountFrozen.into()); } Self::validate_owner( program_id, &source_account.owner, owner_info, account_info_iter.as_slice(), )?; source_account.delegate = COption::None; source_account.delegated_amount = 0; Account::pack(source_account, &mut source_account_info.data.borrow_mut())?; Ok(()) } /// Processes a [SetAuthority](enum.TokenInstruction.html) instruction. pub fn process_set_authority( program_id: &Pubkey, accounts: &[AccountInfo], authority_type: AuthorityType, new_authority: COption<Pubkey>, ) -> ProgramResult { let account_info_iter = &mut accounts.iter(); let account_info = next_account_info(account_info_iter)?; let authority_info = next_account_info(account_info_iter)?; if account_info.data_len() == Account::get_packed_len() { let mut account = Account::unpack(&account_info.data.borrow())?; if account.is_frozen() { return Err(TokenError::AccountFrozen.into()); } match authority_type { AuthorityType::AccountOwner => { Self::validate_owner( program_id, &account.owner, authority_info, account_info_iter.as_slice(), )?; if let COption::Some(authority) = new_authority { account.owner = authority; } else { return Err(TokenError::InvalidInstruction.into()); } account.delegate = COption::None; account.delegated_amount = 0; if account.is_native() { account.close_authority = COption::None; } } AuthorityType::CloseAccount => { let authority = account.close_authority.unwrap_or(account.owner); Self::validate_owner( program_id, &authority, authority_info, account_info_iter.as_slice(), )?; account.close_authority = new_authority; } _ => { return Err(TokenError::AuthorityTypeNotSupported.into()); } } Account::pack(account, &mut account_info.data.borrow_mut())?; } else if account_info.data_len() == Mint::get_packed_len() { let mut mint = Mint::unpack(&account_info.data.borrow())?; match authority_type { AuthorityType::MintTokens => { // Once a mint's supply is fixed, it cannot be undone by setting a new // mint_authority let mint_authority = mint .mint_authority .ok_or(Into::<ProgramError>::into(TokenError::FixedSupply))?; Self::validate_owner( program_id, &mint_authority, authority_info, account_info_iter.as_slice(), )?; mint.mint_authority = new_authority; } AuthorityType::FreezeAccount => { // Once a mint's freeze authority is disabled, it cannot be re-enabled by // setting a new freeze_authority let freeze_authority = mint .freeze_authority .ok_or(Into::<ProgramError>::into(TokenError::MintCannotFreeze))?; Self::validate_owner( program_id, &freeze_authority, authority_info, account_info_iter.as_slice(), )?; mint.freeze_authority = new_authority; } _ => { return Err(TokenError::AuthorityTypeNotSupported.into()); } } Mint::pack(mint, &mut account_info.data.borrow_mut())?; } else { return Err(ProgramError::InvalidArgument); } Ok(()) } /// Processes a [MintTo](enum.TokenInstruction.html) instruction. pub fn process_mint_to( program_id: &Pubkey, accounts: &[AccountInfo], amount: u64, expected_decimals: Option<u8>, ) -> ProgramResult { let account_info_iter = &mut accounts.iter(); let mint_info = next_account_info(account_info_iter)?; let destination_account_info = next_account_info(account_info_iter)?; let owner_info = next_account_info(account_info_iter)?; let mut destination_account = Account::unpack(&destination_account_info.data.borrow())?; if destination_account.is_frozen() { return Err(TokenError::AccountFrozen.into()); } if destination_account.is_native() { return Err(TokenError::NativeNotSupported.into()); } if !Self::cmp_pubkeys(mint_info.key, &destination_account.mint) { return Err(TokenError::MintMismatch.into()); } let mut mint = Mint::unpack(&mint_info.data.borrow())?; if let Some(expected_decimals) = expected_decimals { if expected_decimals != mint.decimals { return Err(TokenError::MintDecimalsMismatch.into()); } } match mint.mint_authority { COption::Some(mint_authority) => Self::validate_owner( program_id, &mint_authority, owner_info, account_info_iter.as_slice(), )?, COption::None => return Err(TokenError::FixedSupply.into()), } if amount == 0 { Self::check_account_owner(program_id, mint_info)?; Self::check_account_owner(program_id, destination_account_info)?; } destination_account.amount = destination_account .amount .checked_add(amount) .ok_or(TokenError::Overflow)?; mint.supply = mint .supply .checked_add(amount) .ok_or(TokenError::Overflow)?; Account::pack( destination_account, &mut destination_account_info.data.borrow_mut(), )?; Mint::pack(mint, &mut mint_info.data.borrow_mut())?; Ok(()) } /// Processes a [Burn](enum.TokenInstruction.html) instruction. pub fn process_burn( program_id: &Pubkey, accounts: &[AccountInfo], amount: u64, expected_decimals: Option<u8>, ) -> ProgramResult { let account_info_iter = &mut accounts.iter(); let source_account_info = next_account_info(account_info_iter)?; let mint_info = next_account_info(account_info_iter)?; let authority_info = next_account_info(account_info_iter)?; let mut source_account = Account::unpack(&source_account_info.data.borrow())?; let mut mint = Mint::unpack(&mint_info.data.borrow())?; if source_account.is_frozen() { return Err(TokenError::AccountFrozen.into()); } if source_account.is_native() { return Err(TokenError::NativeNotSupported.into()); } if source_account.amount < amount { return Err(TokenError::InsufficientFunds.into()); } if !Self::cmp_pubkeys(mint_info.key, &source_account.mint) { return Err(TokenError::MintMismatch.into()); } if let Some(expected_decimals) = expected_decimals { if expected_decimals != mint.decimals { return Err(TokenError::MintDecimalsMismatch.into()); } } if !source_account.is_owned_by_system_program_or_incinerator() { match source_account.delegate { COption::Some(ref delegate) if Self::cmp_pubkeys(authority_info.key, delegate) => { Self::validate_owner( program_id, delegate, authority_info, account_info_iter.as_slice(), )?; if source_account.delegated_amount < amount { return Err(TokenError::InsufficientFunds.into()); } source_account.delegated_amount = source_account .delegated_amount .checked_sub(amount) .ok_or(TokenError::Overflow)?; if source_account.delegated_amount == 0 { source_account.delegate = COption::None; } } _ => Self::validate_owner( program_id, &source_account.owner, authority_info, account_info_iter.as_slice(), )?, } } if amount == 0 { Self::check_account_owner(program_id, source_account_info)?; Self::check_account_owner(program_id, mint_info)?; } source_account.amount = source_account .amount .checked_sub(amount) .ok_or(TokenError::Overflow)?; mint.supply = mint .supply .checked_sub(amount) .ok_or(TokenError::Overflow)?; Account::pack(source_account, &mut source_account_info.data.borrow_mut())?; Mint::pack(mint, &mut mint_info.data.borrow_mut())?; Ok(()) } /// Processes a [CloseAccount](enum.TokenInstruction.html) instruction. pub fn process_close_account(program_id: &Pubkey, accounts: &[AccountInfo]) -> ProgramResult { let account_info_iter = &mut accounts.iter(); let source_account_info = next_account_info(account_info_iter)?; let destination_account_info = next_account_info(account_info_iter)?; let authority_info = next_account_info(account_info_iter)?; if Self::cmp_pubkeys(source_account_info.key, destination_account_info.key) { return Err(ProgramError::InvalidAccountData); } let source_account = Account::unpack(&source_account_info.data.borrow())?; if !source_account.is_native() && source_account.amount != 0 { return Err(TokenError::NonNativeHasBalance.into()); } let authority = source_account .close_authority .unwrap_or(source_account.owner); if !source_account.is_owned_by_system_program_or_incinerator() { Self::validate_owner( program_id, &authority, authority_info, account_info_iter.as_slice(), )?; } else if !solana_program::incinerator::check_id(destination_account_info.key) { return Err(ProgramError::InvalidAccountData); } let destination_starting_lamports = destination_account_info.lamports(); **destination_account_info.lamports.borrow_mut() = destination_starting_lamports .checked_add(source_account_info.lamports()) .ok_or(TokenError::Overflow)?; **source_account_info.lamports.borrow_mut() = 0; sol_memset(*source_account_info.data.borrow_mut(), 0, Account::LEN); Ok(()) } /// Processes a [FreezeAccount](enum.TokenInstruction.html) or a /// [ThawAccount](enum.TokenInstruction.html) instruction. pub fn process_toggle_freeze_account( program_id: &Pubkey, accounts: &[AccountInfo], freeze: bool, ) -> ProgramResult { let account_info_iter = &mut accounts.iter(); let source_account_info = next_account_info(account_info_iter)?; let mint_info = next_account_info(account_info_iter)?; let authority_info = next_account_info(account_info_iter)?; let mut source_account = Account::unpack(&source_account_info.data.borrow())?; if freeze && source_account.is_frozen() || !freeze && !source_account.is_frozen() { return Err(TokenError::InvalidState.into()); } if source_account.is_native() { return Err(TokenError::NativeNotSupported.into()); } if !Self::cmp_pubkeys(mint_info.key, &source_account.mint) { return Err(TokenError::MintMismatch.into()); } let mint = Mint::unpack(&mint_info.data.borrow_mut())?; match mint.freeze_authority { COption::Some(authority) => Self::validate_owner( program_id, &authority, authority_info, account_info_iter.as_slice(), ), COption::None => Err(TokenError::MintCannotFreeze.into()), }?; source_account.state = if freeze { AccountState::Frozen } else { AccountState::Initialized }; Account::pack(source_account, &mut source_account_info.data.borrow_mut())?; Ok(()) } /// Processes a [SyncNative](enum.TokenInstruction.html) instruction pub fn process_sync_native(program_id: &Pubkey, accounts: &[AccountInfo]) -> ProgramResult { let account_info_iter = &mut accounts.iter(); let native_account_info = next_account_info(account_info_iter)?; Self::check_account_owner(program_id, native_account_info)?; let mut native_account = Account::unpack(&native_account_info.data.borrow())?; if let COption::Some(rent_exempt_reserve) = native_account.is_native { let new_amount = native_account_info .lamports() .checked_sub(rent_exempt_reserve) .ok_or(TokenError::Overflow)?; if new_amount < native_account.amount { return Err(TokenError::InvalidState.into()); } native_account.amount = new_amount; } else { return Err(TokenError::NonNativeNotSupported.into()); } Account::pack(native_account, &mut native_account_info.data.borrow_mut())?; Ok(()) } /// Processes a [GetAccountDataSize](enum.TokenInstruction.html) instruction pub fn process_get_account_data_size( program_id: &Pubkey, accounts: &[AccountInfo], ) -> ProgramResult { let account_info_iter = &mut accounts.iter(); // make sure the mint is valid let mint_info = next_account_info(account_info_iter)?; Self::check_account_owner(program_id, mint_info)?; let _ = Mint::unpack(&mint_info.data.borrow()) .map_err(|_| Into::<ProgramError>::into(TokenError::InvalidMint))?; set_return_data(&Account::LEN.to_le_bytes()); Ok(()) } /// Processes an [InitializeImmutableOwner](enum.TokenInstruction.html) instruction pub fn process_initialize_immutable_owner(accounts: &[AccountInfo]) -> ProgramResult { let account_info_iter = &mut accounts.iter(); let token_account_info = next_account_info(account_info_iter)?; let account = Account::unpack_unchecked(&token_account_info.data.borrow())?; if account.is_initialized() { return Err(TokenError::AlreadyInUse.into()); } msg!("Please upgrade to SPL Token 2022 for immutable owner support"); Ok(()) } /// Processes an [AmountToUiAmount](enum.TokenInstruction.html) instruction pub fn process_amount_to_ui_amount( program_id: &Pubkey, accounts: &[AccountInfo], amount: u64, ) -> ProgramResult { let account_info_iter = &mut accounts.iter(); let mint_info = next_account_info(account_info_iter)?; Self::check_account_owner(program_id, mint_info)?; let mint = Mint::unpack(&mint_info.data.borrow_mut()) .map_err(|_| Into::<ProgramError>::into(TokenError::InvalidMint))?; let ui_amount = amount_to_ui_amount_string_trimmed(amount, mint.decimals); set_return_data(&ui_amount.into_bytes()); Ok(()) } /// Processes an [AmountToUiAmount](enum.TokenInstruction.html) instruction pub fn process_ui_amount_to_amount( program_id: &Pubkey, accounts: &[AccountInfo], ui_amount: &str, ) -> ProgramResult { let account_info_iter = &mut accounts.iter(); let mint_info = next_account_info(account_info_iter)?; Self::check_account_owner(program_id, mint_info)?; let mint = Mint::unpack(&mint_info.data.borrow_mut()) .map_err(|_| Into::<ProgramError>::into(TokenError::InvalidMint))?; let amount = try_ui_amount_into_amount(ui_amount.to_string(), mint.decimals)?; set_return_data(&amount.to_le_bytes()); Ok(()) } /// Processes an [Instruction](enum.Instruction.html). pub fn process(program_id: &Pubkey, accounts: &[AccountInfo], input: &[u8]) -> ProgramResult { let instruction = TokenInstruction::unpack(input)?; match instruction { TokenInstruction::InitializeMint { decimals, mint_authority, freeze_authority, } => { msg!("Instruction: InitializeMint"); Self::process_initialize_mint(accounts, decimals, mint_authority, freeze_authority) } TokenInstruction::InitializeMint2 { decimals, mint_authority, freeze_authority, } => { msg!("Instruction: InitializeMint2"); Self::process_initialize_mint2(accounts, decimals, mint_authority, freeze_authority) } TokenInstruction::InitializeAccount => { msg!("Instruction: InitializeAccount"); Self::process_initialize_account(program_id, accounts) } TokenInstruction::InitializeAccount2 { owner } => { msg!("Instruction: InitializeAccount2"); Self::process_initialize_account2(program_id, accounts, owner) } TokenInstruction::InitializeAccount3 { owner } => { msg!("Instruction: InitializeAccount3"); Self::process_initialize_account3(program_id, accounts, owner) } TokenInstruction::InitializeMultisig { m } => { msg!("Instruction: InitializeMultisig"); Self::process_initialize_multisig(accounts, m) } TokenInstruction::InitializeMultisig2 { m } => { msg!("Instruction: InitializeMultisig2"); Self::process_initialize_multisig2(accounts, m) } TokenInstruction::Transfer { amount } => { msg!("Instruction: Transfer"); Self::process_transfer(program_id, accounts, amount, None) } TokenInstruction::Approve { amount } => { msg!("Instruction: Approve"); Self::process_approve(program_id, accounts, amount, None) } TokenInstruction::Revoke => { msg!("Instruction: Revoke"); Self::process_revoke(program_id, accounts) } TokenInstruction::SetAuthority { authority_type, new_authority, } => { msg!("Instruction: SetAuthority"); Self::process_set_authority(program_id, accounts, authority_type, new_authority) } TokenInstruction::MintTo { amount } => { msg!("Instruction: MintTo"); Self::process_mint_to(program_id, accounts, amount, None) } TokenInstruction::Burn { amount } => { msg!("Instruction: Burn"); Self::process_burn(program_id, accounts, amount, None) } TokenInstruction::CloseAccount => { msg!("Instruction: CloseAccount"); Self::process_close_account(program_id, accounts) } TokenInstruction::FreezeAccount => { msg!("Instruction: FreezeAccount"); Self::process_toggle_freeze_account(program_id, accounts, true) } TokenInstruction::ThawAccount => { msg!("Instruction: ThawAccount"); Self::process_toggle_freeze_account(program_id, accounts, false) } TokenInstruction::TransferChecked { amount, decimals } => { msg!("Instruction: TransferChecked"); Self::process_transfer(program_id, accounts, amount, Some(decimals)) } TokenInstruction::ApproveChecked { amount, decimals } => { msg!("Instruction: ApproveChecked"); Self::process_approve(program_id, accounts, amount, Some(decimals)) } TokenInstruction::MintToChecked { amount, decimals } => { msg!("Instruction: MintToChecked"); Self::process_mint_to(program_id, accounts, amount, Some(decimals)) } TokenInstruction::BurnChecked { amount, decimals } => { msg!("Instruction: BurnChecked"); Self::process_burn(program_id, accounts, amount, Some(decimals)) } TokenInstruction::SyncNative => { msg!("Instruction: SyncNative"); Self::process_sync_native(program_id, accounts) } TokenInstruction::GetAccountDataSize => { msg!("Instruction: GetAccountDataSize"); Self::process_get_account_data_size(program_id, accounts) } TokenInstruction::InitializeImmutableOwner => { msg!("Instruction: InitializeImmutableOwner"); Self::process_initialize_immutable_owner(accounts) } TokenInstruction::AmountToUiAmount { amount } => { msg!("Instruction: AmountToUiAmount"); Self::process_amount_to_ui_amount(program_id, accounts, amount) } TokenInstruction::UiAmountToAmount { ui_amount } => { msg!("Instruction: UiAmountToAmount"); Self::process_ui_amount_to_amount(program_id, accounts, ui_amount) } } } /// Checks that the account is owned by the expected program pub fn check_account_owner(program_id: &Pubkey, account_info: &AccountInfo) -> ProgramResult { if !Self::cmp_pubkeys(program_id, account_info.owner) { Err(ProgramError::IncorrectProgramId) } else { Ok(()) } } /// Checks two pubkeys for equality in a computationally cheap way using /// `sol_memcmp` pub fn cmp_pubkeys(a: &Pubkey, b: &Pubkey) -> bool { sol_memcmp(a.as_ref(), b.as_ref(), PUBKEY_BYTES) == 0 } /// Validates owner(s) are present pub fn validate_owner( program_id: &Pubkey, expected_owner: &Pubkey, owner_account_info: &AccountInfo, signers: &[AccountInfo], ) -> ProgramResult { if !Self::cmp_pubkeys(expected_owner, owner_account_info.key) { return Err(TokenError::OwnerMismatch.into()); } if Self::cmp_pubkeys(program_id, owner_account_info.owner) && owner_account_info.data_len() == Multisig::get_packed_len() { let multisig = Multisig::unpack(&owner_account_info.data.borrow())?; let mut num_signers = 0; let mut matched = [false; MAX_SIGNERS]; for signer in signers.iter() { for (position, key) in multisig.signers[0..multisig.n as usize].iter().enumerate() { if Self::cmp_pubkeys(key, signer.key) && !matched[position] { if !signer.is_signer { return Err(ProgramError::MissingRequiredSignature); } matched[position] = true; num_signers += 1; } } } if num_signers < multisig.m { return Err(ProgramError::MissingRequiredSignature); } return Ok(()); } else if !owner_account_info.is_signer { return Err(ProgramError::MissingRequiredSignature); } Ok(()) } } impl PrintProgramError for TokenError { fn print<E>(&self) where E: 'static + std::error::Error + DecodeError<E> + PrintProgramError + FromPrimitive, { match self { TokenError::NotRentExempt => msg!("Error: Lamport balance below rent-exempt threshold"), TokenError::InsufficientFunds => msg!("Error: insufficient funds"), TokenError::InvalidMint => msg!("Error: Invalid Mint"), TokenError::MintMismatch => msg!("Error: Account not associated with this Mint"), TokenError::OwnerMismatch => msg!("Error: owner does not match"), TokenError::FixedSupply => msg!("Error: the total supply of this token is fixed"), TokenError::AlreadyInUse => msg!("Error: account or token already in use"), TokenError::InvalidNumberOfProvidedSigners => { msg!("Error: Invalid number of provided signers") } TokenError::InvalidNumberOfRequiredSigners => { msg!("Error: Invalid number of required signers") } TokenError::UninitializedState => msg!("Error: State is uninitialized"), TokenError::NativeNotSupported => { msg!("Error: Instruction does not support native tokens") } TokenError::NonNativeHasBalance => { msg!("Error: Non-native account can only be closed if its balance is zero") } TokenError::InvalidInstruction => msg!("Error: Invalid instruction"), TokenError::InvalidState => msg!("Error: Invalid account state for operation"), TokenError::Overflow => msg!("Error: Operation overflowed"), TokenError::AuthorityTypeNotSupported => { msg!("Error: Account does not support specified authority type") } TokenError::MintCannotFreeze => msg!("Error: This token mint cannot freeze accounts"), TokenError::AccountFrozen => msg!("Error: Account is frozen"), TokenError::MintDecimalsMismatch => { msg!("Error: decimals different from the Mint decimals") } TokenError::NonNativeNotSupported => { msg!("Error: Instruction does not support non-native tokens") } } } } #[cfg(test)] mod tests { use super::*; use crate::instruction::*; use serial_test::serial; use solana_program::{ account_info::IntoAccountInfo, clock::Epoch, instruction::Instruction, program_error, sysvar::rent, }; use solana_sdk::account::{ create_account_for_test, create_is_signer_account_infos, Account as SolanaAccount, }; use std::sync::{Arc, RwLock}; lazy_static::lazy_static! { static ref EXPECTED_DATA: Arc<RwLock<Vec<u8>>> = Arc::new(RwLock::new(Vec::new())); } fn set_expected_data(expected_data: Vec<u8>) { *EXPECTED_DATA.write().unwrap() = expected_data; } struct SyscallStubs {} impl solana_sdk::program_stubs::SyscallStubs for SyscallStubs { fn sol_log(&self, _message: &str) {} fn sol_invoke_signed( &self, _instruction: &Instruction, _account_infos: &[AccountInfo], _signers_seeds: &[&[&[u8]]], ) -> ProgramResult { Err(ProgramError::Custom(42)) // Not supported } fn sol_get_clock_sysvar(&self, _var_addr: *mut u8) -> u64 { program_error::UNSUPPORTED_SYSVAR } fn sol_get_epoch_schedule_sysvar(&self, _var_addr: *mut u8) -> u64 { program_error::UNSUPPORTED_SYSVAR } #[allow(deprecated)] fn sol_get_fees_sysvar(&self, _var_addr: *mut u8) -> u64 { program_error::UNSUPPORTED_SYSVAR } fn sol_get_rent_sysvar(&self, var_addr: *mut u8) -> u64 { unsafe { *(var_addr as *mut _ as *mut Rent) = Rent::default(); } solana_program::entrypoint::SUCCESS } fn sol_set_return_data(&self, data: &[u8]) { assert_eq!(&*EXPECTED_DATA.write().unwrap(), data) } } fn do_process_instruction( instruction: Instruction, accounts: Vec<&mut SolanaAccount>, ) -> ProgramResult { { use std::sync::Once; static ONCE: Once = Once::new(); ONCE.call_once(|| { solana_sdk::program_stubs::set_syscall_stubs(Box::new(SyscallStubs {})); }); } let mut meta = instruction .accounts .iter() .zip(accounts) .map(|(account_meta, account)| (&account_meta.pubkey, account_meta.is_signer, account)) .collect::<Vec<_>>(); let account_infos = create_is_signer_account_infos(&mut meta); Processor::process(&instruction.program_id, &account_infos, &instruction.data) } fn do_process_instruction_dups( instruction: Instruction, account_infos: Vec<AccountInfo>, ) -> ProgramResult { Processor::process(&instruction.program_id, &account_infos, &instruction.data) } fn return_token_error_as_program_error() -> ProgramError { TokenError::MintMismatch.into() } fn rent_sysvar() -> SolanaAccount { create_account_for_test(&Rent::default()) } fn mint_minimum_balance() -> u64 { Rent::default().minimum_balance(Mint::get_packed_len()) } fn account_minimum_balance() -> u64 { Rent::default().minimum_balance(Account::get_packed_len()) } fn multisig_minimum_balance() -> u64 { Rent::default().minimum_balance(Multisig::get_packed_len()) } #[test] fn test_print_error() { let error = return_token_error_as_program_error(); error.print::<TokenError>(); } #[test] #[should_panic(expected = "Custom(3)")] fn test_error_unwrap() { Err::<(), ProgramError>(return_token_error_as_program_error()).unwrap(); } #[test] fn test_unique_account_sizes() { assert_ne!(Mint::get_packed_len(), 0); assert_ne!(Mint::get_packed_len(), Account::get_packed_len()); assert_ne!(Mint::get_packed_len(), Multisig::get_packed_len()); assert_ne!(Account::get_packed_len(), 0); assert_ne!(Account::get_packed_len(), Multisig::get_packed_len()); assert_ne!(Multisig::get_packed_len(), 0); } #[test] fn test_pack_unpack() { // Mint let check = Mint { mint_authority: COption::Some(Pubkey::new(&[1; 32])), supply: 42, decimals: 7, is_initialized: true, freeze_authority: COption::Some(Pubkey::new(&[2; 32])), }; let mut packed = vec![0; Mint::get_packed_len() + 1]; assert_eq!( Err(ProgramError::InvalidAccountData), Mint::pack(check, &mut packed) ); let mut packed = vec![0; Mint::get_packed_len() - 1]; assert_eq!( Err(ProgramError::InvalidAccountData), Mint::pack(check, &mut packed) ); let mut packed = vec![0; Mint::get_packed_len()]; Mint::pack(check, &mut packed).unwrap(); let expect = vec![ 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 42, 0, 0, 0, 0, 0, 0, 0, 7, 1, 1, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, ]; assert_eq!(packed, expect); let unpacked = Mint::unpack(&packed).unwrap(); assert_eq!(unpacked, check); // Account let check = Account { mint: Pubkey::new(&[1; 32]), owner: Pubkey::new(&[2; 32]), amount: 3, delegate: COption::Some(Pubkey::new(&[4; 32])), state: AccountState::Frozen, is_native: COption::Some(5), delegated_amount: 6, close_authority: COption::Some(Pubkey::new(&[7; 32])), }; let mut packed = vec![0; Account::get_packed_len() + 1]; assert_eq!( Err(ProgramError::InvalidAccountData), Account::pack(check, &mut packed) ); let mut packed = vec![0; Account::get_packed_len() - 1]; assert_eq!( Err(ProgramError::InvalidAccountData), Account::pack(check, &mut packed) ); let mut packed = vec![0; Account::get_packed_len()]; Account::pack(check, &mut packed).unwrap(); let expect = vec![ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 1, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, ]; assert_eq!(packed, expect); let unpacked = Account::unpack(&packed).unwrap(); assert_eq!(unpacked, check); // Multisig let check = Multisig { m: 1, n: 2, is_initialized: true, signers: [Pubkey::new(&[3; 32]); MAX_SIGNERS], }; let mut packed = vec![0; Multisig::get_packed_len() + 1]; assert_eq!( Err(ProgramError::InvalidAccountData), Multisig::pack(check, &mut packed) ); let mut packed = vec![0; Multisig::get_packed_len() - 1]; assert_eq!( Err(ProgramError::InvalidAccountData), Multisig::pack(check, &mut packed) ); let mut packed = vec![0; Multisig::get_packed_len()]; Multisig::pack(check, &mut packed).unwrap(); let expect = vec![ 1, 2, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, ]; assert_eq!(packed, expect); let unpacked = Multisig::unpack(&packed).unwrap(); assert_eq!(unpacked, check); } #[test] fn test_initialize_mint() { let program_id = crate::id(); let owner_key = Pubkey::new_unique(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(42, Mint::get_packed_len(), &program_id); let mint2_key = Pubkey::new_unique(); let mut mint2_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let mut rent_sysvar = rent_sysvar(); // mint is not rent exempt assert_eq!( Err(TokenError::NotRentExempt.into()), do_process_instruction( initialize_mint(&program_id, &mint_key, &owner_key, None, 2).unwrap(), vec![&mut mint_account, &mut rent_sysvar] ) ); mint_account.lamports = mint_minimum_balance(); // create new mint do_process_instruction( initialize_mint(&program_id, &mint_key, &owner_key, None, 2).unwrap(), vec![&mut mint_account, &mut rent_sysvar], ) .unwrap(); // create twice assert_eq!( Err(TokenError::AlreadyInUse.into()), do_process_instruction( initialize_mint(&program_id, &mint_key, &owner_key, None, 2,).unwrap(), vec![&mut mint_account, &mut rent_sysvar] ) ); // create another mint that can freeze do_process_instruction( initialize_mint(&program_id, &mint2_key, &owner_key, Some(&owner_key), 2).unwrap(), vec![&mut mint2_account, &mut rent_sysvar], ) .unwrap(); let mint = Mint::unpack_unchecked(&mint2_account.data).unwrap(); assert_eq!(mint.freeze_authority, COption::Some(owner_key)); } #[test] fn test_initialize_mint2() { let program_id = crate::id(); let owner_key = Pubkey::new_unique(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(42, Mint::get_packed_len(), &program_id); let mint2_key = Pubkey::new_unique(); let mut mint2_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); // mint is not rent exempt assert_eq!( Err(TokenError::NotRentExempt.into()), do_process_instruction( initialize_mint2(&program_id, &mint_key, &owner_key, None, 2).unwrap(), vec![&mut mint_account] ) ); mint_account.lamports = mint_minimum_balance(); // create new mint do_process_instruction( initialize_mint2(&program_id, &mint_key, &owner_key, None, 2).unwrap(), vec![&mut mint_account], ) .unwrap(); // create twice assert_eq!( Err(TokenError::AlreadyInUse.into()), do_process_instruction( initialize_mint2(&program_id, &mint_key, &owner_key, None, 2,).unwrap(), vec![&mut mint_account] ) ); // create another mint that can freeze do_process_instruction( initialize_mint2(&program_id, &mint2_key, &owner_key, Some(&owner_key), 2).unwrap(), vec![&mut mint2_account], ) .unwrap(); let mint = Mint::unpack_unchecked(&mint2_account.data).unwrap(); assert_eq!(mint.freeze_authority, COption::Some(owner_key)); } #[test] fn test_initialize_mint_account() { let program_id = crate::id(); let account_key = Pubkey::new_unique(); let mut account_account = SolanaAccount::new(42, Account::get_packed_len(), &program_id); let owner_key = Pubkey::new_unique(); let mut owner_account = SolanaAccount::default(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let mut rent_sysvar = rent_sysvar(); // account is not rent exempt assert_eq!( Err(TokenError::NotRentExempt.into()), do_process_instruction( initialize_account(&program_id, &account_key, &mint_key, &owner_key).unwrap(), vec![ &mut account_account, &mut mint_account, &mut owner_account, &mut rent_sysvar ], ) ); account_account.lamports = account_minimum_balance(); // mint is not valid (not initialized) assert_eq!( Err(TokenError::InvalidMint.into()), do_process_instruction( initialize_account(&program_id, &account_key, &mint_key, &owner_key).unwrap(), vec![ &mut account_account, &mut mint_account, &mut owner_account, &mut rent_sysvar ], ) ); // create mint do_process_instruction( initialize_mint(&program_id, &mint_key, &owner_key, None, 2).unwrap(), vec![&mut mint_account, &mut rent_sysvar], ) .unwrap(); // mint not owned by program let not_program_id = Pubkey::new_unique(); mint_account.owner = not_program_id; assert_eq!( Err(ProgramError::IncorrectProgramId), do_process_instruction( initialize_account(&program_id, &account_key, &mint_key, &owner_key).unwrap(), vec![ &mut account_account, &mut mint_account, &mut owner_account, &mut rent_sysvar ], ) ); mint_account.owner = program_id; // create account do_process_instruction( initialize_account(&program_id, &account_key, &mint_key, &owner_key).unwrap(), vec![ &mut account_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); // create twice assert_eq!( Err(TokenError::AlreadyInUse.into()), do_process_instruction( initialize_account(&program_id, &account_key, &mint_key, &owner_key).unwrap(), vec![ &mut account_account, &mut mint_account, &mut owner_account, &mut rent_sysvar ], ) ); } #[test] fn test_transfer_dups() { let program_id = crate::id(); let account1_key = Pubkey::new_unique(); let mut account1_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let mut account1_info: AccountInfo = (&account1_key, true, &mut account1_account).into(); let account2_key = Pubkey::new_unique(); let mut account2_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let mut account2_info: AccountInfo = (&account2_key, false, &mut account2_account).into(); let account3_key = Pubkey::new_unique(); let mut account3_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let account3_info: AccountInfo = (&account3_key, false, &mut account3_account).into(); let account4_key = Pubkey::new_unique(); let mut account4_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let account4_info: AccountInfo = (&account4_key, true, &mut account4_account).into(); let multisig_key = Pubkey::new_unique(); let mut multisig_account = SolanaAccount::new( multisig_minimum_balance(), Multisig::get_packed_len(), &program_id, ); let multisig_info: AccountInfo = (&multisig_key, true, &mut multisig_account).into(); let owner_key = Pubkey::new_unique(); let mut owner_account = SolanaAccount::default(); let owner_info: AccountInfo = (&owner_key, true, &mut owner_account).into(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let mint_info: AccountInfo = (&mint_key, false, &mut mint_account).into(); let rent_key = rent::id(); let mut rent_sysvar = rent_sysvar(); let rent_info: AccountInfo = (&rent_key, false, &mut rent_sysvar).into(); // create mint do_process_instruction_dups( initialize_mint(&program_id, &mint_key, &owner_key, None, 2).unwrap(), vec![mint_info.clone(), rent_info.clone()], ) .unwrap(); // create account do_process_instruction_dups( initialize_account(&program_id, &account1_key, &mint_key, &account1_key).unwrap(), vec![ account1_info.clone(), mint_info.clone(), account1_info.clone(), rent_info.clone(), ], ) .unwrap(); // create another account do_process_instruction_dups( initialize_account(&program_id, &account2_key, &mint_key, &owner_key).unwrap(), vec![ account2_info.clone(), mint_info.clone(), owner_info.clone(), rent_info.clone(), ], ) .unwrap(); // mint to account do_process_instruction_dups( mint_to(&program_id, &mint_key, &account1_key, &owner_key, &[], 1000).unwrap(), vec![mint_info.clone(), account1_info.clone(), owner_info.clone()], ) .unwrap(); // source-owner transfer do_process_instruction_dups( transfer( &program_id, &account1_key, &account2_key, &account1_key, &[], 500, ) .unwrap(), vec![ account1_info.clone(), account2_info.clone(), account1_info.clone(), ], ) .unwrap(); // source-owner TransferChecked do_process_instruction_dups( transfer_checked( &program_id, &account1_key, &mint_key, &account2_key, &account1_key, &[], 500, 2, ) .unwrap(), vec![ account1_info.clone(), mint_info.clone(), account2_info.clone(), account1_info.clone(), ], ) .unwrap(); // source-delegate transfer let mut account = Account::unpack_unchecked(&account1_info.data.borrow()).unwrap(); account.amount = 1000; account.delegated_amount = 1000; account.delegate = COption::Some(account1_key); account.owner = owner_key; Account::pack(account, &mut account1_info.data.borrow_mut()).unwrap(); do_process_instruction_dups( transfer( &program_id, &account1_key, &account2_key, &account1_key, &[], 500, ) .unwrap(), vec![ account1_info.clone(), account2_info.clone(), account1_info.clone(), ], ) .unwrap(); // source-delegate TransferChecked do_process_instruction_dups( transfer_checked( &program_id, &account1_key, &mint_key, &account2_key, &account1_key, &[], 500, 2, ) .unwrap(), vec![ account1_info.clone(), mint_info.clone(), account2_info.clone(), account1_info.clone(), ], ) .unwrap(); // test destination-owner transfer do_process_instruction_dups( initialize_account(&program_id, &account3_key, &mint_key, &account2_key).unwrap(), vec![ account3_info.clone(), mint_info.clone(), account2_info.clone(), rent_info.clone(), ], ) .unwrap(); do_process_instruction_dups( mint_to(&program_id, &mint_key, &account3_key, &owner_key, &[], 1000).unwrap(), vec![mint_info.clone(), account3_info.clone(), owner_info.clone()], ) .unwrap(); account1_info.is_signer = false; account2_info.is_signer = true; do_process_instruction_dups( transfer( &program_id, &account3_key, &account2_key, &account2_key, &[], 500, ) .unwrap(), vec![ account3_info.clone(), account2_info.clone(), account2_info.clone(), ], ) .unwrap(); // destination-owner TransferChecked do_process_instruction_dups( transfer_checked( &program_id, &account3_key, &mint_key, &account2_key, &account2_key, &[], 500, 2, ) .unwrap(), vec![ account3_info.clone(), mint_info.clone(), account2_info.clone(), account2_info.clone(), ], ) .unwrap(); // test source-multisig signer do_process_instruction_dups( initialize_multisig(&program_id, &multisig_key, &[&account4_key], 1).unwrap(), vec![ multisig_info.clone(), rent_info.clone(), account4_info.clone(), ], ) .unwrap(); do_process_instruction_dups( initialize_account(&program_id, &account4_key, &mint_key, &multisig_key).unwrap(), vec![ account4_info.clone(), mint_info.clone(), multisig_info.clone(), rent_info.clone(), ], ) .unwrap(); do_process_instruction_dups( mint_to(&program_id, &mint_key, &account4_key, &owner_key, &[], 1000).unwrap(), vec![mint_info.clone(), account4_info.clone(), owner_info.clone()], ) .unwrap(); // source-multisig-signer transfer do_process_instruction_dups( transfer( &program_id, &account4_key, &account2_key, &multisig_key, &[&account4_key], 500, ) .unwrap(), vec![ account4_info.clone(), account2_info.clone(), multisig_info.clone(), account4_info.clone(), ], ) .unwrap(); // source-multisig-signer TransferChecked do_process_instruction_dups( transfer_checked( &program_id, &account4_key, &mint_key, &account2_key, &multisig_key, &[&account4_key], 500, 2, ) .unwrap(), vec![ account4_info.clone(), mint_info.clone(), account2_info.clone(), multisig_info.clone(), account4_info.clone(), ], ) .unwrap(); } #[test] fn test_transfer() { let program_id = crate::id(); let account_key = Pubkey::new_unique(); let mut account_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let account2_key = Pubkey::new_unique(); let mut account2_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let account3_key = Pubkey::new_unique(); let mut account3_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let delegate_key = Pubkey::new_unique(); let mut delegate_account = SolanaAccount::default(); let mismatch_key = Pubkey::new_unique(); let mut mismatch_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let owner_key = Pubkey::new_unique(); let mut owner_account = SolanaAccount::default(); let owner2_key = Pubkey::new_unique(); let mut owner2_account = SolanaAccount::default(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let mint2_key = Pubkey::new_unique(); let mut rent_sysvar = rent_sysvar(); // create mint do_process_instruction( initialize_mint(&program_id, &mint_key, &owner_key, None, 2).unwrap(), vec![&mut mint_account, &mut rent_sysvar], ) .unwrap(); // create account do_process_instruction( initialize_account(&program_id, &account_key, &mint_key, &owner_key).unwrap(), vec![ &mut account_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); // create another account do_process_instruction( initialize_account(&program_id, &account2_key, &mint_key, &owner_key).unwrap(), vec![ &mut account2_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); // create another account do_process_instruction( initialize_account(&program_id, &account3_key, &mint_key, &owner_key).unwrap(), vec![ &mut account3_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); // create mismatch account do_process_instruction( initialize_account(&program_id, &mismatch_key, &mint_key, &owner_key).unwrap(), vec![ &mut mismatch_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); let mut account = Account::unpack_unchecked(&mismatch_account.data).unwrap(); account.mint = mint2_key; Account::pack(account, &mut mismatch_account.data).unwrap(); // mint to account do_process_instruction( mint_to(&program_id, &mint_key, &account_key, &owner_key, &[], 1000).unwrap(), vec![&mut mint_account, &mut account_account, &mut owner_account], ) .unwrap(); // missing signer let mut instruction = transfer( &program_id, &account_key, &account2_key, &owner_key, &[], 1000, ) .unwrap(); instruction.accounts[2].is_signer = false; assert_eq!( Err(ProgramError::MissingRequiredSignature), do_process_instruction( instruction, vec![ &mut account_account, &mut account2_account, &mut owner_account, ], ) ); // mismatch mint assert_eq!( Err(TokenError::MintMismatch.into()), do_process_instruction( transfer( &program_id, &account_key, &mismatch_key, &owner_key, &[], 1000 ) .unwrap(), vec![ &mut account_account, &mut mismatch_account, &mut owner_account, ], ) ); // missing owner assert_eq!( Err(TokenError::OwnerMismatch.into()), do_process_instruction( transfer( &program_id, &account_key, &account2_key, &owner2_key, &[], 1000 ) .unwrap(), vec![ &mut account_account, &mut account2_account, &mut owner2_account, ], ) ); // account not owned by program let not_program_id = Pubkey::new_unique(); account_account.owner = not_program_id; assert_eq!( Err(ProgramError::IncorrectProgramId), do_process_instruction( transfer(&program_id, &account_key, &account2_key, &owner_key, &[], 0,).unwrap(), vec![ &mut account_account, &mut account2_account, &mut owner2_account, ], ) ); account_account.owner = program_id; // account 2 not owned by program let not_program_id = Pubkey::new_unique(); account2_account.owner = not_program_id; assert_eq!( Err(ProgramError::IncorrectProgramId), do_process_instruction( transfer(&program_id, &account_key, &account2_key, &owner_key, &[], 0,).unwrap(), vec![ &mut account_account, &mut account2_account, &mut owner2_account, ], ) ); account2_account.owner = program_id; // transfer do_process_instruction( transfer( &program_id, &account_key, &account2_key, &owner_key, &[], 1000, ) .unwrap(), vec![ &mut account_account, &mut account2_account, &mut owner_account, ], ) .unwrap(); // insufficient funds assert_eq!( Err(TokenError::InsufficientFunds.into()), do_process_instruction( transfer(&program_id, &account_key, &account2_key, &owner_key, &[], 1).unwrap(), vec![ &mut account_account, &mut account2_account, &mut owner_account, ], ) ); // transfer half back do_process_instruction( transfer( &program_id, &account2_key, &account_key, &owner_key, &[], 500, ) .unwrap(), vec![ &mut account2_account, &mut account_account, &mut owner_account, ], ) .unwrap(); // incorrect decimals assert_eq!( Err(TokenError::MintDecimalsMismatch.into()), do_process_instruction( transfer_checked( &program_id, &account2_key, &mint_key, &account_key, &owner_key, &[], 1, 10 // <-- incorrect decimals ) .unwrap(), vec![ &mut account2_account, &mut mint_account, &mut account_account, &mut owner_account, ], ) ); // incorrect mint assert_eq!( Err(TokenError::MintMismatch.into()), do_process_instruction( transfer_checked( &program_id, &account2_key, &account3_key, // <-- incorrect mint &account_key, &owner_key, &[], 1, 2 ) .unwrap(), vec![ &mut account2_account, &mut account3_account, // <-- incorrect mint &mut account_account, &mut owner_account, ], ) ); // transfer rest with explicit decimals do_process_instruction( transfer_checked( &program_id, &account2_key, &mint_key, &account_key, &owner_key, &[], 500, 2, ) .unwrap(), vec![ &mut account2_account, &mut mint_account, &mut account_account, &mut owner_account, ], ) .unwrap(); // insufficient funds assert_eq!( Err(TokenError::InsufficientFunds.into()), do_process_instruction( transfer(&program_id, &account2_key, &account_key, &owner_key, &[], 1).unwrap(), vec![ &mut account2_account, &mut account_account, &mut owner_account, ], ) ); // approve delegate do_process_instruction( approve( &program_id, &account_key, &delegate_key, &owner_key, &[], 100, ) .unwrap(), vec![ &mut account_account, &mut delegate_account, &mut owner_account, ], ) .unwrap(); // transfer via delegate do_process_instruction( transfer( &program_id, &account_key, &account2_key, &delegate_key, &[], 100, ) .unwrap(), vec![ &mut account_account, &mut account2_account, &mut delegate_account, ], ) .unwrap(); // insufficient funds approved via delegate assert_eq!( Err(TokenError::OwnerMismatch.into()), do_process_instruction( transfer( &program_id, &account_key, &account2_key, &delegate_key, &[], 100 ) .unwrap(), vec![ &mut account_account, &mut account2_account, &mut delegate_account, ], ) ); // transfer rest do_process_instruction( transfer( &program_id, &account_key, &account2_key, &owner_key, &[], 900, ) .unwrap(), vec![ &mut account_account, &mut account2_account, &mut owner_account, ], ) .unwrap(); // approve delegate do_process_instruction( approve( &program_id, &account_key, &delegate_key, &owner_key, &[], 100, ) .unwrap(), vec![ &mut account_account, &mut delegate_account, &mut owner_account, ], ) .unwrap(); // insufficient funds in source account via delegate assert_eq!( Err(TokenError::InsufficientFunds.into()), do_process_instruction( transfer( &program_id, &account_key, &account2_key, &delegate_key, &[], 100 ) .unwrap(), vec![ &mut account_account, &mut account2_account, &mut delegate_account, ], ) ); } #[test] fn test_self_transfer() { let program_id = crate::id(); let account_key = Pubkey::new_unique(); let mut account_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let account2_key = Pubkey::new_unique(); let mut account2_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let account3_key = Pubkey::new_unique(); let mut account3_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let delegate_key = Pubkey::new_unique(); let mut delegate_account = SolanaAccount::default(); let owner_key = Pubkey::new_unique(); let mut owner_account = SolanaAccount::default(); let owner2_key = Pubkey::new_unique(); let mut owner2_account = SolanaAccount::default(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let mut rent_sysvar = rent_sysvar(); // create mint do_process_instruction( initialize_mint(&program_id, &mint_key, &owner_key, None, 2).unwrap(), vec![&mut mint_account, &mut rent_sysvar], ) .unwrap(); // create account do_process_instruction( initialize_account(&program_id, &account_key, &mint_key, &owner_key).unwrap(), vec![ &mut account_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); // create another account do_process_instruction( initialize_account(&program_id, &account2_key, &mint_key, &owner_key).unwrap(), vec![ &mut account2_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); // create another account do_process_instruction( initialize_account(&program_id, &account3_key, &mint_key, &owner_key).unwrap(), vec![ &mut account3_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); // mint to account do_process_instruction( mint_to(&program_id, &mint_key, &account_key, &owner_key, &[], 1000).unwrap(), vec![&mut mint_account, &mut account_account, &mut owner_account], ) .unwrap(); let account_info = (&account_key, false, &mut account_account).into_account_info(); let account3_info = (&account3_key, false, &mut account3_account).into_account_info(); let delegate_info = (&delegate_key, true, &mut delegate_account).into_account_info(); let owner_info = (&owner_key, true, &mut owner_account).into_account_info(); let owner2_info = (&owner2_key, true, &mut owner2_account).into_account_info(); let mint_info = (&mint_key, false, &mut mint_account).into_account_info(); // transfer let instruction = transfer( &program_id, account_info.key, account_info.key, owner_info.key, &[], 1000, ) .unwrap(); assert_eq!( Ok(()), Processor::process( &instruction.program_id, &[ account_info.clone(), account_info.clone(), owner_info.clone(), ], &instruction.data, ) ); // no balance change... let account = Account::unpack_unchecked(&account_info.try_borrow_data().unwrap()).unwrap(); assert_eq!(account.amount, 1000); // transfer checked let instruction = transfer_checked( &program_id, account_info.key, mint_info.key, account_info.key, owner_info.key, &[], 1000, 2, ) .unwrap(); assert_eq!( Ok(()), Processor::process( &instruction.program_id, &[ account_info.clone(), mint_info.clone(), account_info.clone(), owner_info.clone(), ], &instruction.data, ) ); // no balance change... let account = Account::unpack_unchecked(&account_info.try_borrow_data().unwrap()).unwrap(); assert_eq!(account.amount, 1000); // missing signer let mut owner_no_sign_info = owner_info.clone(); let mut instruction = transfer( &program_id, account_info.key, account_info.key, owner_no_sign_info.key, &[], 1000, ) .unwrap(); instruction.accounts[2].is_signer = false; owner_no_sign_info.is_signer = false; assert_eq!( Err(ProgramError::MissingRequiredSignature), Processor::process( &instruction.program_id, &[ account_info.clone(), account_info.clone(), owner_no_sign_info.clone(), ], &instruction.data, ) ); // missing signer checked let mut instruction = transfer_checked( &program_id, account_info.key, mint_info.key, account_info.key, owner_no_sign_info.key, &[], 1000, 2, ) .unwrap(); instruction.accounts[3].is_signer = false; assert_eq!( Err(ProgramError::MissingRequiredSignature), Processor::process( &instruction.program_id, &[ account_info.clone(), mint_info.clone(), account_info.clone(), owner_no_sign_info, ], &instruction.data, ) ); // missing owner let instruction = transfer( &program_id, account_info.key, account_info.key, owner2_info.key, &[], 1000, ) .unwrap(); assert_eq!( Err(TokenError::OwnerMismatch.into()), Processor::process( &instruction.program_id, &[ account_info.clone(), account_info.clone(), owner2_info.clone(), ], &instruction.data, ) ); // missing owner checked let instruction = transfer_checked( &program_id, account_info.key, mint_info.key, account_info.key, owner2_info.key, &[], 1000, 2, ) .unwrap(); assert_eq!( Err(TokenError::OwnerMismatch.into()), Processor::process( &instruction.program_id, &[ account_info.clone(), mint_info.clone(), account_info.clone(), owner2_info.clone(), ], &instruction.data, ) ); // insufficient funds let instruction = transfer( &program_id, account_info.key, account_info.key, owner_info.key, &[], 1001, ) .unwrap(); assert_eq!( Err(TokenError::InsufficientFunds.into()), Processor::process( &instruction.program_id, &[ account_info.clone(), account_info.clone(), owner_info.clone(), ], &instruction.data, ) ); // insufficient funds checked let instruction = transfer_checked( &program_id, account_info.key, mint_info.key, account_info.key, owner_info.key, &[], 1001, 2, ) .unwrap(); assert_eq!( Err(TokenError::InsufficientFunds.into()), Processor::process( &instruction.program_id, &[ account_info.clone(), mint_info.clone(), account_info.clone(), owner_info.clone(), ], &instruction.data, ) ); // incorrect decimals let instruction = transfer_checked( &program_id, account_info.key, mint_info.key, account_info.key, owner_info.key, &[], 1, 10, // <-- incorrect decimals ) .unwrap(); assert_eq!( Err(TokenError::MintDecimalsMismatch.into()), Processor::process( &instruction.program_id, &[ account_info.clone(), mint_info.clone(), account_info.clone(), owner_info.clone(), ], &instruction.data, ) ); // incorrect mint let instruction = transfer_checked( &program_id, account_info.key, account3_info.key, // <-- incorrect mint account_info.key, owner_info.key, &[], 1, 2, ) .unwrap(); assert_eq!( Err(TokenError::MintMismatch.into()), Processor::process( &instruction.program_id, &[ account_info.clone(), account3_info.clone(), // <-- incorrect mint account_info.clone(), owner_info.clone(), ], &instruction.data, ) ); // approve delegate let instruction = approve( &program_id, account_info.key, delegate_info.key, owner_info.key, &[], 100, ) .unwrap(); Processor::process( &instruction.program_id, &[ account_info.clone(), delegate_info.clone(), owner_info.clone(), ], &instruction.data, ) .unwrap(); // delegate transfer let instruction = transfer( &program_id, account_info.key, account_info.key, delegate_info.key, &[], 100, ) .unwrap(); assert_eq!( Ok(()), Processor::process( &instruction.program_id, &[ account_info.clone(), account_info.clone(), delegate_info.clone(), ], &instruction.data, ) ); // no balance change... let account = Account::unpack_unchecked(&account_info.try_borrow_data().unwrap()).unwrap(); assert_eq!(account.amount, 1000); assert_eq!(account.delegated_amount, 100); // delegate transfer checked let instruction = transfer_checked( &program_id, account_info.key, mint_info.key, account_info.key, delegate_info.key, &[], 100, 2, ) .unwrap(); assert_eq!( Ok(()), Processor::process( &instruction.program_id, &[ account_info.clone(), mint_info.clone(), account_info.clone(), delegate_info.clone(), ], &instruction.data, ) ); // no balance change... let account = Account::unpack_unchecked(&account_info.try_borrow_data().unwrap()).unwrap(); assert_eq!(account.amount, 1000); assert_eq!(account.delegated_amount, 100); // delegate insufficient funds let instruction = transfer( &program_id, account_info.key, account_info.key, delegate_info.key, &[], 101, ) .unwrap(); assert_eq!( Err(TokenError::InsufficientFunds.into()), Processor::process( &instruction.program_id, &[ account_info.clone(), account_info.clone(), delegate_info.clone(), ], &instruction.data, ) ); // delegate insufficient funds checked let instruction = transfer_checked( &program_id, account_info.key, mint_info.key, account_info.key, delegate_info.key, &[], 101, 2, ) .unwrap(); assert_eq!( Err(TokenError::InsufficientFunds.into()), Processor::process( &instruction.program_id, &[ account_info.clone(), mint_info.clone(), account_info.clone(), delegate_info.clone(), ], &instruction.data, ) ); // owner transfer with delegate assigned let instruction = transfer( &program_id, account_info.key, account_info.key, owner_info.key, &[], 1000, ) .unwrap(); assert_eq!( Ok(()), Processor::process( &instruction.program_id, &[ account_info.clone(), account_info.clone(), owner_info.clone(), ], &instruction.data, ) ); // no balance change... let account = Account::unpack_unchecked(&account_info.try_borrow_data().unwrap()).unwrap(); assert_eq!(account.amount, 1000); // owner transfer with delegate assigned checked let instruction = transfer_checked( &program_id, account_info.key, mint_info.key, account_info.key, owner_info.key, &[], 1000, 2, ) .unwrap(); assert_eq!( Ok(()), Processor::process( &instruction.program_id, &[ account_info.clone(), mint_info.clone(), account_info.clone(), owner_info.clone(), ], &instruction.data, ) ); // no balance change... let account = Account::unpack_unchecked(&account_info.try_borrow_data().unwrap()).unwrap(); assert_eq!(account.amount, 1000); } #[test] fn test_mintable_token_with_zero_supply() { let program_id = crate::id(); let account_key = Pubkey::new_unique(); let mut account_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let owner_key = Pubkey::new_unique(); let mut owner_account = SolanaAccount::default(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let mut rent_sysvar = rent_sysvar(); // create mint-able token with zero supply let decimals = 2; do_process_instruction( initialize_mint(&program_id, &mint_key, &owner_key, None, decimals).unwrap(), vec![&mut mint_account, &mut rent_sysvar], ) .unwrap(); let mint = Mint::unpack_unchecked(&mint_account.data).unwrap(); assert_eq!( mint, Mint { mint_authority: COption::Some(owner_key), supply: 0, decimals, is_initialized: true, freeze_authority: COption::None, } ); // create account do_process_instruction( initialize_account(&program_id, &account_key, &mint_key, &owner_key).unwrap(), vec![ &mut account_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); // mint to do_process_instruction( mint_to(&program_id, &mint_key, &account_key, &owner_key, &[], 42).unwrap(), vec![&mut mint_account, &mut account_account, &mut owner_account], ) .unwrap(); let _ = Mint::unpack(&mint_account.data).unwrap(); let account = Account::unpack_unchecked(&account_account.data).unwrap(); assert_eq!(account.amount, 42); // mint to 2, with incorrect decimals assert_eq!( Err(TokenError::MintDecimalsMismatch.into()), do_process_instruction( mint_to_checked( &program_id, &mint_key, &account_key, &owner_key, &[], 42, decimals + 1 ) .unwrap(), vec![&mut mint_account, &mut account_account, &mut owner_account], ) ); let _ = Mint::unpack(&mint_account.data).unwrap(); let account = Account::unpack_unchecked(&account_account.data).unwrap(); assert_eq!(account.amount, 42); // mint to 2 do_process_instruction( mint_to_checked( &program_id, &mint_key, &account_key, &owner_key, &[], 42, decimals, ) .unwrap(), vec![&mut mint_account, &mut account_account, &mut owner_account], ) .unwrap(); let _ = Mint::unpack(&mint_account.data).unwrap(); let account = Account::unpack_unchecked(&account_account.data).unwrap(); assert_eq!(account.amount, 84); } #[test] fn test_approve_dups() { let program_id = crate::id(); let account1_key = Pubkey::new_unique(); let mut account1_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let account1_info: AccountInfo = (&account1_key, true, &mut account1_account).into(); let account2_key = Pubkey::new_unique(); let mut account2_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let account2_info: AccountInfo = (&account2_key, false, &mut account2_account).into(); let account3_key = Pubkey::new_unique(); let mut account3_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let account3_info: AccountInfo = (&account3_key, true, &mut account3_account).into(); let multisig_key = Pubkey::new_unique(); let mut multisig_account = SolanaAccount::new( multisig_minimum_balance(), Multisig::get_packed_len(), &program_id, ); let multisig_info: AccountInfo = (&multisig_key, true, &mut multisig_account).into(); let owner_key = Pubkey::new_unique(); let mut owner_account = SolanaAccount::default(); let owner_info: AccountInfo = (&owner_key, true, &mut owner_account).into(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let mint_info: AccountInfo = (&mint_key, false, &mut mint_account).into(); let rent_key = rent::id(); let mut rent_sysvar = rent_sysvar(); let rent_info: AccountInfo = (&rent_key, false, &mut rent_sysvar).into(); // create mint do_process_instruction_dups( initialize_mint(&program_id, &mint_key, &owner_key, None, 2).unwrap(), vec![mint_info.clone(), rent_info.clone()], ) .unwrap(); // create account do_process_instruction_dups( initialize_account(&program_id, &account1_key, &mint_key, &account1_key).unwrap(), vec![ account1_info.clone(), mint_info.clone(), account1_info.clone(), rent_info.clone(), ], ) .unwrap(); // create another account do_process_instruction_dups( initialize_account(&program_id, &account2_key, &mint_key, &owner_key).unwrap(), vec![ account2_info.clone(), mint_info.clone(), owner_info.clone(), rent_info.clone(), ], ) .unwrap(); // mint to account do_process_instruction_dups( mint_to(&program_id, &mint_key, &account1_key, &owner_key, &[], 1000).unwrap(), vec![mint_info.clone(), account1_info.clone(), owner_info.clone()], ) .unwrap(); // source-owner approve do_process_instruction_dups( approve( &program_id, &account1_key, &account2_key, &account1_key, &[], 500, ) .unwrap(), vec![ account1_info.clone(), account2_info.clone(), account1_info.clone(), ], ) .unwrap(); // source-owner approve_checked do_process_instruction_dups( approve_checked( &program_id, &account1_key, &mint_key, &account2_key, &account1_key, &[], 500, 2, ) .unwrap(), vec![ account1_info.clone(), mint_info.clone(), account2_info.clone(), account1_info.clone(), ], ) .unwrap(); // source-owner revoke do_process_instruction_dups( revoke(&program_id, &account1_key, &account1_key, &[]).unwrap(), vec![account1_info.clone(), account1_info.clone()], ) .unwrap(); // test source-multisig signer do_process_instruction_dups( initialize_multisig(&program_id, &multisig_key, &[&account3_key], 1).unwrap(), vec![ multisig_info.clone(), rent_info.clone(), account3_info.clone(), ], ) .unwrap(); do_process_instruction_dups( initialize_account(&program_id, &account3_key, &mint_key, &multisig_key).unwrap(), vec![ account3_info.clone(), mint_info.clone(), multisig_info.clone(), rent_info.clone(), ], ) .unwrap(); do_process_instruction_dups( mint_to(&program_id, &mint_key, &account3_key, &owner_key, &[], 1000).unwrap(), vec![mint_info.clone(), account3_info.clone(), owner_info.clone()], ) .unwrap(); // source-multisig-signer approve do_process_instruction_dups( approve( &program_id, &account3_key, &account2_key, &multisig_key, &[&account3_key], 500, ) .unwrap(), vec![ account3_info.clone(), account2_info.clone(), multisig_info.clone(), account3_info.clone(), ], ) .unwrap(); // source-multisig-signer approve_checked do_process_instruction_dups( approve_checked( &program_id, &account3_key, &mint_key, &account2_key, &multisig_key, &[&account3_key], 500, 2, ) .unwrap(), vec![ account3_info.clone(), mint_info.clone(), account2_info.clone(), multisig_info.clone(), account3_info.clone(), ], ) .unwrap(); // source-owner multisig-signer do_process_instruction_dups( revoke(&program_id, &account3_key, &multisig_key, &[&account3_key]).unwrap(), vec![ account3_info.clone(), multisig_info.clone(), account3_info.clone(), ], ) .unwrap(); } #[test] fn test_approve() { let program_id = crate::id(); let account_key = Pubkey::new_unique(); let mut account_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let account2_key = Pubkey::new_unique(); let mut account2_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let delegate_key = Pubkey::new_unique(); let mut delegate_account = SolanaAccount::default(); let owner_key = Pubkey::new_unique(); let mut owner_account = SolanaAccount::default(); let owner2_key = Pubkey::new_unique(); let mut owner2_account = SolanaAccount::default(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let mut rent_sysvar = rent_sysvar(); // create mint do_process_instruction( initialize_mint(&program_id, &mint_key, &owner_key, None, 2).unwrap(), vec![&mut mint_account, &mut rent_sysvar], ) .unwrap(); // create account do_process_instruction( initialize_account(&program_id, &account_key, &mint_key, &owner_key).unwrap(), vec![ &mut account_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); // create another account do_process_instruction( initialize_account(&program_id, &account2_key, &mint_key, &owner_key).unwrap(), vec![ &mut account2_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); // mint to account do_process_instruction( mint_to(&program_id, &mint_key, &account_key, &owner_key, &[], 1000).unwrap(), vec![&mut mint_account, &mut account_account, &mut owner_account], ) .unwrap(); // missing signer let mut instruction = approve( &program_id, &account_key, &delegate_key, &owner_key, &[], 100, ) .unwrap(); instruction.accounts[2].is_signer = false; assert_eq!( Err(ProgramError::MissingRequiredSignature), do_process_instruction( instruction, vec![ &mut account_account, &mut delegate_account, &mut owner_account, ], ) ); // no owner assert_eq!( Err(TokenError::OwnerMismatch.into()), do_process_instruction( approve( &program_id, &account_key, &delegate_key, &owner2_key, &[], 100 ) .unwrap(), vec![ &mut account_account, &mut delegate_account, &mut owner2_account, ], ) ); // approve delegate do_process_instruction( approve( &program_id, &account_key, &delegate_key, &owner_key, &[], 100, ) .unwrap(), vec![ &mut account_account, &mut delegate_account, &mut owner_account, ], ) .unwrap(); // approve delegate 2, with incorrect decimals assert_eq!( Err(TokenError::MintDecimalsMismatch.into()), do_process_instruction( approve_checked( &program_id, &account_key, &mint_key, &delegate_key, &owner_key, &[], 100, 0 // <-- incorrect decimals ) .unwrap(), vec![ &mut account_account, &mut mint_account, &mut delegate_account, &mut owner_account, ], ) ); // approve delegate 2, with incorrect mint assert_eq!( Err(TokenError::MintMismatch.into()), do_process_instruction( approve_checked( &program_id, &account_key, &account2_key, // <-- bad mint &delegate_key, &owner_key, &[], 100, 0 ) .unwrap(), vec![ &mut account_account, &mut account2_account, // <-- bad mint &mut delegate_account, &mut owner_account, ], ) ); // approve delegate 2 do_process_instruction( approve_checked( &program_id, &account_key, &mint_key, &delegate_key, &owner_key, &[], 100, 2, ) .unwrap(), vec![ &mut account_account, &mut mint_account, &mut delegate_account, &mut owner_account, ], ) .unwrap(); // revoke delegate do_process_instruction( revoke(&program_id, &account_key, &owner_key, &[]).unwrap(), vec![&mut account_account, &mut owner_account], ) .unwrap(); } #[test] fn test_set_authority_dups() { let program_id = crate::id(); let account1_key = Pubkey::new_unique(); let mut account1_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let account1_info: AccountInfo = (&account1_key, true, &mut account1_account).into(); let owner_key = Pubkey::new_unique(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let mint_info: AccountInfo = (&mint_key, true, &mut mint_account).into(); let rent_key = rent::id(); let mut rent_sysvar = rent_sysvar(); let rent_info: AccountInfo = (&rent_key, false, &mut rent_sysvar).into(); // create mint do_process_instruction_dups( initialize_mint(&program_id, &mint_key, &mint_key, Some(&mint_key), 2).unwrap(), vec![mint_info.clone(), rent_info.clone()], ) .unwrap(); // create account do_process_instruction_dups( initialize_account(&program_id, &account1_key, &mint_key, &account1_key).unwrap(), vec![ account1_info.clone(), mint_info.clone(), account1_info.clone(), rent_info.clone(), ], ) .unwrap(); // set mint_authority when currently self do_process_instruction_dups( set_authority( &program_id, &mint_key, Some(&owner_key), AuthorityType::MintTokens, &mint_key, &[], ) .unwrap(), vec![mint_info.clone(), mint_info.clone()], ) .unwrap(); // set freeze_authority when currently self do_process_instruction_dups( set_authority( &program_id, &mint_key, Some(&owner_key), AuthorityType::FreezeAccount, &mint_key, &[], ) .unwrap(), vec![mint_info.clone(), mint_info.clone()], ) .unwrap(); // set account owner when currently self do_process_instruction_dups( set_authority( &program_id, &account1_key, Some(&owner_key), AuthorityType::AccountOwner, &account1_key, &[], ) .unwrap(), vec![account1_info.clone(), account1_info.clone()], ) .unwrap(); // set close_authority when currently self let mut account = Account::unpack_unchecked(&account1_info.data.borrow()).unwrap(); account.close_authority = COption::Some(account1_key); Account::pack(account, &mut account1_info.data.borrow_mut()).unwrap(); do_process_instruction_dups( set_authority( &program_id, &account1_key, Some(&owner_key), AuthorityType::CloseAccount, &account1_key, &[], ) .unwrap(), vec![account1_info.clone(), account1_info.clone()], ) .unwrap(); } #[test] fn test_set_authority() { let program_id = crate::id(); let account_key = Pubkey::new_unique(); let mut account_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let account2_key = Pubkey::new_unique(); let mut account2_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let owner_key = Pubkey::new_unique(); let mut owner_account = SolanaAccount::default(); let owner2_key = Pubkey::new_unique(); let mut owner2_account = SolanaAccount::default(); let owner3_key = Pubkey::new_unique(); let mut owner3_account = SolanaAccount::default(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let mint2_key = Pubkey::new_unique(); let mut mint2_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let mut rent_sysvar = rent_sysvar(); // create new mint with owner do_process_instruction( initialize_mint(&program_id, &mint_key, &owner_key, None, 2).unwrap(), vec![&mut mint_account, &mut rent_sysvar], ) .unwrap(); // create mint with owner and freeze_authority do_process_instruction( initialize_mint(&program_id, &mint2_key, &owner_key, Some(&owner_key), 2).unwrap(), vec![&mut mint2_account, &mut rent_sysvar], ) .unwrap(); // invalid account assert_eq!( Err(ProgramError::UninitializedAccount), do_process_instruction( set_authority( &program_id, &account_key, Some(&owner2_key), AuthorityType::AccountOwner, &owner_key, &[] ) .unwrap(), vec![&mut account_account, &mut owner_account], ) ); // create account do_process_instruction( initialize_account(&program_id, &account_key, &mint_key, &owner_key).unwrap(), vec![ &mut account_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); // create another account do_process_instruction( initialize_account(&program_id, &account2_key, &mint2_key, &owner_key).unwrap(), vec![ &mut account2_account, &mut mint2_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); // missing owner assert_eq!( Err(TokenError::OwnerMismatch.into()), do_process_instruction( set_authority( &program_id, &account_key, Some(&owner_key), AuthorityType::AccountOwner, &owner2_key, &[] ) .unwrap(), vec![&mut account_account, &mut owner2_account], ) ); // owner did not sign let mut instruction = set_authority( &program_id, &account_key, Some(&owner2_key), AuthorityType::AccountOwner, &owner_key, &[], ) .unwrap(); instruction.accounts[1].is_signer = false; assert_eq!( Err(ProgramError::MissingRequiredSignature), do_process_instruction(instruction, vec![&mut account_account, &mut owner_account,],) ); // wrong authority type assert_eq!( Err(TokenError::AuthorityTypeNotSupported.into()), do_process_instruction( set_authority( &program_id, &account_key, Some(&owner2_key), AuthorityType::FreezeAccount, &owner_key, &[], ) .unwrap(), vec![&mut account_account, &mut owner_account], ) ); // account owner may not be set to None assert_eq!( Err(TokenError::InvalidInstruction.into()), do_process_instruction( set_authority( &program_id, &account_key, None, AuthorityType::AccountOwner, &owner_key, &[], ) .unwrap(), vec![&mut account_account, &mut owner_account], ) ); // set delegate do_process_instruction( approve( &program_id, &account_key, &owner2_key, &owner_key, &[], u64::MAX, ) .unwrap(), vec![ &mut account_account, &mut owner2_account, &mut owner_account, ], ) .unwrap(); let account = Account::unpack_unchecked(&account_account.data).unwrap(); assert_eq!(account.delegate, COption::Some(owner2_key)); assert_eq!(account.delegated_amount, u64::MAX); // set owner do_process_instruction( set_authority( &program_id, &account_key, Some(&owner3_key), AuthorityType::AccountOwner, &owner_key, &[], ) .unwrap(), vec![&mut account_account, &mut owner_account], ) .unwrap(); // check delegate cleared let account = Account::unpack_unchecked(&account_account.data).unwrap(); assert_eq!(account.delegate, COption::None); assert_eq!(account.delegated_amount, 0); // set owner without existing delegate do_process_instruction( set_authority( &program_id, &account_key, Some(&owner2_key), AuthorityType::AccountOwner, &owner3_key, &[], ) .unwrap(), vec![&mut account_account, &mut owner3_account], ) .unwrap(); // set close_authority do_process_instruction( set_authority( &program_id, &account_key, Some(&owner2_key), AuthorityType::CloseAccount, &owner2_key, &[], ) .unwrap(), vec![&mut account_account, &mut owner2_account], ) .unwrap(); // close_authority may be set to None do_process_instruction( set_authority( &program_id, &account_key, None, AuthorityType::CloseAccount, &owner2_key, &[], ) .unwrap(), vec![&mut account_account, &mut owner2_account], ) .unwrap(); // wrong owner assert_eq!( Err(TokenError::OwnerMismatch.into()), do_process_instruction( set_authority( &program_id, &mint_key, Some(&owner3_key), AuthorityType::MintTokens, &owner2_key, &[] ) .unwrap(), vec![&mut mint_account, &mut owner2_account], ) ); // owner did not sign let mut instruction = set_authority( &program_id, &mint_key, Some(&owner2_key), AuthorityType::MintTokens, &owner_key, &[], ) .unwrap(); instruction.accounts[1].is_signer = false; assert_eq!( Err(ProgramError::MissingRequiredSignature), do_process_instruction(instruction, vec![&mut mint_account, &mut owner_account],) ); // cannot freeze assert_eq!( Err(TokenError::MintCannotFreeze.into()), do_process_instruction( set_authority( &program_id, &mint_key, Some(&owner2_key), AuthorityType::FreezeAccount, &owner_key, &[], ) .unwrap(), vec![&mut mint_account, &mut owner_account], ) ); // set owner do_process_instruction( set_authority( &program_id, &mint_key, Some(&owner2_key), AuthorityType::MintTokens, &owner_key, &[], ) .unwrap(), vec![&mut mint_account, &mut owner_account], ) .unwrap(); // set owner to None do_process_instruction( set_authority( &program_id, &mint_key, None, AuthorityType::MintTokens, &owner2_key, &[], ) .unwrap(), vec![&mut mint_account, &mut owner2_account], ) .unwrap(); // test unsetting mint_authority is one-way operation assert_eq!( Err(TokenError::FixedSupply.into()), do_process_instruction( set_authority( &program_id, &mint2_key, Some(&owner2_key), AuthorityType::MintTokens, &owner_key, &[] ) .unwrap(), vec![&mut mint_account, &mut owner_account], ) ); // set freeze_authority do_process_instruction( set_authority( &program_id, &mint2_key, Some(&owner2_key), AuthorityType::FreezeAccount, &owner_key, &[], ) .unwrap(), vec![&mut mint2_account, &mut owner_account], ) .unwrap(); // test unsetting freeze_authority is one-way operation do_process_instruction( set_authority( &program_id, &mint2_key, None, AuthorityType::FreezeAccount, &owner2_key, &[], ) .unwrap(), vec![&mut mint2_account, &mut owner2_account], ) .unwrap(); assert_eq!( Err(TokenError::MintCannotFreeze.into()), do_process_instruction( set_authority( &program_id, &mint2_key, Some(&owner2_key), AuthorityType::FreezeAccount, &owner_key, &[], ) .unwrap(), vec![&mut mint2_account, &mut owner2_account], ) ); } #[test] fn test_mint_to_dups() { let program_id = crate::id(); let account1_key = Pubkey::new_unique(); let mut account1_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let account1_info: AccountInfo = (&account1_key, true, &mut account1_account).into(); let owner_key = Pubkey::new_unique(); let mut owner_account = SolanaAccount::default(); let owner_info: AccountInfo = (&owner_key, true, &mut owner_account).into(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let mint_info: AccountInfo = (&mint_key, true, &mut mint_account).into(); let rent_key = rent::id(); let mut rent_sysvar = rent_sysvar(); let rent_info: AccountInfo = (&rent_key, false, &mut rent_sysvar).into(); // create mint do_process_instruction_dups( initialize_mint(&program_id, &mint_key, &mint_key, None, 2).unwrap(), vec![mint_info.clone(), rent_info.clone()], ) .unwrap(); // create account do_process_instruction_dups( initialize_account(&program_id, &account1_key, &mint_key, &owner_key).unwrap(), vec![ account1_info.clone(), mint_info.clone(), owner_info.clone(), rent_info.clone(), ], ) .unwrap(); // mint_to when mint_authority is self do_process_instruction_dups( mint_to(&program_id, &mint_key, &account1_key, &mint_key, &[], 42).unwrap(), vec![mint_info.clone(), account1_info.clone(), mint_info.clone()], ) .unwrap(); // mint_to_checked when mint_authority is self do_process_instruction_dups( mint_to_checked(&program_id, &mint_key, &account1_key, &mint_key, &[], 42, 2).unwrap(), vec![mint_info.clone(), account1_info.clone(), mint_info.clone()], ) .unwrap(); // mint_to when mint_authority is account owner let mut mint = Mint::unpack_unchecked(&mint_info.data.borrow()).unwrap(); mint.mint_authority = COption::Some(account1_key); Mint::pack(mint, &mut mint_info.data.borrow_mut()).unwrap(); do_process_instruction_dups( mint_to( &program_id, &mint_key, &account1_key, &account1_key, &[], 42, ) .unwrap(), vec![ mint_info.clone(), account1_info.clone(), account1_info.clone(), ], ) .unwrap(); // mint_to_checked when mint_authority is account owner do_process_instruction_dups( mint_to( &program_id, &mint_key, &account1_key, &account1_key, &[], 42, ) .unwrap(), vec![ mint_info.clone(), account1_info.clone(), account1_info.clone(), ], ) .unwrap(); } #[test] fn test_mint_to() { let program_id = crate::id(); let account_key = Pubkey::new_unique(); let mut account_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let account2_key = Pubkey::new_unique(); let mut account2_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let account3_key = Pubkey::new_unique(); let mut account3_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let mismatch_key = Pubkey::new_unique(); let mut mismatch_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let owner_key = Pubkey::new_unique(); let mut owner_account = SolanaAccount::default(); let owner2_key = Pubkey::new_unique(); let mut owner2_account = SolanaAccount::default(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let mint2_key = Pubkey::new_unique(); let uninitialized_key = Pubkey::new_unique(); let mut uninitialized_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let mut rent_sysvar = rent_sysvar(); // create new mint with owner do_process_instruction( initialize_mint(&program_id, &mint_key, &owner_key, None, 2).unwrap(), vec![&mut mint_account, &mut rent_sysvar], ) .unwrap(); // create account do_process_instruction( initialize_account(&program_id, &account_key, &mint_key, &owner_key).unwrap(), vec![ &mut account_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); // create another account do_process_instruction( initialize_account(&program_id, &account2_key, &mint_key, &owner_key).unwrap(), vec![ &mut account2_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); // create another account do_process_instruction( initialize_account(&program_id, &account3_key, &mint_key, &owner_key).unwrap(), vec![ &mut account3_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); // create mismatch account do_process_instruction( initialize_account(&program_id, &mismatch_key, &mint_key, &owner_key).unwrap(), vec![ &mut mismatch_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); let mut account = Account::unpack_unchecked(&mismatch_account.data).unwrap(); account.mint = mint2_key; Account::pack(account, &mut mismatch_account.data).unwrap(); // mint to do_process_instruction( mint_to(&program_id, &mint_key, &account_key, &owner_key, &[], 42).unwrap(), vec![&mut mint_account, &mut account_account, &mut owner_account], ) .unwrap(); let mint = Mint::unpack_unchecked(&mint_account.data).unwrap(); assert_eq!(mint.supply, 42); let account = Account::unpack_unchecked(&account_account.data).unwrap(); assert_eq!(account.amount, 42); // mint to another account to test supply accumulation do_process_instruction( mint_to(&program_id, &mint_key, &account2_key, &owner_key, &[], 42).unwrap(), vec![&mut mint_account, &mut account2_account, &mut owner_account], ) .unwrap(); let mint = Mint::unpack_unchecked(&mint_account.data).unwrap(); assert_eq!(mint.supply, 84); let account = Account::unpack_unchecked(&account2_account.data).unwrap(); assert_eq!(account.amount, 42); // missing signer let mut instruction = mint_to(&program_id, &mint_key, &account2_key, &owner_key, &[], 42).unwrap(); instruction.accounts[2].is_signer = false; assert_eq!( Err(ProgramError::MissingRequiredSignature), do_process_instruction( instruction, vec![&mut mint_account, &mut account2_account, &mut owner_account], ) ); // mismatch account assert_eq!( Err(TokenError::MintMismatch.into()), do_process_instruction( mint_to(&program_id, &mint_key, &mismatch_key, &owner_key, &[], 42).unwrap(), vec![&mut mint_account, &mut mismatch_account, &mut owner_account], ) ); // missing owner assert_eq!( Err(TokenError::OwnerMismatch.into()), do_process_instruction( mint_to(&program_id, &mint_key, &account2_key, &owner2_key, &[], 42).unwrap(), vec![ &mut mint_account, &mut account2_account, &mut owner2_account, ], ) ); // mint not owned by program let not_program_id = Pubkey::new_unique(); mint_account.owner = not_program_id; assert_eq!( Err(ProgramError::IncorrectProgramId), do_process_instruction( mint_to(&program_id, &mint_key, &account_key, &owner_key, &[], 0).unwrap(), vec![&mut mint_account, &mut account_account, &mut owner_account], ) ); mint_account.owner = program_id; // account not owned by program let not_program_id = Pubkey::new_unique(); account_account.owner = not_program_id; assert_eq!( Err(ProgramError::IncorrectProgramId), do_process_instruction( mint_to(&program_id, &mint_key, &account_key, &owner_key, &[], 0).unwrap(), vec![&mut mint_account, &mut account_account, &mut owner_account], ) ); account_account.owner = program_id; // uninitialized destination account assert_eq!( Err(ProgramError::UninitializedAccount), do_process_instruction( mint_to( &program_id, &mint_key, &uninitialized_key, &owner_key, &[], 42 ) .unwrap(), vec![ &mut mint_account, &mut uninitialized_account, &mut owner_account, ], ) ); // unset mint_authority and test minting fails do_process_instruction( set_authority( &program_id, &mint_key, None, AuthorityType::MintTokens, &owner_key, &[], ) .unwrap(), vec![&mut mint_account, &mut owner_account], ) .unwrap(); assert_eq!( Err(TokenError::FixedSupply.into()), do_process_instruction( mint_to(&program_id, &mint_key, &account2_key, &owner_key, &[], 42).unwrap(), vec![&mut mint_account, &mut account2_account, &mut owner_account], ) ); } #[test] fn test_burn_dups() { let program_id = crate::id(); let account1_key = Pubkey::new_unique(); let mut account1_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let account1_info: AccountInfo = (&account1_key, true, &mut account1_account).into(); let owner_key = Pubkey::new_unique(); let mut owner_account = SolanaAccount::default(); let owner_info: AccountInfo = (&owner_key, true, &mut owner_account).into(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let mint_info: AccountInfo = (&mint_key, true, &mut mint_account).into(); let rent_key = rent::id(); let mut rent_sysvar = rent_sysvar(); let rent_info: AccountInfo = (&rent_key, false, &mut rent_sysvar).into(); // create mint do_process_instruction_dups( initialize_mint(&program_id, &mint_key, &owner_key, None, 2).unwrap(), vec![mint_info.clone(), rent_info.clone()], ) .unwrap(); // create account do_process_instruction_dups( initialize_account(&program_id, &account1_key, &mint_key, &account1_key).unwrap(), vec![ account1_info.clone(), mint_info.clone(), account1_info.clone(), rent_info.clone(), ], ) .unwrap(); // mint to account do_process_instruction_dups( mint_to(&program_id, &mint_key, &account1_key, &owner_key, &[], 1000).unwrap(), vec![mint_info.clone(), account1_info.clone(), owner_info.clone()], ) .unwrap(); // source-owner burn do_process_instruction_dups( burn( &program_id, &mint_key, &account1_key, &account1_key, &[], 500, ) .unwrap(), vec![ account1_info.clone(), mint_info.clone(), account1_info.clone(), ], ) .unwrap(); // source-owner burn_checked do_process_instruction_dups( burn_checked( &program_id, &account1_key, &mint_key, &account1_key, &[], 500, 2, ) .unwrap(), vec![ account1_info.clone(), mint_info.clone(), account1_info.clone(), ], ) .unwrap(); // mint-owner burn do_process_instruction_dups( mint_to(&program_id, &mint_key, &account1_key, &owner_key, &[], 1000).unwrap(), vec![mint_info.clone(), account1_info.clone(), owner_info.clone()], ) .unwrap(); let mut account = Account::unpack_unchecked(&account1_info.data.borrow()).unwrap(); account.owner = mint_key; Account::pack(account, &mut account1_info.data.borrow_mut()).unwrap(); do_process_instruction_dups( burn(&program_id, &account1_key, &mint_key, &mint_key, &[], 500).unwrap(), vec![account1_info.clone(), mint_info.clone(), mint_info.clone()], ) .unwrap(); // mint-owner burn_checked do_process_instruction_dups( burn_checked( &program_id, &account1_key, &mint_key, &mint_key, &[], 500, 2, ) .unwrap(), vec![account1_info.clone(), mint_info.clone(), mint_info.clone()], ) .unwrap(); // source-delegate burn do_process_instruction_dups( mint_to(&program_id, &mint_key, &account1_key, &owner_key, &[], 1000).unwrap(), vec![mint_info.clone(), account1_info.clone(), owner_info.clone()], ) .unwrap(); let mut account = Account::unpack_unchecked(&account1_info.data.borrow()).unwrap(); account.delegated_amount = 1000; account.delegate = COption::Some(account1_key); account.owner = owner_key; Account::pack(account, &mut account1_info.data.borrow_mut()).unwrap(); do_process_instruction_dups( burn( &program_id, &account1_key, &mint_key, &account1_key, &[], 500, ) .unwrap(), vec![ account1_info.clone(), mint_info.clone(), account1_info.clone(), ], ) .unwrap(); // source-delegate burn_checked do_process_instruction_dups( burn_checked( &program_id, &account1_key, &mint_key, &account1_key, &[], 500, 2, ) .unwrap(), vec![ account1_info.clone(), mint_info.clone(), account1_info.clone(), ], ) .unwrap(); // mint-delegate burn do_process_instruction_dups( mint_to(&program_id, &mint_key, &account1_key, &owner_key, &[], 1000).unwrap(), vec![mint_info.clone(), account1_info.clone(), owner_info.clone()], ) .unwrap(); let mut account = Account::unpack_unchecked(&account1_info.data.borrow()).unwrap(); account.delegated_amount = 1000; account.delegate = COption::Some(mint_key); account.owner = owner_key; Account::pack(account, &mut account1_info.data.borrow_mut()).unwrap(); do_process_instruction_dups( burn(&program_id, &account1_key, &mint_key, &mint_key, &[], 500).unwrap(), vec![account1_info.clone(), mint_info.clone(), mint_info.clone()], ) .unwrap(); // mint-delegate burn_checked do_process_instruction_dups( burn_checked( &program_id, &account1_key, &mint_key, &mint_key, &[], 500, 2, ) .unwrap(), vec![account1_info.clone(), mint_info.clone(), mint_info.clone()], ) .unwrap(); } #[test] fn test_burn() { let program_id = crate::id(); let account_key = Pubkey::new_unique(); let mut account_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let account2_key = Pubkey::new_unique(); let mut account2_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let account3_key = Pubkey::new_unique(); let mut account3_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let delegate_key = Pubkey::new_unique(); let mut delegate_account = SolanaAccount::default(); let mismatch_key = Pubkey::new_unique(); let mut mismatch_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let owner_key = Pubkey::new_unique(); let mut owner_account = SolanaAccount::default(); let owner2_key = Pubkey::new_unique(); let mut owner2_account = SolanaAccount::default(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let mint2_key = Pubkey::new_unique(); let mut rent_sysvar = rent_sysvar(); // create new mint do_process_instruction( initialize_mint(&program_id, &mint_key, &owner_key, None, 2).unwrap(), vec![&mut mint_account, &mut rent_sysvar], ) .unwrap(); // create account do_process_instruction( initialize_account(&program_id, &account_key, &mint_key, &owner_key).unwrap(), vec![ &mut account_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); // create another account do_process_instruction( initialize_account(&program_id, &account2_key, &mint_key, &owner_key).unwrap(), vec![ &mut account2_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); // create another account do_process_instruction( initialize_account(&program_id, &account3_key, &mint_key, &owner_key).unwrap(), vec![ &mut account3_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); // create mismatch account do_process_instruction( initialize_account(&program_id, &mismatch_key, &mint_key, &owner_key).unwrap(), vec![ &mut mismatch_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); // mint to account do_process_instruction( mint_to(&program_id, &mint_key, &account_key, &owner_key, &[], 1000).unwrap(), vec![&mut mint_account, &mut account_account, &mut owner_account], ) .unwrap(); // mint to mismatch account and change mint key do_process_instruction( mint_to(&program_id, &mint_key, &mismatch_key, &owner_key, &[], 1000).unwrap(), vec![&mut mint_account, &mut mismatch_account, &mut owner_account], ) .unwrap(); let mut account = Account::unpack_unchecked(&mismatch_account.data).unwrap(); account.mint = mint2_key; Account::pack(account, &mut mismatch_account.data).unwrap(); // missing signer let mut instruction = burn(&program_id, &account_key, &mint_key, &delegate_key, &[], 42).unwrap(); instruction.accounts[1].is_signer = false; assert_eq!( Err(TokenError::OwnerMismatch.into()), do_process_instruction( instruction, vec![ &mut account_account, &mut mint_account, &mut delegate_account ], ) ); // missing owner assert_eq!( Err(TokenError::OwnerMismatch.into()), do_process_instruction( burn(&program_id, &account_key, &mint_key, &owner2_key, &[], 42).unwrap(), vec![&mut account_account, &mut mint_account, &mut owner2_account], ) ); // account not owned by program let not_program_id = Pubkey::new_unique(); account_account.owner = not_program_id; assert_eq!( Err(ProgramError::IncorrectProgramId), do_process_instruction( burn(&program_id, &account_key, &mint_key, &owner_key, &[], 0).unwrap(), vec![&mut account_account, &mut mint_account, &mut owner_account], ) ); account_account.owner = program_id; // mint not owned by program let not_program_id = Pubkey::new_unique(); mint_account.owner = not_program_id; assert_eq!( Err(ProgramError::IncorrectProgramId), do_process_instruction( burn(&program_id, &account_key, &mint_key, &owner_key, &[], 0).unwrap(), vec![&mut account_account, &mut mint_account, &mut owner_account], ) ); mint_account.owner = program_id; // mint mismatch assert_eq!( Err(TokenError::MintMismatch.into()), do_process_instruction( burn(&program_id, &mismatch_key, &mint_key, &owner_key, &[], 42).unwrap(), vec![&mut mismatch_account, &mut mint_account, &mut owner_account], ) ); // burn do_process_instruction( burn(&program_id, &account_key, &mint_key, &owner_key, &[], 21).unwrap(), vec![&mut account_account, &mut mint_account, &mut owner_account], ) .unwrap(); // burn_checked, with incorrect decimals assert_eq!( Err(TokenError::MintDecimalsMismatch.into()), do_process_instruction( burn_checked(&program_id, &account_key, &mint_key, &owner_key, &[], 21, 3).unwrap(), vec![&mut account_account, &mut mint_account, &mut owner_account], ) ); // burn_checked do_process_instruction( burn_checked(&program_id, &account_key, &mint_key, &owner_key, &[], 21, 2).unwrap(), vec![&mut account_account, &mut mint_account, &mut owner_account], ) .unwrap(); let mint = Mint::unpack_unchecked(&mint_account.data).unwrap(); assert_eq!(mint.supply, 2000 - 42); let account = Account::unpack_unchecked(&account_account.data).unwrap(); assert_eq!(account.amount, 1000 - 42); // insufficient funds assert_eq!( Err(TokenError::InsufficientFunds.into()), do_process_instruction( burn( &program_id, &account_key, &mint_key, &owner_key, &[], 100_000_000 ) .unwrap(), vec![&mut account_account, &mut mint_account, &mut owner_account], ) ); // approve delegate do_process_instruction( approve( &program_id, &account_key, &delegate_key, &owner_key, &[], 84, ) .unwrap(), vec![ &mut account_account, &mut delegate_account, &mut owner_account, ], ) .unwrap(); // not a delegate of source account assert_eq!( Err(TokenError::InsufficientFunds.into()), do_process_instruction( burn( &program_id, &account_key, &mint_key, &owner_key, &[], 100_000_000 ) .unwrap(), vec![&mut account_account, &mut mint_account, &mut owner_account], ) ); // burn via delegate do_process_instruction( burn(&program_id, &account_key, &mint_key, &delegate_key, &[], 84).unwrap(), vec![ &mut account_account, &mut mint_account, &mut delegate_account, ], ) .unwrap(); // match let mint = Mint::unpack_unchecked(&mint_account.data).unwrap(); assert_eq!(mint.supply, 2000 - 42 - 84); let account = Account::unpack_unchecked(&account_account.data).unwrap(); assert_eq!(account.amount, 1000 - 42 - 84); // insufficient funds approved via delegate assert_eq!( Err(TokenError::OwnerMismatch.into()), do_process_instruction( burn( &program_id, &account_key, &mint_key, &delegate_key, &[], 100 ) .unwrap(), vec![ &mut account_account, &mut mint_account, &mut delegate_account ], ) ); } #[test] fn test_burn_and_close_system_and_incinerator_tokens() { let program_id = crate::id(); let account_key = Pubkey::new_unique(); let mut account_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let incinerator_account_key = Pubkey::new_unique(); let mut incinerator_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let system_account_key = Pubkey::new_unique(); let mut system_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let owner_key = Pubkey::new_unique(); let mut owner_account = SolanaAccount::default(); let recipient_key = Pubkey::new_unique(); let mut recipient_account = SolanaAccount::default(); let mut mock_incinerator_account = SolanaAccount::default(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); // create new mint do_process_instruction( initialize_mint2(&program_id, &mint_key, &owner_key, None, 2).unwrap(), vec![&mut mint_account], ) .unwrap(); // create account do_process_instruction( initialize_account3(&program_id, &account_key, &mint_key, &owner_key).unwrap(), vec![&mut account_account, &mut mint_account], ) .unwrap(); // create incinerator- and system-owned accounts do_process_instruction( initialize_account3( &program_id, &incinerator_account_key, &mint_key, &solana_program::incinerator::id(), ) .unwrap(), vec![&mut incinerator_account, &mut mint_account], ) .unwrap(); do_process_instruction( initialize_account3( &program_id, &system_account_key, &mint_key, &solana_program::system_program::id(), ) .unwrap(), vec![&mut system_account, &mut mint_account], ) .unwrap(); // mint to account do_process_instruction( mint_to(&program_id, &mint_key, &account_key, &owner_key, &[], 1000).unwrap(), vec![&mut mint_account, &mut account_account, &mut owner_account], ) .unwrap(); // transfer half to incinerator, half to system program do_process_instruction( transfer( &program_id, &account_key, &incinerator_account_key, &owner_key, &[], 500, ) .unwrap(), vec![ &mut account_account, &mut incinerator_account, &mut owner_account, ], ) .unwrap(); do_process_instruction( transfer( &program_id, &account_key, &system_account_key, &owner_key, &[], 500, ) .unwrap(), vec![ &mut account_account, &mut system_account, &mut owner_account, ], ) .unwrap(); // close with balance fails assert_eq!( Err(TokenError::NonNativeHasBalance.into()), do_process_instruction( close_account( &program_id, &incinerator_account_key, &solana_program::incinerator::id(), &owner_key, &[] ) .unwrap(), vec![ &mut incinerator_account, &mut mock_incinerator_account, &mut owner_account, ], ) ); assert_eq!( Err(TokenError::NonNativeHasBalance.into()), do_process_instruction( close_account( &program_id, &system_account_key, &solana_program::incinerator::id(), &owner_key, &[] ) .unwrap(), vec![ &mut system_account, &mut mock_incinerator_account, &mut owner_account, ], ) ); // anyone can burn do_process_instruction( burn( &program_id, &incinerator_account_key, &mint_key, &recipient_key, &[], 500, ) .unwrap(), vec![ &mut incinerator_account, &mut mint_account, &mut recipient_account, ], ) .unwrap(); do_process_instruction( burn( &program_id, &system_account_key, &mint_key, &recipient_key, &[], 500, ) .unwrap(), vec![ &mut system_account, &mut mint_account, &mut recipient_account, ], ) .unwrap(); // closing fails if destination is not the incinerator assert_eq!( Err(ProgramError::InvalidAccountData), do_process_instruction( close_account( &program_id, &incinerator_account_key, &recipient_key, &owner_key, &[] ) .unwrap(), vec![ &mut incinerator_account, &mut recipient_account, &mut owner_account, ], ) ); assert_eq!( Err(ProgramError::InvalidAccountData), do_process_instruction( close_account( &program_id, &system_account_key, &recipient_key, &owner_key, &[] ) .unwrap(), vec![ &mut system_account, &mut recipient_account, &mut owner_account, ], ) ); // closing succeeds with incinerator recipient do_process_instruction( close_account( &program_id, &incinerator_account_key, &solana_program::incinerator::id(), &owner_key, &[], ) .unwrap(), vec![ &mut incinerator_account, &mut mock_incinerator_account, &mut owner_account, ], ) .unwrap(); do_process_instruction( close_account( &program_id, &system_account_key, &solana_program::incinerator::id(), &owner_key, &[], ) .unwrap(), vec![ &mut system_account, &mut mock_incinerator_account, &mut owner_account, ], ) .unwrap(); } #[test] fn test_multisig() { let program_id = crate::id(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let account_key = Pubkey::new_unique(); let mut account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let account2_key = Pubkey::new_unique(); let mut account2_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let owner_key = Pubkey::new_unique(); let mut owner_account = SolanaAccount::default(); let multisig_key = Pubkey::new_unique(); let mut multisig_account = SolanaAccount::new(42, Multisig::get_packed_len(), &program_id); let multisig_delegate_key = Pubkey::new_unique(); let mut multisig_delegate_account = SolanaAccount::new( multisig_minimum_balance(), Multisig::get_packed_len(), &program_id, ); let signer_keys = vec![Pubkey::new_unique(); MAX_SIGNERS]; let signer_key_refs: Vec<&Pubkey> = signer_keys.iter().collect(); let mut signer_accounts = vec![SolanaAccount::new(0, 0, &program_id); MAX_SIGNERS]; let mut rent_sysvar = rent_sysvar(); // multisig is not rent exempt let account_info_iter = &mut signer_accounts.iter_mut(); assert_eq!( Err(TokenError::NotRentExempt.into()), do_process_instruction( initialize_multisig(&program_id, &multisig_key, &[&signer_keys[0]], 1).unwrap(), vec![ &mut multisig_account, &mut rent_sysvar, account_info_iter.next().unwrap(), ], ) ); multisig_account.lamports = multisig_minimum_balance(); let mut multisig_account2 = multisig_account.clone(); // single signer let account_info_iter = &mut signer_accounts.iter_mut(); do_process_instruction( initialize_multisig(&program_id, &multisig_key, &[&signer_keys[0]], 1).unwrap(), vec![ &mut multisig_account, &mut rent_sysvar, account_info_iter.next().unwrap(), ], ) .unwrap(); // single signer using `initialize_multisig2` let account_info_iter = &mut signer_accounts.iter_mut(); do_process_instruction( initialize_multisig2(&program_id, &multisig_key, &[&signer_keys[0]], 1).unwrap(), vec![&mut multisig_account2, account_info_iter.next().unwrap()], ) .unwrap(); // multiple signer let account_info_iter = &mut signer_accounts.iter_mut(); do_process_instruction( initialize_multisig( &program_id, &multisig_delegate_key, &signer_key_refs, MAX_SIGNERS as u8, ) .unwrap(), vec![ &mut multisig_delegate_account, &mut rent_sysvar, account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), ], ) .unwrap(); // create new mint with multisig owner do_process_instruction( initialize_mint(&program_id, &mint_key, &multisig_key, None, 2).unwrap(), vec![&mut mint_account, &mut rent_sysvar], ) .unwrap(); // create account with multisig owner do_process_instruction( initialize_account(&program_id, &account_key, &mint_key, &multisig_key).unwrap(), vec![ &mut account, &mut mint_account, &mut multisig_account, &mut rent_sysvar, ], ) .unwrap(); // create another account with multisig owner do_process_instruction( initialize_account( &program_id, &account2_key, &mint_key, &multisig_delegate_key, ) .unwrap(), vec![ &mut account2_account, &mut mint_account, &mut multisig_account, &mut rent_sysvar, ], ) .unwrap(); // mint to account let account_info_iter = &mut signer_accounts.iter_mut(); do_process_instruction( mint_to( &program_id, &mint_key, &account_key, &multisig_key, &[&signer_keys[0]], 1000, ) .unwrap(), vec![ &mut mint_account, &mut account, &mut multisig_account, account_info_iter.next().unwrap(), ], ) .unwrap(); // approve let account_info_iter = &mut signer_accounts.iter_mut(); do_process_instruction( approve( &program_id, &account_key, &multisig_delegate_key, &multisig_key, &[&signer_keys[0]], 100, ) .unwrap(), vec![ &mut account, &mut multisig_delegate_account, &mut multisig_account, account_info_iter.next().unwrap(), ], ) .unwrap(); // transfer let account_info_iter = &mut signer_accounts.iter_mut(); do_process_instruction( transfer( &program_id, &account_key, &account2_key, &multisig_key, &[&signer_keys[0]], 42, ) .unwrap(), vec![ &mut account, &mut account2_account, &mut multisig_account, account_info_iter.next().unwrap(), ], ) .unwrap(); // transfer via delegate let account_info_iter = &mut signer_accounts.iter_mut(); do_process_instruction( transfer( &program_id, &account_key, &account2_key, &multisig_delegate_key, &signer_key_refs, 42, ) .unwrap(), vec![ &mut account, &mut account2_account, &mut multisig_delegate_account, account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), ], ) .unwrap(); // mint to let account_info_iter = &mut signer_accounts.iter_mut(); do_process_instruction( mint_to( &program_id, &mint_key, &account2_key, &multisig_key, &[&signer_keys[0]], 42, ) .unwrap(), vec![ &mut mint_account, &mut account2_account, &mut multisig_account, account_info_iter.next().unwrap(), ], ) .unwrap(); // burn let account_info_iter = &mut signer_accounts.iter_mut(); do_process_instruction( burn( &program_id, &account_key, &mint_key, &multisig_key, &[&signer_keys[0]], 42, ) .unwrap(), vec![ &mut account, &mut mint_account, &mut multisig_account, account_info_iter.next().unwrap(), ], ) .unwrap(); // burn via delegate let account_info_iter = &mut signer_accounts.iter_mut(); do_process_instruction( burn( &program_id, &account_key, &mint_key, &multisig_delegate_key, &signer_key_refs, 42, ) .unwrap(), vec![ &mut account, &mut mint_account, &mut multisig_delegate_account, account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), account_info_iter.next().unwrap(), ], ) .unwrap(); // freeze account let account3_key = Pubkey::new_unique(); let mut account3_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let mint2_key = Pubkey::new_unique(); let mut mint2_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); do_process_instruction( initialize_mint( &program_id, &mint2_key, &multisig_key, Some(&multisig_key), 2, ) .unwrap(), vec![&mut mint2_account, &mut rent_sysvar], ) .unwrap(); do_process_instruction( initialize_account(&program_id, &account3_key, &mint2_key, &owner_key).unwrap(), vec![ &mut account3_account, &mut mint2_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); let account_info_iter = &mut signer_accounts.iter_mut(); do_process_instruction( mint_to( &program_id, &mint2_key, &account3_key, &multisig_key, &[&signer_keys[0]], 1000, ) .unwrap(), vec![ &mut mint2_account, &mut account3_account, &mut multisig_account, account_info_iter.next().unwrap(), ], ) .unwrap(); let account_info_iter = &mut signer_accounts.iter_mut(); do_process_instruction( freeze_account( &program_id, &account3_key, &mint2_key, &multisig_key, &[&signer_keys[0]], ) .unwrap(), vec![ &mut account3_account, &mut mint2_account, &mut multisig_account, account_info_iter.next().unwrap(), ], ) .unwrap(); // do SetAuthority on mint let account_info_iter = &mut signer_accounts.iter_mut(); do_process_instruction( set_authority( &program_id, &mint_key, Some(&owner_key), AuthorityType::MintTokens, &multisig_key, &[&signer_keys[0]], ) .unwrap(), vec![ &mut mint_account, &mut multisig_account, account_info_iter.next().unwrap(), ], ) .unwrap(); // do SetAuthority on account let account_info_iter = &mut signer_accounts.iter_mut(); do_process_instruction( set_authority( &program_id, &account_key, Some(&owner_key), AuthorityType::AccountOwner, &multisig_key, &[&signer_keys[0]], ) .unwrap(), vec![ &mut account, &mut multisig_account, account_info_iter.next().unwrap(), ], ) .unwrap(); } #[test] fn test_validate_owner() { let program_id = crate::id(); let owner_key = Pubkey::new_unique(); let mut signer_keys = [Pubkey::default(); MAX_SIGNERS]; for signer_key in signer_keys.iter_mut().take(MAX_SIGNERS) { *signer_key = Pubkey::new_unique(); } let mut signer_lamports = 0; let mut signer_data = vec![]; let mut signers = vec![ AccountInfo::new( &owner_key, true, false, &mut signer_lamports, &mut signer_data, &program_id, false, Epoch::default(), ); MAX_SIGNERS + 1 ]; for (signer, key) in signers.iter_mut().zip(&signer_keys) { signer.key = key; } let mut lamports = 0; let mut data = vec![0; Multisig::get_packed_len()]; let mut multisig = Multisig::unpack_unchecked(&data).unwrap(); multisig.m = MAX_SIGNERS as u8; multisig.n = MAX_SIGNERS as u8; multisig.signers = signer_keys; multisig.is_initialized = true; Multisig::pack(multisig, &mut data).unwrap(); let owner_account_info = AccountInfo::new( &owner_key, false, false, &mut lamports, &mut data, &program_id, false, Epoch::default(), ); // full 11 of 11 Processor::validate_owner(&program_id, &owner_key, &owner_account_info, &signers).unwrap(); // 1 of 11 { let mut multisig = Multisig::unpack_unchecked(&owner_account_info.data.borrow()).unwrap(); multisig.m = 1; Multisig::pack(multisig, &mut owner_account_info.data.borrow_mut()).unwrap(); } Processor::validate_owner(&program_id, &owner_key, &owner_account_info, &signers).unwrap(); // 2:1 { let mut multisig = Multisig::unpack_unchecked(&owner_account_info.data.borrow()).unwrap(); multisig.m = 2; multisig.n = 1; Multisig::pack(multisig, &mut owner_account_info.data.borrow_mut()).unwrap(); } assert_eq!( Err(ProgramError::MissingRequiredSignature), Processor::validate_owner(&program_id, &owner_key, &owner_account_info, &signers) ); // 0:11 { let mut multisig = Multisig::unpack_unchecked(&owner_account_info.data.borrow()).unwrap(); multisig.m = 0; multisig.n = 11; Multisig::pack(multisig, &mut owner_account_info.data.borrow_mut()).unwrap(); } Processor::validate_owner(&program_id, &owner_key, &owner_account_info, &signers).unwrap(); // 2:11 but 0 provided { let mut multisig = Multisig::unpack_unchecked(&owner_account_info.data.borrow()).unwrap(); multisig.m = 2; multisig.n = 11; Multisig::pack(multisig, &mut owner_account_info.data.borrow_mut()).unwrap(); } assert_eq!( Err(ProgramError::MissingRequiredSignature), Processor::validate_owner(&program_id, &owner_key, &owner_account_info, &[]) ); // 2:11 but 1 provided { let mut multisig = Multisig::unpack_unchecked(&owner_account_info.data.borrow()).unwrap(); multisig.m = 2; multisig.n = 11; Multisig::pack(multisig, &mut owner_account_info.data.borrow_mut()).unwrap(); } assert_eq!( Err(ProgramError::MissingRequiredSignature), Processor::validate_owner(&program_id, &owner_key, &owner_account_info, &signers[0..1]) ); // 2:11, 2 from middle provided { let mut multisig = Multisig::unpack_unchecked(&owner_account_info.data.borrow()).unwrap(); multisig.m = 2; multisig.n = 11; Multisig::pack(multisig, &mut owner_account_info.data.borrow_mut()).unwrap(); } Processor::validate_owner(&program_id, &owner_key, &owner_account_info, &signers[5..7]) .unwrap(); // 11:11, one is not a signer { let mut multisig = Multisig::unpack_unchecked(&owner_account_info.data.borrow()).unwrap(); multisig.m = 11; multisig.n = 11; Multisig::pack(multisig, &mut owner_account_info.data.borrow_mut()).unwrap(); } signers[5].is_signer = false; assert_eq!( Err(ProgramError::MissingRequiredSignature), Processor::validate_owner(&program_id, &owner_key, &owner_account_info, &signers) ); signers[5].is_signer = true; // 11:11, single signer signs multiple times { let mut signer_lamports = 0; let mut signer_data = vec![]; let signers = vec![ AccountInfo::new( &signer_keys[5], true, false, &mut signer_lamports, &mut signer_data, &program_id, false, Epoch::default(), ); MAX_SIGNERS + 1 ]; let mut multisig = Multisig::unpack_unchecked(&owner_account_info.data.borrow()).unwrap(); multisig.m = 11; multisig.n = 11; Multisig::pack(multisig, &mut owner_account_info.data.borrow_mut()).unwrap(); assert_eq!( Err(ProgramError::MissingRequiredSignature), Processor::validate_owner(&program_id, &owner_key, &owner_account_info, &signers) ); } } #[test] fn test_owner_close_account_dups() { let program_id = crate::id(); let owner_key = Pubkey::new_unique(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let mint_info: AccountInfo = (&mint_key, false, &mut mint_account).into(); let rent_key = rent::id(); let mut rent_sysvar = rent_sysvar(); let rent_info: AccountInfo = (&rent_key, false, &mut rent_sysvar).into(); // create mint do_process_instruction_dups( initialize_mint(&program_id, &mint_key, &owner_key, None, 2).unwrap(), vec![mint_info.clone(), rent_info.clone()], ) .unwrap(); let to_close_key = Pubkey::new_unique(); let mut to_close_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let to_close_account_info: AccountInfo = (&to_close_key, true, &mut to_close_account).into(); let destination_account_key = Pubkey::new_unique(); let mut destination_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let destination_account_info: AccountInfo = (&destination_account_key, true, &mut destination_account).into(); // create account do_process_instruction_dups( initialize_account(&program_id, &to_close_key, &mint_key, &to_close_key).unwrap(), vec![ to_close_account_info.clone(), mint_info.clone(), to_close_account_info.clone(), rent_info.clone(), ], ) .unwrap(); // source-owner close do_process_instruction_dups( close_account( &program_id, &to_close_key, &destination_account_key, &to_close_key, &[], ) .unwrap(), vec![ to_close_account_info.clone(), destination_account_info.clone(), to_close_account_info.clone(), ], ) .unwrap(); assert_eq!(*to_close_account_info.data.borrow(), &[0u8; Account::LEN]); } #[test] fn test_close_authority_close_account_dups() { let program_id = crate::id(); let owner_key = Pubkey::new_unique(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let mint_info: AccountInfo = (&mint_key, false, &mut mint_account).into(); let rent_key = rent::id(); let mut rent_sysvar = rent_sysvar(); let rent_info: AccountInfo = (&rent_key, false, &mut rent_sysvar).into(); // create mint do_process_instruction_dups( initialize_mint(&program_id, &mint_key, &owner_key, None, 2).unwrap(), vec![mint_info.clone(), rent_info.clone()], ) .unwrap(); let to_close_key = Pubkey::new_unique(); let mut to_close_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let to_close_account_info: AccountInfo = (&to_close_key, true, &mut to_close_account).into(); let destination_account_key = Pubkey::new_unique(); let mut destination_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let destination_account_info: AccountInfo = (&destination_account_key, true, &mut destination_account).into(); // create account do_process_instruction_dups( initialize_account(&program_id, &to_close_key, &mint_key, &to_close_key).unwrap(), vec![ to_close_account_info.clone(), mint_info.clone(), to_close_account_info.clone(), rent_info.clone(), ], ) .unwrap(); let mut account = Account::unpack_unchecked(&to_close_account_info.data.borrow()).unwrap(); account.close_authority = COption::Some(to_close_key); account.owner = owner_key; Account::pack(account, &mut to_close_account_info.data.borrow_mut()).unwrap(); do_process_instruction_dups( close_account( &program_id, &to_close_key, &destination_account_key, &to_close_key, &[], ) .unwrap(), vec![ to_close_account_info.clone(), destination_account_info.clone(), to_close_account_info.clone(), ], ) .unwrap(); assert_eq!(*to_close_account_info.data.borrow(), &[0u8; Account::LEN]); } #[test] fn test_close_account() { let program_id = crate::id(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let account_key = Pubkey::new_unique(); let mut account_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let account2_key = Pubkey::new_unique(); let mut account2_account = SolanaAccount::new( account_minimum_balance() + 42, Account::get_packed_len(), &program_id, ); let account3_key = Pubkey::new_unique(); let mut account3_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let owner_key = Pubkey::new_unique(); let mut owner_account = SolanaAccount::default(); let owner2_key = Pubkey::new_unique(); let mut owner2_account = SolanaAccount::default(); let mut rent_sysvar = rent_sysvar(); // uninitialized assert_eq!( Err(ProgramError::UninitializedAccount), do_process_instruction( close_account(&program_id, &account_key, &account3_key, &owner2_key, &[]).unwrap(), vec![ &mut account_account, &mut account3_account, &mut owner2_account, ], ) ); // initialize and mint to non-native account do_process_instruction( initialize_mint(&program_id, &mint_key, &owner_key, None, 2).unwrap(), vec![&mut mint_account, &mut rent_sysvar], ) .unwrap(); do_process_instruction( initialize_account(&program_id, &account_key, &mint_key, &owner_key).unwrap(), vec![ &mut account_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); do_process_instruction( mint_to(&program_id, &mint_key, &account_key, &owner_key, &[], 42).unwrap(), vec![ &mut mint_account, &mut account_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); let account = Account::unpack_unchecked(&account_account.data).unwrap(); assert_eq!(account.amount, 42); // initialize native account do_process_instruction( initialize_account( &program_id, &account2_key, &crate::native_mint::id(), &owner_key, ) .unwrap(), vec![ &mut account2_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); let account = Account::unpack_unchecked(&account2_account.data).unwrap(); assert!(account.is_native()); assert_eq!(account.amount, 42); // close non-native account with balance assert_eq!( Err(TokenError::NonNativeHasBalance.into()), do_process_instruction( close_account(&program_id, &account_key, &account3_key, &owner_key, &[]).unwrap(), vec![ &mut account_account, &mut account3_account, &mut owner_account, ], ) ); assert_eq!(account_account.lamports, account_minimum_balance()); // empty account do_process_instruction( burn(&program_id, &account_key, &mint_key, &owner_key, &[], 42).unwrap(), vec![&mut account_account, &mut mint_account, &mut owner_account], ) .unwrap(); // wrong owner assert_eq!( Err(TokenError::OwnerMismatch.into()), do_process_instruction( close_account(&program_id, &account_key, &account3_key, &owner2_key, &[]).unwrap(), vec![ &mut account_account, &mut account3_account, &mut owner2_account, ], ) ); // close account do_process_instruction( close_account(&program_id, &account_key, &account3_key, &owner_key, &[]).unwrap(), vec![ &mut account_account, &mut account3_account, &mut owner_account, ], ) .unwrap(); assert_eq!(account_account.lamports, 0); assert_eq!(account3_account.lamports, 2 * account_minimum_balance()); let account = Account::unpack_unchecked(&account_account.data).unwrap(); assert_eq!(account.amount, 0); // fund and initialize new non-native account to test close authority let account_key = Pubkey::new_unique(); let mut account_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let owner2_key = Pubkey::new_unique(); let mut owner2_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); do_process_instruction( initialize_account(&program_id, &account_key, &mint_key, &owner_key).unwrap(), vec![ &mut account_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); account_account.lamports = 2; do_process_instruction( set_authority( &program_id, &account_key, Some(&owner2_key), AuthorityType::CloseAccount, &owner_key, &[], ) .unwrap(), vec![&mut account_account, &mut owner_account], ) .unwrap(); // account owner cannot authorize close if close_authority is set assert_eq!( Err(TokenError::OwnerMismatch.into()), do_process_instruction( close_account(&program_id, &account_key, &account3_key, &owner_key, &[]).unwrap(), vec![ &mut account_account, &mut account3_account, &mut owner_account, ], ) ); // close non-native account with close_authority do_process_instruction( close_account(&program_id, &account_key, &account3_key, &owner2_key, &[]).unwrap(), vec![ &mut account_account, &mut account3_account, &mut owner2_account, ], ) .unwrap(); assert_eq!(account_account.lamports, 0); assert_eq!(account3_account.lamports, 2 * account_minimum_balance() + 2); let account = Account::unpack_unchecked(&account_account.data).unwrap(); assert_eq!(account.amount, 0); // close native account do_process_instruction( close_account(&program_id, &account2_key, &account3_key, &owner_key, &[]).unwrap(), vec![ &mut account2_account, &mut account3_account, &mut owner_account, ], ) .unwrap(); assert_eq!(account2_account.data, [0u8; Account::LEN]); assert_eq!( account3_account.lamports, 3 * account_minimum_balance() + 2 + 42 ); } #[test] fn test_native_token() { let program_id = crate::id(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let account_key = Pubkey::new_unique(); let mut account_account = SolanaAccount::new( account_minimum_balance() + 40, Account::get_packed_len(), &program_id, ); let account2_key = Pubkey::new_unique(); let mut account2_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let account3_key = Pubkey::new_unique(); let mut account3_account = SolanaAccount::new(account_minimum_balance(), 0, &program_id); let owner_key = Pubkey::new_unique(); let mut owner_account = SolanaAccount::default(); let owner2_key = Pubkey::new_unique(); let mut owner2_account = SolanaAccount::default(); let owner3_key = Pubkey::new_unique(); let mut rent_sysvar = rent_sysvar(); // initialize native account do_process_instruction( initialize_account( &program_id, &account_key, &crate::native_mint::id(), &owner_key, ) .unwrap(), vec![ &mut account_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); let account = Account::unpack_unchecked(&account_account.data).unwrap(); assert!(account.is_native()); assert_eq!(account.amount, 40); // initialize native account do_process_instruction( initialize_account( &program_id, &account2_key, &crate::native_mint::id(), &owner_key, ) .unwrap(), vec![ &mut account2_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); let account = Account::unpack_unchecked(&account2_account.data).unwrap(); assert!(account.is_native()); assert_eq!(account.amount, 0); // mint_to unsupported assert_eq!( Err(TokenError::NativeNotSupported.into()), do_process_instruction( mint_to( &program_id, &crate::native_mint::id(), &account_key, &owner_key, &[], 42 ) .unwrap(), vec![&mut mint_account, &mut account_account, &mut owner_account], ) ); // burn unsupported let bogus_mint_key = Pubkey::new_unique(); let mut bogus_mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); do_process_instruction( initialize_mint(&program_id, &bogus_mint_key, &owner_key, None, 2).unwrap(), vec![&mut bogus_mint_account, &mut rent_sysvar], ) .unwrap(); assert_eq!( Err(TokenError::NativeNotSupported.into()), do_process_instruction( burn( &program_id, &account_key, &bogus_mint_key, &owner_key, &[], 42 ) .unwrap(), vec![ &mut account_account, &mut bogus_mint_account, &mut owner_account ], ) ); // ensure can't transfer below rent-exempt reserve assert_eq!( Err(TokenError::InsufficientFunds.into()), do_process_instruction( transfer( &program_id, &account_key, &account2_key, &owner_key, &[], 50, ) .unwrap(), vec![ &mut account_account, &mut account2_account, &mut owner_account, ], ) ); // transfer between native accounts do_process_instruction( transfer( &program_id, &account_key, &account2_key, &owner_key, &[], 40, ) .unwrap(), vec![ &mut account_account, &mut account2_account, &mut owner_account, ], ) .unwrap(); assert_eq!(account_account.lamports, account_minimum_balance()); let account = Account::unpack_unchecked(&account_account.data).unwrap(); assert!(account.is_native()); assert_eq!(account.amount, 0); assert_eq!(account2_account.lamports, account_minimum_balance() + 40); let account = Account::unpack_unchecked(&account2_account.data).unwrap(); assert!(account.is_native()); assert_eq!(account.amount, 40); // set close authority do_process_instruction( set_authority( &program_id, &account_key, Some(&owner3_key), AuthorityType::CloseAccount, &owner_key, &[], ) .unwrap(), vec![&mut account_account, &mut owner_account], ) .unwrap(); let account = Account::unpack_unchecked(&account_account.data).unwrap(); assert_eq!(account.close_authority, COption::Some(owner3_key)); // set new account owner do_process_instruction( set_authority( &program_id, &account_key, Some(&owner2_key), AuthorityType::AccountOwner, &owner_key, &[], ) .unwrap(), vec![&mut account_account, &mut owner_account], ) .unwrap(); // close authority cleared let account = Account::unpack_unchecked(&account_account.data).unwrap(); assert_eq!(account.close_authority, COption::None); // close native account do_process_instruction( close_account(&program_id, &account_key, &account3_key, &owner2_key, &[]).unwrap(), vec![ &mut account_account, &mut account3_account, &mut owner2_account, ], ) .unwrap(); assert_eq!(account_account.lamports, 0); assert_eq!(account3_account.lamports, 2 * account_minimum_balance()); assert_eq!(account_account.data, [0u8; Account::LEN]); } #[test] fn test_overflow() { let program_id = crate::id(); let account_key = Pubkey::new_unique(); let mut account_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let account2_key = Pubkey::new_unique(); let mut account2_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let owner_key = Pubkey::new_unique(); let mut owner_account = SolanaAccount::default(); let owner2_key = Pubkey::new_unique(); let mut owner2_account = SolanaAccount::default(); let mint_owner_key = Pubkey::new_unique(); let mut mint_owner_account = SolanaAccount::default(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let mut rent_sysvar = rent_sysvar(); // create new mint with owner do_process_instruction( initialize_mint(&program_id, &mint_key, &mint_owner_key, None, 2).unwrap(), vec![&mut mint_account, &mut rent_sysvar], ) .unwrap(); // create an account do_process_instruction( initialize_account(&program_id, &account_key, &mint_key, &owner_key).unwrap(), vec![ &mut account_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); // create another account do_process_instruction( initialize_account(&program_id, &account2_key, &mint_key, &owner2_key).unwrap(), vec![ &mut account2_account, &mut mint_account, &mut owner2_account, &mut rent_sysvar, ], ) .unwrap(); // mint the max to an account do_process_instruction( mint_to( &program_id, &mint_key, &account_key, &mint_owner_key, &[], u64::MAX, ) .unwrap(), vec![ &mut mint_account, &mut account_account, &mut mint_owner_account, ], ) .unwrap(); let account = Account::unpack_unchecked(&account_account.data).unwrap(); assert_eq!(account.amount, u64::MAX); // attempt to mint one more to account assert_eq!( Err(TokenError::Overflow.into()), do_process_instruction( mint_to( &program_id, &mint_key, &account_key, &mint_owner_key, &[], 1, ) .unwrap(), vec![ &mut mint_account, &mut account_account, &mut mint_owner_account, ], ) ); let account = Account::unpack_unchecked(&account_account.data).unwrap(); assert_eq!(account.amount, u64::MAX); // atttempt to mint one more to the other account assert_eq!( Err(TokenError::Overflow.into()), do_process_instruction( mint_to( &program_id, &mint_key, &account2_key, &mint_owner_key, &[], 1, ) .unwrap(), vec![ &mut mint_account, &mut account2_account, &mut mint_owner_account, ], ) ); // burn some of the supply do_process_instruction( burn(&program_id, &account_key, &mint_key, &owner_key, &[], 100).unwrap(), vec![&mut account_account, &mut mint_account, &mut owner_account], ) .unwrap(); let account = Account::unpack_unchecked(&account_account.data).unwrap(); assert_eq!(account.amount, u64::MAX - 100); do_process_instruction( mint_to( &program_id, &mint_key, &account_key, &mint_owner_key, &[], 100, ) .unwrap(), vec![ &mut mint_account, &mut account_account, &mut mint_owner_account, ], ) .unwrap(); let account = Account::unpack_unchecked(&account_account.data).unwrap(); assert_eq!(account.amount, u64::MAX); // manipulate account balance to attempt overflow transfer let mut account = Account::unpack_unchecked(&account2_account.data).unwrap(); account.amount = 1; Account::pack(account, &mut account2_account.data).unwrap(); assert_eq!( Err(TokenError::Overflow.into()), do_process_instruction( transfer( &program_id, &account2_key, &account_key, &owner2_key, &[], 1, ) .unwrap(), vec![ &mut account2_account, &mut account_account, &mut owner2_account, ], ) ); } #[test] fn test_frozen() { let program_id = crate::id(); let account_key = Pubkey::new_unique(); let mut account_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let account2_key = Pubkey::new_unique(); let mut account2_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let owner_key = Pubkey::new_unique(); let mut owner_account = SolanaAccount::default(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let mut rent_sysvar = rent_sysvar(); // create new mint and fund first account do_process_instruction( initialize_mint(&program_id, &mint_key, &owner_key, None, 2).unwrap(), vec![&mut mint_account, &mut rent_sysvar], ) .unwrap(); // create account do_process_instruction( initialize_account(&program_id, &account_key, &mint_key, &owner_key).unwrap(), vec![ &mut account_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); // create another account do_process_instruction( initialize_account(&program_id, &account2_key, &mint_key, &owner_key).unwrap(), vec![ &mut account2_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); // fund first account do_process_instruction( mint_to(&program_id, &mint_key, &account_key, &owner_key, &[], 1000).unwrap(), vec![&mut mint_account, &mut account_account, &mut owner_account], ) .unwrap(); // no transfer if either account is frozen let mut account = Account::unpack_unchecked(&account2_account.data).unwrap(); account.state = AccountState::Frozen; Account::pack(account, &mut account2_account.data).unwrap(); assert_eq!( Err(TokenError::AccountFrozen.into()), do_process_instruction( transfer( &program_id, &account_key, &account2_key, &owner_key, &[], 500, ) .unwrap(), vec![ &mut account_account, &mut account2_account, &mut owner_account, ], ) ); let mut account = Account::unpack_unchecked(&account_account.data).unwrap(); account.state = AccountState::Initialized; Account::pack(account, &mut account_account.data).unwrap(); let mut account = Account::unpack_unchecked(&account2_account.data).unwrap(); account.state = AccountState::Frozen; Account::pack(account, &mut account2_account.data).unwrap(); assert_eq!( Err(TokenError::AccountFrozen.into()), do_process_instruction( transfer( &program_id, &account_key, &account2_key, &owner_key, &[], 500, ) .unwrap(), vec![ &mut account_account, &mut account2_account, &mut owner_account, ], ) ); // no approve if account is frozen let mut account = Account::unpack_unchecked(&account_account.data).unwrap(); account.state = AccountState::Frozen; Account::pack(account, &mut account_account.data).unwrap(); let delegate_key = Pubkey::new_unique(); let mut delegate_account = SolanaAccount::default(); assert_eq!( Err(TokenError::AccountFrozen.into()), do_process_instruction( approve( &program_id, &account_key, &delegate_key, &owner_key, &[], 100 ) .unwrap(), vec![ &mut account_account, &mut delegate_account, &mut owner_account, ], ) ); // no revoke if account is frozen let mut account = Account::unpack_unchecked(&account_account.data).unwrap(); account.delegate = COption::Some(delegate_key); account.delegated_amount = 100; Account::pack(account, &mut account_account.data).unwrap(); assert_eq!( Err(TokenError::AccountFrozen.into()), do_process_instruction( revoke(&program_id, &account_key, &owner_key, &[]).unwrap(), vec![&mut account_account, &mut owner_account], ) ); // no set authority if account is frozen let new_owner_key = Pubkey::new_unique(); assert_eq!( Err(TokenError::AccountFrozen.into()), do_process_instruction( set_authority( &program_id, &account_key, Some(&new_owner_key), AuthorityType::AccountOwner, &owner_key, &[] ) .unwrap(), vec![&mut account_account, &mut owner_account,], ) ); // no mint_to if destination account is frozen assert_eq!( Err(TokenError::AccountFrozen.into()), do_process_instruction( mint_to(&program_id, &mint_key, &account_key, &owner_key, &[], 100).unwrap(), vec![&mut mint_account, &mut account_account, &mut owner_account,], ) ); // no burn if account is frozen assert_eq!( Err(TokenError::AccountFrozen.into()), do_process_instruction( burn(&program_id, &account_key, &mint_key, &owner_key, &[], 100).unwrap(), vec![&mut account_account, &mut mint_account, &mut owner_account], ) ); } #[test] fn test_freeze_thaw_dups() { let program_id = crate::id(); let account1_key = Pubkey::new_unique(); let mut account1_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let account1_info: AccountInfo = (&account1_key, true, &mut account1_account).into(); let owner_key = Pubkey::new_unique(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let mint_info: AccountInfo = (&mint_key, true, &mut mint_account).into(); let rent_key = rent::id(); let mut rent_sysvar = rent_sysvar(); let rent_info: AccountInfo = (&rent_key, false, &mut rent_sysvar).into(); // create mint do_process_instruction_dups( initialize_mint(&program_id, &mint_key, &owner_key, Some(&account1_key), 2).unwrap(), vec![mint_info.clone(), rent_info.clone()], ) .unwrap(); // create account do_process_instruction_dups( initialize_account(&program_id, &account1_key, &mint_key, &account1_key).unwrap(), vec![ account1_info.clone(), mint_info.clone(), account1_info.clone(), rent_info.clone(), ], ) .unwrap(); // freeze where mint freeze_authority is account do_process_instruction_dups( freeze_account(&program_id, &account1_key, &mint_key, &account1_key, &[]).unwrap(), vec![ account1_info.clone(), mint_info.clone(), account1_info.clone(), ], ) .unwrap(); // thaw where mint freeze_authority is account let mut account = Account::unpack_unchecked(&account1_info.data.borrow()).unwrap(); account.state = AccountState::Frozen; Account::pack(account, &mut account1_info.data.borrow_mut()).unwrap(); do_process_instruction_dups( thaw_account(&program_id, &account1_key, &mint_key, &account1_key, &[]).unwrap(), vec![ account1_info.clone(), mint_info.clone(), account1_info.clone(), ], ) .unwrap(); } #[test] fn test_freeze_account() { let program_id = crate::id(); let account_key = Pubkey::new_unique(); let mut account_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let account_owner_key = Pubkey::new_unique(); let mut account_owner_account = SolanaAccount::default(); let owner_key = Pubkey::new_unique(); let mut owner_account = SolanaAccount::default(); let owner2_key = Pubkey::new_unique(); let mut owner2_account = SolanaAccount::default(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let mut rent_sysvar = rent_sysvar(); // create new mint with owner different from account owner do_process_instruction( initialize_mint(&program_id, &mint_key, &owner_key, None, 2).unwrap(), vec![&mut mint_account, &mut rent_sysvar], ) .unwrap(); // create account do_process_instruction( initialize_account(&program_id, &account_key, &mint_key, &account_owner_key).unwrap(), vec![ &mut account_account, &mut mint_account, &mut account_owner_account, &mut rent_sysvar, ], ) .unwrap(); // mint to account do_process_instruction( mint_to(&program_id, &mint_key, &account_key, &owner_key, &[], 1000).unwrap(), vec![&mut mint_account, &mut account_account, &mut owner_account], ) .unwrap(); // mint cannot freeze assert_eq!( Err(TokenError::MintCannotFreeze.into()), do_process_instruction( freeze_account(&program_id, &account_key, &mint_key, &owner_key, &[]).unwrap(), vec![&mut account_account, &mut mint_account, &mut owner_account], ) ); // missing freeze_authority let mut mint = Mint::unpack_unchecked(&mint_account.data).unwrap(); mint.freeze_authority = COption::Some(owner_key); Mint::pack(mint, &mut mint_account.data).unwrap(); assert_eq!( Err(TokenError::OwnerMismatch.into()), do_process_instruction( freeze_account(&program_id, &account_key, &mint_key, &owner2_key, &[]).unwrap(), vec![&mut account_account, &mut mint_account, &mut owner2_account], ) ); // check explicit thaw assert_eq!( Err(TokenError::InvalidState.into()), do_process_instruction( thaw_account(&program_id, &account_key, &mint_key, &owner2_key, &[]).unwrap(), vec![&mut account_account, &mut mint_account, &mut owner2_account], ) ); // freeze do_process_instruction( freeze_account(&program_id, &account_key, &mint_key, &owner_key, &[]).unwrap(), vec![&mut account_account, &mut mint_account, &mut owner_account], ) .unwrap(); let account = Account::unpack_unchecked(&account_account.data).unwrap(); assert_eq!(account.state, AccountState::Frozen); // check explicit freeze assert_eq!( Err(TokenError::InvalidState.into()), do_process_instruction( freeze_account(&program_id, &account_key, &mint_key, &owner_key, &[]).unwrap(), vec![&mut account_account, &mut mint_account, &mut owner_account], ) ); // check thaw authority assert_eq!( Err(TokenError::OwnerMismatch.into()), do_process_instruction( thaw_account(&program_id, &account_key, &mint_key, &owner2_key, &[]).unwrap(), vec![&mut account_account, &mut mint_account, &mut owner2_account], ) ); // thaw do_process_instruction( thaw_account(&program_id, &account_key, &mint_key, &owner_key, &[]).unwrap(), vec![&mut account_account, &mut mint_account, &mut owner_account], ) .unwrap(); let account = Account::unpack_unchecked(&account_account.data).unwrap(); assert_eq!(account.state, AccountState::Initialized); } #[test] fn test_initialize_account2_and_3() { let program_id = crate::id(); let account_key = Pubkey::new_unique(); let mut account_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let mut account2_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let mut account3_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let owner_key = Pubkey::new_unique(); let mut owner_account = SolanaAccount::default(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let mut rent_sysvar = rent_sysvar(); // create mint do_process_instruction( initialize_mint(&program_id, &mint_key, &owner_key, None, 2).unwrap(), vec![&mut mint_account, &mut rent_sysvar], ) .unwrap(); do_process_instruction( initialize_account(&program_id, &account_key, &mint_key, &owner_key).unwrap(), vec![ &mut account_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); do_process_instruction( initialize_account2(&program_id, &account_key, &mint_key, &owner_key).unwrap(), vec![&mut account2_account, &mut mint_account, &mut rent_sysvar], ) .unwrap(); assert_eq!(account_account, account2_account); do_process_instruction( initialize_account3(&program_id, &account_key, &mint_key, &owner_key).unwrap(), vec![&mut account3_account, &mut mint_account], ) .unwrap(); assert_eq!(account_account, account3_account); } #[test] fn test_sync_native() { let program_id = crate::id(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let native_account_key = Pubkey::new_unique(); let lamports = 40; let mut native_account = SolanaAccount::new( account_minimum_balance() + lamports, Account::get_packed_len(), &program_id, ); let non_native_account_key = Pubkey::new_unique(); let mut non_native_account = SolanaAccount::new( account_minimum_balance() + 50, Account::get_packed_len(), &program_id, ); let owner_key = Pubkey::new_unique(); let mut owner_account = SolanaAccount::default(); let mut rent_sysvar = rent_sysvar(); // initialize non-native mint do_process_instruction( initialize_mint(&program_id, &mint_key, &owner_key, None, 2).unwrap(), vec![&mut mint_account, &mut rent_sysvar], ) .unwrap(); // initialize non-native account do_process_instruction( initialize_account(&program_id, &non_native_account_key, &mint_key, &owner_key) .unwrap(), vec![ &mut non_native_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); let account = Account::unpack_unchecked(&non_native_account.data).unwrap(); assert!(!account.is_native()); assert_eq!(account.amount, 0); // fail sync non-native assert_eq!( Err(TokenError::NonNativeNotSupported.into()), do_process_instruction( sync_native(&program_id, &non_native_account_key,).unwrap(), vec![&mut non_native_account], ) ); // fail sync uninitialized assert_eq!( Err(ProgramError::UninitializedAccount), do_process_instruction( sync_native(&program_id, &native_account_key,).unwrap(), vec![&mut native_account], ) ); // wrap native account do_process_instruction( initialize_account( &program_id, &native_account_key, &crate::native_mint::id(), &owner_key, ) .unwrap(), vec![ &mut native_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); // fail sync, not owned by program let not_program_id = Pubkey::new_unique(); native_account.owner = not_program_id; assert_eq!( Err(ProgramError::IncorrectProgramId), do_process_instruction( sync_native(&program_id, &native_account_key,).unwrap(), vec![&mut native_account], ) ); native_account.owner = program_id; let account = Account::unpack_unchecked(&native_account.data).unwrap(); assert!(account.is_native()); assert_eq!(account.amount, lamports); // sync, no change do_process_instruction( sync_native(&program_id, &native_account_key).unwrap(), vec![&mut native_account], ) .unwrap(); let account = Account::unpack_unchecked(&native_account.data).unwrap(); assert_eq!(account.amount, lamports); // transfer sol let new_lamports = lamports + 50; native_account.lamports = account_minimum_balance() + new_lamports; // success sync do_process_instruction( sync_native(&program_id, &native_account_key).unwrap(), vec![&mut native_account], ) .unwrap(); let account = Account::unpack_unchecked(&native_account.data).unwrap(); assert_eq!(account.amount, new_lamports); // reduce sol native_account.lamports -= 1; // fail sync assert_eq!( Err(TokenError::InvalidState.into()), do_process_instruction( sync_native(&program_id, &native_account_key,).unwrap(), vec![&mut native_account], ) ); } #[test] #[serial] fn test_get_account_data_size() { // see integration tests for return-data validity let program_id = crate::id(); let owner_key = Pubkey::new_unique(); let mut rent_sysvar = rent_sysvar(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let mint_key = Pubkey::new_unique(); // fail if an invalid mint is passed in assert_eq!( Err(TokenError::InvalidMint.into()), do_process_instruction( get_account_data_size(&program_id, &mint_key).unwrap(), vec![&mut mint_account], ) ); do_process_instruction( initialize_mint(&program_id, &mint_key, &owner_key, None, 2).unwrap(), vec![&mut mint_account, &mut rent_sysvar], ) .unwrap(); set_expected_data(Account::LEN.to_le_bytes().to_vec()); do_process_instruction( get_account_data_size(&program_id, &mint_key).unwrap(), vec![&mut mint_account], ) .unwrap(); } #[test] fn test_initialize_immutable_owner() { let program_id = crate::id(); let account_key = Pubkey::new_unique(); let mut account_account = SolanaAccount::new( account_minimum_balance(), Account::get_packed_len(), &program_id, ); let owner_key = Pubkey::new_unique(); let mut owner_account = SolanaAccount::default(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let mut rent_sysvar = rent_sysvar(); // create mint do_process_instruction( initialize_mint(&program_id, &mint_key, &owner_key, None, 2).unwrap(), vec![&mut mint_account, &mut rent_sysvar], ) .unwrap(); // success initialize immutable do_process_instruction( initialize_immutable_owner(&program_id, &account_key).unwrap(), vec![&mut account_account], ) .unwrap(); // create account do_process_instruction( initialize_account(&program_id, &account_key, &mint_key, &owner_key).unwrap(), vec![ &mut account_account, &mut mint_account, &mut owner_account, &mut rent_sysvar, ], ) .unwrap(); // fail post-init assert_eq!( Err(TokenError::AlreadyInUse.into()), do_process_instruction( initialize_immutable_owner(&program_id, &account_key).unwrap(), vec![&mut account_account], ) ); } #[test] #[serial] fn test_amount_to_ui_amount() { let program_id = crate::id(); let owner_key = Pubkey::new_unique(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let mut rent_sysvar = rent_sysvar(); // fail if an invalid mint is passed in assert_eq!( Err(TokenError::InvalidMint.into()), do_process_instruction( amount_to_ui_amount(&program_id, &mint_key, 110).unwrap(), vec![&mut mint_account], ) ); // create mint do_process_instruction( initialize_mint(&program_id, &mint_key, &owner_key, None, 2).unwrap(), vec![&mut mint_account, &mut rent_sysvar], ) .unwrap(); set_expected_data("0.23".as_bytes().to_vec()); do_process_instruction( amount_to_ui_amount(&program_id, &mint_key, 23).unwrap(), vec![&mut mint_account], ) .unwrap(); set_expected_data("1.1".as_bytes().to_vec()); do_process_instruction( amount_to_ui_amount(&program_id, &mint_key, 110).unwrap(), vec![&mut mint_account], ) .unwrap(); set_expected_data("42".as_bytes().to_vec()); do_process_instruction( amount_to_ui_amount(&program_id, &mint_key, 4200).unwrap(), vec![&mut mint_account], ) .unwrap(); set_expected_data("0".as_bytes().to_vec()); do_process_instruction( amount_to_ui_amount(&program_id, &mint_key, 0).unwrap(), vec![&mut mint_account], ) .unwrap(); } #[test] #[serial] fn test_ui_amount_to_amount() { let program_id = crate::id(); let owner_key = Pubkey::new_unique(); let mint_key = Pubkey::new_unique(); let mut mint_account = SolanaAccount::new(mint_minimum_balance(), Mint::get_packed_len(), &program_id); let mut rent_sysvar = rent_sysvar(); // fail if an invalid mint is passed in assert_eq!( Err(TokenError::InvalidMint.into()), do_process_instruction( ui_amount_to_amount(&program_id, &mint_key, "1.1").unwrap(), vec![&mut mint_account], ) ); // create mint do_process_instruction( initialize_mint(&program_id, &mint_key, &owner_key, None, 2).unwrap(), vec![&mut mint_account, &mut rent_sysvar], ) .unwrap(); set_expected_data(23u64.to_le_bytes().to_vec()); do_process_instruction( ui_amount_to_amount(&program_id, &mint_key, "0.23").unwrap(), vec![&mut mint_account], ) .unwrap(); set_expected_data(20u64.to_le_bytes().to_vec()); do_process_instruction( ui_amount_to_amount(&program_id, &mint_key, "0.20").unwrap(), vec![&mut mint_account], ) .unwrap(); set_expected_data(20u64.to_le_bytes().to_vec()); do_process_instruction( ui_amount_to_amount(&program_id, &mint_key, "0.2000").unwrap(), vec![&mut mint_account], ) .unwrap(); set_expected_data(20u64.to_le_bytes().to_vec()); do_process_instruction( ui_amount_to_amount(&program_id, &mint_key, ".20").unwrap(), vec![&mut mint_account], ) .unwrap(); set_expected_data(110u64.to_le_bytes().to_vec()); do_process_instruction( ui_amount_to_amount(&program_id, &mint_key, "1.1").unwrap(), vec![&mut mint_account], ) .unwrap(); set_expected_data(110u64.to_le_bytes().to_vec()); do_process_instruction( ui_amount_to_amount(&program_id, &mint_key, "1.10").unwrap(), vec![&mut mint_account], ) .unwrap(); set_expected_data(4200u64.to_le_bytes().to_vec()); do_process_instruction( ui_amount_to_amount(&program_id, &mint_key, "42").unwrap(), vec![&mut mint_account], ) .unwrap(); set_expected_data(4200u64.to_le_bytes().to_vec()); do_process_instruction( ui_amount_to_amount(&program_id, &mint_key, "42.").unwrap(), vec![&mut mint_account], ) .unwrap(); set_expected_data(0u64.to_le_bytes().to_vec()); do_process_instruction( ui_amount_to_amount(&program_id, &mint_key, "0").unwrap(), vec![&mut mint_account], ) .unwrap(); // fail if invalid ui_amount passed in assert_eq!( Err(ProgramError::InvalidArgument), do_process_instruction( ui_amount_to_amount(&program_id, &mint_key, "").unwrap(), vec![&mut mint_account], ) ); assert_eq!( Err(ProgramError::InvalidArgument), do_process_instruction( ui_amount_to_amount(&program_id, &mint_key, ".").unwrap(), vec![&mut mint_account], ) ); assert_eq!( Err(ProgramError::InvalidArgument), do_process_instruction( ui_amount_to_amount(&program_id, &mint_key, "0.111").unwrap(), vec![&mut mint_account], ) ); assert_eq!( Err(ProgramError::InvalidArgument), do_process_instruction( ui_amount_to_amount(&program_id, &mint_key, "0.t").unwrap(), vec![&mut mint_account], ) ); } }
33.998426
100
0.513416
f7d477ebf3c96453fda667f907d4ba38bad21f58
20,503
#[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; use cosmwasm_std::{ from_binary, to_binary, Addr, BankMsg, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult, SubMsg, WasmMsg, }; use cw2::set_contract_version; use cw20::{Balance, Cw20Coin, Cw20CoinVerified, Cw20ExecuteMsg, Cw20ReceiveMsg}; use crate::error::ContractError; use crate::msg::{ CreateMsg, DetailsResponse, ExecuteMsg, InstantiateMsg, ListResponse, QueryMsg, ReceiveMsg, }; use crate::state::{all_escrow_ids, Escrow, GenericBalance, ESCROWS}; // version info for migration info const CONTRACT_NAME: &str = "crates.io:cw20-escrow"; const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); #[cfg_attr(not(feature = "library"), entry_point)] pub fn instantiate( deps: DepsMut, _env: Env, _info: MessageInfo, _msg: InstantiateMsg, ) -> StdResult<Response> { set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?; // no setup Ok(Response::default()) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn execute( deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg, ) -> Result<Response, ContractError> { match msg { ExecuteMsg::Create(msg) => { execute_create(deps, msg, Balance::from(info.funds), &info.sender) } ExecuteMsg::Approve { id } => execute_approve(deps, env, info, id), ExecuteMsg::TopUp { id } => execute_top_up(deps, id, Balance::from(info.funds)), ExecuteMsg::Refund { id } => execute_refund(deps, env, info, id), ExecuteMsg::Receive(msg) => execute_receive(deps, info, msg), } } pub fn execute_receive( deps: DepsMut, info: MessageInfo, wrapper: Cw20ReceiveMsg, ) -> Result<Response, ContractError> { let msg: ReceiveMsg = from_binary(&wrapper.msg)?; let balance = Balance::Cw20(Cw20CoinVerified { address: info.sender, amount: wrapper.amount, }); let api = deps.api; match msg { ReceiveMsg::Create(msg) => { execute_create(deps, msg, balance, &api.addr_validate(&wrapper.sender)?) } ReceiveMsg::TopUp { id } => execute_top_up(deps, id, balance), } } pub fn execute_create( deps: DepsMut, msg: CreateMsg, balance: Balance, sender: &Addr, ) -> Result<Response, ContractError> { if balance.is_empty() { return Err(ContractError::EmptyBalance {}); } let mut cw20_whitelist = msg.addr_whitelist(deps.api)?; let escrow_balance = match balance { Balance::Native(balance) => GenericBalance { native: balance.0, cw20: vec![], }, Balance::Cw20(token) => { // make sure the token sent is on the whitelist by default if !cw20_whitelist.iter().any(|t| t == &token.address) { cw20_whitelist.push(token.address.clone()) } GenericBalance { native: vec![], cw20: vec![token], } } }; let escrow = Escrow { arbiter: deps.api.addr_validate(&msg.arbiter)?, recipient: deps.api.addr_validate(&msg.recipient)?, source: sender.clone(), end_height: msg.end_height, end_time: msg.end_time, balance: escrow_balance, cw20_whitelist, }; // try to store it, fail if the id was already in use ESCROWS.update(deps.storage, &msg.id, |existing| match existing { None => Ok(escrow), Some(_) => Err(ContractError::AlreadyInUse {}), })?; let res = Response::new().add_attributes(vec![("action", "create"), ("id", msg.id.as_str())]); Ok(res) } pub fn execute_top_up( deps: DepsMut, id: String, balance: Balance, ) -> Result<Response, ContractError> { if balance.is_empty() { return Err(ContractError::EmptyBalance {}); } // this fails is no escrow there let mut escrow = ESCROWS.load(deps.storage, &id)?; if let Balance::Cw20(token) = &balance { // ensure the token is on the whitelist if !escrow.cw20_whitelist.iter().any(|t| t == &token.address) { return Err(ContractError::NotInWhitelist {}); } }; escrow.balance.add_tokens(balance); // and save ESCROWS.save(deps.storage, &id, &escrow)?; let res = Response::new().add_attributes(vec![("action", "top_up"), ("id", id.as_str())]); Ok(res) } pub fn execute_approve( deps: DepsMut, env: Env, info: MessageInfo, id: String, ) -> Result<Response, ContractError> { // this fails is no escrow there let escrow = ESCROWS.load(deps.storage, &id)?; if info.sender != escrow.arbiter { Err(ContractError::Unauthorized {}) } else if escrow.is_expired(&env) { Err(ContractError::Expired {}) } else { // we delete the escrow ESCROWS.remove(deps.storage, &id); // send all tokens out let messages: Vec<SubMsg> = send_tokens(&escrow.recipient, &escrow.balance)?; Ok(Response::new() .add_attribute("action", "approve") .add_attribute("id", id) .add_attribute("to", escrow.recipient) .add_submessages(messages)) } } pub fn execute_refund( deps: DepsMut, env: Env, info: MessageInfo, id: String, ) -> Result<Response, ContractError> { // this fails is no escrow there let escrow = ESCROWS.load(deps.storage, &id)?; // the arbiter can send anytime OR anyone can send after expiration if !escrow.is_expired(&env) && info.sender != escrow.arbiter { Err(ContractError::Unauthorized {}) } else { // we delete the escrow ESCROWS.remove(deps.storage, &id); // send all tokens out let messages = send_tokens(&escrow.source, &escrow.balance)?; Ok(Response::new() .add_attribute("action", "refund") .add_attribute("id", id) .add_attribute("to", escrow.source) .add_submessages(messages)) } } fn send_tokens(to: &Addr, balance: &GenericBalance) -> StdResult<Vec<SubMsg>> { let native_balance = &balance.native; let mut msgs: Vec<SubMsg> = if native_balance.is_empty() { vec![] } else { vec![SubMsg::new(BankMsg::Send { to_address: to.into(), amount: native_balance.to_vec(), })] }; let cw20_balance = &balance.cw20; let cw20_msgs: StdResult<Vec<_>> = cw20_balance .iter() .map(|c| { let msg = Cw20ExecuteMsg::Transfer { recipient: to.into(), amount: c.amount, }; let exec = SubMsg::new(WasmMsg::Execute { contract_addr: c.address.to_string(), msg: to_binary(&msg)?, funds: vec![], }); Ok(exec) }) .collect(); msgs.append(&mut cw20_msgs?); Ok(msgs) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> { match msg { QueryMsg::List {} => to_binary(&query_list(deps)?), QueryMsg::Details { id } => to_binary(&query_details(deps, id)?), } } fn query_details(deps: Deps, id: String) -> StdResult<DetailsResponse> { let escrow = ESCROWS.load(deps.storage, &id)?; let cw20_whitelist = escrow.human_whitelist(); // transform tokens let native_balance = escrow.balance.native; let cw20_balance: StdResult<Vec<_>> = escrow .balance .cw20 .into_iter() .map(|token| { Ok(Cw20Coin { address: token.address.into(), amount: token.amount, }) }) .collect(); let details = DetailsResponse { id, arbiter: escrow.arbiter.into(), recipient: escrow.recipient.into(), source: escrow.source.into(), end_height: escrow.end_height, end_time: escrow.end_time, native_balance, cw20_balance: cw20_balance?, cw20_whitelist, }; Ok(details) } fn query_list(deps: Deps) -> StdResult<ListResponse> { Ok(ListResponse { escrows: all_escrow_ids(deps.storage)?, }) } #[cfg(test)] mod tests { use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info}; use cosmwasm_std::{coin, coins, CosmosMsg, StdError, Uint128}; use crate::msg::ExecuteMsg::TopUp; use super::*; #[test] fn happy_path_native() { let mut deps = mock_dependencies(); // instantiate an empty contract let instantiate_msg = InstantiateMsg {}; let info = mock_info(&String::from("anyone"), &[]); let res = instantiate(deps.as_mut(), mock_env(), info, instantiate_msg).unwrap(); assert_eq!(0, res.messages.len()); // create an escrow let create = CreateMsg { id: "foobar".to_string(), arbiter: String::from("arbitrate"), recipient: String::from("recd"), end_time: None, end_height: Some(123456), cw20_whitelist: None, }; let sender = String::from("source"); let balance = coins(100, "tokens"); let info = mock_info(&sender, &balance); let msg = ExecuteMsg::Create(create.clone()); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(0, res.messages.len()); assert_eq!(("action", "create"), res.attributes[0]); // ensure the details is what we expect let details = query_details(deps.as_ref(), "foobar".to_string()).unwrap(); assert_eq!( details, DetailsResponse { id: "foobar".to_string(), arbiter: String::from("arbitrate"), recipient: String::from("recd"), source: String::from("source"), end_height: Some(123456), end_time: None, native_balance: balance.clone(), cw20_balance: vec![], cw20_whitelist: vec![], } ); // approve it let id = create.id.clone(); let info = mock_info(&create.arbiter, &[]); let res = execute(deps.as_mut(), mock_env(), info, ExecuteMsg::Approve { id }).unwrap(); assert_eq!(1, res.messages.len()); assert_eq!(("action", "approve"), res.attributes[0]); assert_eq!( res.messages[0], SubMsg::new(CosmosMsg::Bank(BankMsg::Send { to_address: create.recipient, amount: balance, })) ); // second attempt fails (not found) let id = create.id.clone(); let info = mock_info(&create.arbiter, &[]); let err = execute(deps.as_mut(), mock_env(), info, ExecuteMsg::Approve { id }).unwrap_err(); assert!(matches!(err, ContractError::Std(StdError::NotFound { .. }))); } #[test] fn happy_path_cw20() { let mut deps = mock_dependencies(); // instantiate an empty contract let instantiate_msg = InstantiateMsg {}; let info = mock_info(&String::from("anyone"), &[]); let res = instantiate(deps.as_mut(), mock_env(), info, instantiate_msg).unwrap(); assert_eq!(0, res.messages.len()); // create an escrow let create = CreateMsg { id: "foobar".to_string(), arbiter: String::from("arbitrate"), recipient: String::from("recd"), end_time: None, end_height: None, cw20_whitelist: Some(vec![String::from("other-token")]), }; let receive = Cw20ReceiveMsg { sender: String::from("source"), amount: Uint128::new(100), msg: to_binary(&ExecuteMsg::Create(create.clone())).unwrap(), }; let token_contract = String::from("my-cw20-token"); let info = mock_info(&token_contract, &[]); let msg = ExecuteMsg::Receive(receive.clone()); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(0, res.messages.len()); assert_eq!(("action", "create"), res.attributes[0]); // ensure the whitelist is what we expect let details = query_details(deps.as_ref(), "foobar".to_string()).unwrap(); assert_eq!( details, DetailsResponse { id: "foobar".to_string(), arbiter: String::from("arbitrate"), recipient: String::from("recd"), source: String::from("source"), end_height: None, end_time: None, native_balance: vec![], cw20_balance: vec![Cw20Coin { address: String::from("my-cw20-token"), amount: Uint128::new(100), }], cw20_whitelist: vec![String::from("other-token"), String::from("my-cw20-token")], } ); // approve it let id = create.id.clone(); let info = mock_info(&create.arbiter, &[]); let res = execute(deps.as_mut(), mock_env(), info, ExecuteMsg::Approve { id }).unwrap(); assert_eq!(1, res.messages.len()); assert_eq!(("action", "approve"), res.attributes[0]); let send_msg = Cw20ExecuteMsg::Transfer { recipient: create.recipient, amount: receive.amount, }; assert_eq!( res.messages[0], SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: token_contract, msg: to_binary(&send_msg).unwrap(), funds: vec![] })) ); // second attempt fails (not found) let id = create.id.clone(); let info = mock_info(&create.arbiter, &[]); let err = execute(deps.as_mut(), mock_env(), info, ExecuteMsg::Approve { id }).unwrap_err(); assert!(matches!(err, ContractError::Std(StdError::NotFound { .. }))); } #[test] fn add_tokens_proper() { let mut tokens = GenericBalance::default(); tokens.add_tokens(Balance::from(vec![coin(123, "atom"), coin(789, "eth")])); tokens.add_tokens(Balance::from(vec![coin(456, "atom"), coin(12, "btc")])); assert_eq!( tokens.native, vec![coin(579, "atom"), coin(789, "eth"), coin(12, "btc")] ); } #[test] fn add_cw_tokens_proper() { let mut tokens = GenericBalance::default(); let bar_token = Addr::unchecked("bar_token"); let foo_token = Addr::unchecked("foo_token"); tokens.add_tokens(Balance::Cw20(Cw20CoinVerified { address: foo_token.clone(), amount: Uint128::new(12345), })); tokens.add_tokens(Balance::Cw20(Cw20CoinVerified { address: bar_token.clone(), amount: Uint128::new(777), })); tokens.add_tokens(Balance::Cw20(Cw20CoinVerified { address: foo_token.clone(), amount: Uint128::new(23400), })); assert_eq!( tokens.cw20, vec![ Cw20CoinVerified { address: foo_token, amount: Uint128::new(35745), }, Cw20CoinVerified { address: bar_token, amount: Uint128::new(777), } ] ); } #[test] fn top_up_mixed_tokens() { let mut deps = mock_dependencies(); // instantiate an empty contract let instantiate_msg = InstantiateMsg {}; let info = mock_info(&String::from("anyone"), &[]); let res = instantiate(deps.as_mut(), mock_env(), info, instantiate_msg).unwrap(); assert_eq!(0, res.messages.len()); // only accept these tokens let whitelist = vec![String::from("bar_token"), String::from("foo_token")]; // create an escrow with 2 native tokens let create = CreateMsg { id: "foobar".to_string(), arbiter: String::from("arbitrate"), recipient: String::from("recd"), end_time: None, end_height: None, cw20_whitelist: Some(whitelist), }; let sender = String::from("source"); let balance = vec![coin(100, "fee"), coin(200, "stake")]; let info = mock_info(&sender, &balance); let msg = ExecuteMsg::Create(create.clone()); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(0, res.messages.len()); assert_eq!(("action", "create"), res.attributes[0]); // top it up with 2 more native tokens let extra_native = vec![coin(250, "random"), coin(300, "stake")]; let info = mock_info(&sender, &extra_native); let top_up = ExecuteMsg::TopUp { id: create.id.clone(), }; let res = execute(deps.as_mut(), mock_env(), info, top_up).unwrap(); assert_eq!(0, res.messages.len()); assert_eq!(("action", "top_up"), res.attributes[0]); // top up with one foreign token let bar_token = String::from("bar_token"); let base = TopUp { id: create.id.clone(), }; let top_up = ExecuteMsg::Receive(Cw20ReceiveMsg { sender: String::from("random"), amount: Uint128::new(7890), msg: to_binary(&base).unwrap(), }); let info = mock_info(&bar_token, &[]); let res = execute(deps.as_mut(), mock_env(), info, top_up).unwrap(); assert_eq!(0, res.messages.len()); assert_eq!(("action", "top_up"), res.attributes[0]); // top with a foreign token not on the whitelist // top up with one foreign token let baz_token = String::from("baz_token"); let base = TopUp { id: create.id.clone(), }; let top_up = ExecuteMsg::Receive(Cw20ReceiveMsg { sender: String::from("random"), amount: Uint128::new(7890), msg: to_binary(&base).unwrap(), }); let info = mock_info(&baz_token, &[]); let err = execute(deps.as_mut(), mock_env(), info, top_up).unwrap_err(); assert_eq!(err, ContractError::NotInWhitelist {}); // top up with second foreign token let foo_token = String::from("foo_token"); let base = TopUp { id: create.id.clone(), }; let top_up = ExecuteMsg::Receive(Cw20ReceiveMsg { sender: String::from("random"), amount: Uint128::new(888), msg: to_binary(&base).unwrap(), }); let info = mock_info(&foo_token, &[]); let res = execute(deps.as_mut(), mock_env(), info, top_up).unwrap(); assert_eq!(0, res.messages.len()); assert_eq!(("action", "top_up"), res.attributes[0]); // approve it let id = create.id.clone(); let info = mock_info(&create.arbiter, &[]); let res = execute(deps.as_mut(), mock_env(), info, ExecuteMsg::Approve { id }).unwrap(); assert_eq!(("action", "approve"), res.attributes[0]); assert_eq!(3, res.messages.len()); // first message releases all native coins assert_eq!( res.messages[0], SubMsg::new(CosmosMsg::Bank(BankMsg::Send { to_address: create.recipient.clone(), amount: vec![coin(100, "fee"), coin(500, "stake"), coin(250, "random")], })) ); // second one release bar cw20 token let send_msg = Cw20ExecuteMsg::Transfer { recipient: create.recipient.clone(), amount: Uint128::new(7890), }; assert_eq!( res.messages[1], SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: bar_token, msg: to_binary(&send_msg).unwrap(), funds: vec![] })) ); // third one release foo cw20 token let send_msg = Cw20ExecuteMsg::Transfer { recipient: create.recipient, amount: Uint128::new(888), }; assert_eq!( res.messages[2], SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: foo_token, msg: to_binary(&send_msg).unwrap(), funds: vec![] })) ); } }
33.945364
100
0.558845
75aeb65a8f51705a84ac92a47b936112b5817ddb
5,609
//! Types used to extract Serde values from an HTTP request. use codegen::CallSite; use extract::{Context, Error, ExtractFuture}; use util::buf_stream::{self, BufStream}; use futures::{Future, Poll}; use serde::de::DeserializeOwned; use serde_urlencoded; /* * # TODO: Move this module to `codegen`? */ /// Extract a value using Serde #[derive(Debug)] pub struct SerdeFuture<T, B> { state: State<T, B>, is_json: bool, } #[derive(Debug)] enum State<T, B> { Complete(Result<T, Option<Error>>), Body(buf_stream::Collect<B, Vec<u8>>), } #[doc(hidden)] pub fn requires_body(callsite: &CallSite) -> bool { use codegen::Source::Body; match callsite.source() { Body => true, _ => false, } } impl<T, B> SerdeFuture<T, B> where T: DeserializeOwned, B: BufStream, { /// Immediately extract a value using only the HTTP request head pub fn new_extract(ctx: &Context) -> Self { use codegen::Source::*; match ctx.callsite().source() { Capture(_) => { unimplemented!(); } Header(_) => { unimplemented!(); } QueryString => { let query = ctx.request().uri() .path_and_query() .and_then(|path_and_query| path_and_query.query()) .unwrap_or(""); let res = serde_urlencoded::from_str(query) .map_err(|err| { use std::error::Error as E; if query.is_empty() { Some(Error::missing_argument()) } else { Some(Error::invalid_argument(&err.description())) } }); let state = State::Complete(res); SerdeFuture { state, is_json: false } } Body => { unimplemented!(); } Unknown => { unimplemented!(); } } } /// Extract a value using the HTTP request head and body pub fn new_extract_body(ctx: &Context, body: B) -> Self { use codegen::Source::*; match ctx.callsite().source() { Capture(_) => { unimplemented!("Capture"); } Header(_) => { unimplemented!("Header"); } QueryString => { unimplemented!("QueryString"); } Body => { use http::header; if let Some(value) = ctx.request().headers().get(header::CONTENT_TYPE) { let content_type = value.as_bytes().to_ascii_lowercase(); match &content_type[..] { b"application/json" => { let state = State::Body(body.collect()); SerdeFuture { state, is_json: true } } b"application/x-www-form-urlencoded" => { let state = State::Body(body.collect()); SerdeFuture { state, is_json: false } } _ => { let err = Error::web(::Error::from(::error::ErrorKind::bad_request())); let state = State::Complete(Err(Some(err))); SerdeFuture { state, is_json: false } } } } else { let err = Error::web(::Error::from(::error::ErrorKind::bad_request())); let state = State::Complete(Err(Some(err))); SerdeFuture { state, is_json: false } } } Unknown => { unimplemented!("Unknown"); } } } } impl<T, B> ExtractFuture for SerdeFuture<T, B> where T: DeserializeOwned, B: BufStream, { type Item = T; fn poll(&mut self) -> Poll<(), Error> { use self::State::*; loop { let res = match self.state { Complete(Err(ref mut e)) => { return Err(e.take().unwrap()); } Complete(Ok(_)) => { return Ok(().into()); } Body(ref mut collect) => { let res = collect.poll() // TODO: Is there a better way to handle errors? .map_err(|_| Error::internal_error()); let res = try_ready!(res); if self.is_json == true { ::serde_json::from_slice(&res[..]) .map_err(|_| { // TODO: Handle error better Some(Error::internal_error()) }) } else { ::serde_urlencoded::from_bytes(&res[..]) .map_err(|_| { // TODO: Handle error better Some(Error::internal_error()) }) } } }; self.state = State::Complete(res); } } fn extract(self) -> T { use self::State::Complete; match self.state { Complete(Ok(res)) => res, _ => panic!("invalid state"), } } }
29.835106
99
0.420039
908f9c4dc0f0fced86cd078a69dd1b80ceaed760
196
//! The Rust core error handling type //! //! This module provides the `Result<T, E>` type for returning and //! propagating errors. mod from_stream; #[doc(inline)] pub use std::result::Result;
19.6
66
0.69898
71ef79678308d9aa6725bedc6329f8fe533a42bb
1,453
pub struct IconPadding { props: crate::Props, } impl yew::Component for IconPadding { type Properties = crate::Props; type Message = (); fn create(props: Self::Properties, _: yew::prelude::ComponentLink<Self>) -> Self { Self { props } } fn update(&mut self, _: Self::Message) -> yew::prelude::ShouldRender { true } fn change(&mut self, _: Self::Properties) -> yew::prelude::ShouldRender { false } fn view(&self) -> yew::prelude::Html { yew::prelude::html! { <svg class=self.props.class.unwrap_or("") width=self.props.size.unwrap_or(24).to_string() height=self.props.size.unwrap_or(24).to_string() viewBox="0 0 24 24" fill=self.props.fill.unwrap_or("none") stroke=self.props.color.unwrap_or("currentColor") stroke-width=self.props.stroke_width.unwrap_or(2).to_string() stroke-linecap=self.props.stroke_linecap.unwrap_or("round") stroke-linejoin=self.props.stroke_linejoin.unwrap_or("round") > <svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24"><g><rect fill="none" height="24" width="24"/></g><g><path d="M3,3v18h18V3H3z M9,9H7V7h2V9z M13,9h-2V7h2V9z M17,9h-2V7h2V9z"/></g></svg> </svg> } } }
31.586957
264
0.574673
c163c0ced2ed462b30f27cf1ff25b98201d4bde8
417
// Copyright 2018 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. pub mod avdtp_facade; pub mod avrcp_facade; pub mod ble_advertise_facade; pub mod bt_sys_facade; pub mod commands; pub mod constants; pub mod facade; pub mod gatt_client_facade; pub mod gatt_server_facade; pub mod profile_server_facade; pub mod types;
26.0625
73
0.796163
e96074f4a80fbd24ebc2f8611ff04e9ff41769c4
19,714
// 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::iter::repeat; use cryptoutil::{copy_memory, read_u64v_le, write_u64v_le}; use digest::Digest; use mac::{Mac, MacResult}; use util::secure_memset; static IV : [u64; 8] = [ 0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179, ]; static SIGMA : [[usize; 16]; 12] = [ [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ], [ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 ], [ 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 ], [ 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 ], [ 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 ], [ 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 ], [ 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 ], [ 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 ], [ 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 ], [ 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13 , 0 ], [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ], [ 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 ], ]; const BLAKE2B_BLOCKBYTES : usize = 128; const BLAKE2B_OUTBYTES : usize = 64; const BLAKE2B_KEYBYTES : usize = 64; const BLAKE2B_SALTBYTES : usize = 16; const BLAKE2B_PERSONALBYTES : usize = 16; #[derive(Copy)] pub struct Blake2b { h: [u64; 8], t: [u64; 2], f: [u64; 2], buf: [u8; 2*BLAKE2B_BLOCKBYTES], buflen: usize, key: [u8; BLAKE2B_KEYBYTES], key_length: u8, last_node: u8, digest_length: u8, computed: bool, // whether the final digest has been computed param: Blake2bParam } impl Clone for Blake2b { fn clone(&self) -> Blake2b { *self } } #[derive(Copy, Clone)] struct Blake2bParam { digest_length: u8, key_length: u8, fanout: u8, depth: u8, leaf_length: u32, node_offset: u64, node_depth: u8, inner_length: u8, reserved: [u8; 14], salt: [u8; BLAKE2B_SALTBYTES], personal: [u8; BLAKE2B_PERSONALBYTES], } macro_rules! G( ($r:expr, $i:expr, $a:expr, $b:expr, $c:expr, $d:expr, $m:expr) => ({ $a = $a.wrapping_add($b).wrapping_add($m[SIGMA[$r][2*$i+0]]); $d = ($d ^ $a).rotate_right(32); $c = $c.wrapping_add($d); $b = ($b ^ $c).rotate_right(24); $a = $a.wrapping_add($b).wrapping_add($m[SIGMA[$r][2*$i+1]]); $d = ($d ^ $a).rotate_right(16); $c = $c .wrapping_add($d); $b = ($b ^ $c).rotate_right(63); })); macro_rules! round( ($r:expr, $v:expr, $m:expr) => ( { G!($r,0,$v[ 0],$v[ 4],$v[ 8],$v[12], $m); G!($r,1,$v[ 1],$v[ 5],$v[ 9],$v[13], $m); G!($r,2,$v[ 2],$v[ 6],$v[10],$v[14], $m); G!($r,3,$v[ 3],$v[ 7],$v[11],$v[15], $m); G!($r,4,$v[ 0],$v[ 5],$v[10],$v[15], $m); G!($r,5,$v[ 1],$v[ 6],$v[11],$v[12], $m); G!($r,6,$v[ 2],$v[ 7],$v[ 8],$v[13], $m); G!($r,7,$v[ 3],$v[ 4],$v[ 9],$v[14], $m); } )); impl Blake2b { fn set_lastnode(&mut self) { self.f[1] = 0xFFFFFFFFFFFFFFFF; } fn set_lastblock(&mut self) { if self.last_node!=0 { self.set_lastnode(); } self.f[0] = 0xFFFFFFFFFFFFFFFF; } fn increment_counter(&mut self, inc : u64) { self.t[0] += inc; self.t[1] += if self.t[0] < inc { 1 } else { 0 }; } fn init0(param: Blake2bParam, digest_length: u8, key: &[u8]) -> Blake2b { assert!(key.len() <= BLAKE2B_KEYBYTES); let mut b = Blake2b { h: IV, t: [0,0], f: [0,0], buf: [0; 2*BLAKE2B_BLOCKBYTES], buflen: 0, last_node: 0, digest_length: digest_length, computed: false, key: [0; BLAKE2B_KEYBYTES], key_length: key.len() as u8, param: param }; copy_memory(key, &mut b.key); b } fn apply_param(&mut self) { use std::io::Write; use cryptoutil::WriteExt; let mut param_bytes : [u8; 64] = [0; 64]; { let mut writer: &mut [u8] = &mut param_bytes; writer.write_u8(self.param.digest_length).unwrap(); writer.write_u8(self.param.key_length).unwrap(); writer.write_u8(self.param.fanout).unwrap(); writer.write_u8(self.param.depth).unwrap(); writer.write_u32_le(self.param.leaf_length).unwrap(); writer.write_u64_le(self.param.node_offset).unwrap(); writer.write_u8(self.param.node_depth).unwrap(); writer.write_u8(self.param.inner_length).unwrap(); writer.write_all(&self.param.reserved).unwrap(); writer.write_all(&self.param.salt).unwrap(); writer.write_all(&self.param.personal).unwrap(); } let mut param_words : [u64; 8] = [0; 8]; read_u64v_le(&mut param_words, &param_bytes); for (h, param_word) in self.h.iter_mut().zip(param_words.iter()) { *h = *h ^ *param_word; } } // init xors IV with input parameter block fn init_param( p: Blake2bParam, key: &[u8] ) -> Blake2b { let mut b = Blake2b::init0(p, p.digest_length, key); b.apply_param(); b } fn default_param(outlen: u8) -> Blake2bParam { Blake2bParam { digest_length: outlen, key_length: 0, fanout: 1, depth: 1, leaf_length: 0, node_offset: 0, node_depth: 0, inner_length: 0, reserved: [0; 14], salt: [0; BLAKE2B_SALTBYTES], personal: [0; BLAKE2B_PERSONALBYTES], } } pub fn new(outlen: usize) -> Blake2b { assert!(outlen > 0 && outlen <= BLAKE2B_OUTBYTES); Blake2b::init_param(Blake2b::default_param(outlen as u8), &[]) } fn apply_key(&mut self) { let mut block : [u8; BLAKE2B_BLOCKBYTES] = [0; BLAKE2B_BLOCKBYTES]; copy_memory(&self.key[..self.key_length as usize], &mut block); self.update(&block); secure_memset(&mut block[..], 0); } pub fn new_keyed(outlen: usize, key: &[u8] ) -> Blake2b { assert!(outlen > 0 && outlen <= BLAKE2B_OUTBYTES); assert!(key.len() > 0 && key.len() <= BLAKE2B_KEYBYTES); let param = Blake2bParam { digest_length: outlen as u8, key_length: key.len() as u8, fanout: 1, depth: 1, leaf_length: 0, node_offset: 0, node_depth: 0, inner_length: 0, reserved: [0; 14], salt: [0; BLAKE2B_SALTBYTES], personal: [0; BLAKE2B_PERSONALBYTES], }; let mut b = Blake2b::init_param(param, key); b.apply_key(); b } fn compress(&mut self) { let mut ms: [u64; 16] = [0; 16]; let mut vs: [u64; 16] = [0; 16]; read_u64v_le(&mut ms, &self.buf[0..BLAKE2B_BLOCKBYTES]); for (v, h) in vs.iter_mut().zip(self.h.iter()) { *v = *h; } vs[ 8] = IV[0]; vs[ 9] = IV[1]; vs[10] = IV[2]; vs[11] = IV[3]; vs[12] = self.t[0] ^ IV[4]; vs[13] = self.t[1] ^ IV[5]; vs[14] = self.f[0] ^ IV[6]; vs[15] = self.f[1] ^ IV[7]; round!( 0, vs, ms ); round!( 1, vs, ms ); round!( 2, vs, ms ); round!( 3, vs, ms ); round!( 4, vs, ms ); round!( 5, vs, ms ); round!( 6, vs, ms ); round!( 7, vs, ms ); round!( 8, vs, ms ); round!( 9, vs, ms ); round!( 10, vs, ms ); round!( 11, vs, ms ); for (h_elem, (v_low, v_high)) in self.h.iter_mut().zip( vs[0..8].iter().zip(vs[8..16].iter()) ) { *h_elem = *h_elem ^ *v_low ^ *v_high; } } fn update( &mut self, mut input: &[u8] ) { while input.len() > 0 { let left = self.buflen; let fill = 2 * BLAKE2B_BLOCKBYTES - left; if input.len() > fill { copy_memory(&input[0..fill], &mut self.buf[left..]); // Fill buffer self.buflen += fill; self.increment_counter( BLAKE2B_BLOCKBYTES as u64); self.compress(); let mut halves = self.buf.chunks_mut(BLAKE2B_BLOCKBYTES); let first_half = halves.next().unwrap(); let second_half = halves.next().unwrap(); copy_memory(second_half, first_half); self.buflen -= BLAKE2B_BLOCKBYTES; input = &input[fill..input.len()]; } else { // inlen <= fill copy_memory(input, &mut self.buf[left..]); self.buflen += input.len(); break; } } } fn finalize( &mut self, out: &mut [u8] ) { assert!(out.len() == self.digest_length as usize); if !self.computed { if self.buflen > BLAKE2B_BLOCKBYTES { self.increment_counter(BLAKE2B_BLOCKBYTES as u64); self.compress(); self.buflen -= BLAKE2B_BLOCKBYTES; let mut halves = self.buf.chunks_mut(BLAKE2B_BLOCKBYTES); let first_half = halves.next().unwrap(); let second_half = halves.next().unwrap(); copy_memory(second_half, first_half); } let incby = self.buflen as u64; self.increment_counter(incby); self.set_lastblock(); for b in self.buf[self.buflen..].iter_mut() { *b = 0; } self.compress(); write_u64v_le(&mut self.buf[0..64], &self.h); self.computed = true; } let outlen = out.len(); copy_memory(&self.buf[0..outlen], out); } pub fn reset(&mut self) { for (h_elem, iv_elem) in self.h.iter_mut().zip(IV.iter()) { *h_elem = *iv_elem; } for t_elem in self.t.iter_mut() { *t_elem = 0; } for f_elem in self.f.iter_mut() { *f_elem = 0; } for b in self.buf.iter_mut() { *b = 0; } self.buflen = 0; self.last_node = 0; self.computed = false; self.apply_param(); if self.key_length > 0 { self.apply_key(); } } pub fn blake2b(out: &mut[u8], input: &[u8], key: &[u8]) { let mut hasher : Blake2b = if key.len() > 0 { Blake2b::new_keyed(out.len(), key) } else { Blake2b::new(out.len()) }; hasher.update(input); hasher.finalize(out); } } impl Digest for Blake2b { fn reset(&mut self) { Blake2b::reset(self); } fn input(&mut self, msg: &[u8]) { self.update(msg); } fn result(&mut self, out: &mut [u8]) { self.finalize(out); } fn output_bits(&self) -> usize { 8 * (self.digest_length as usize) } fn block_size(&self) -> usize { 8 * BLAKE2B_BLOCKBYTES } } impl Mac for Blake2b { /** * Process input data. * * # Arguments * * data - The input data to process. * */ fn input(&mut self, data: &[u8]) { self.update(data); } /** * Reset the Mac state to begin processing another input stream. */ fn reset(&mut self) { Blake2b::reset(self); } /** * Obtain the result of a Mac computation as a MacResult. */ fn result(&mut self) -> MacResult { let mut mac: Vec<u8> = repeat(0).take(self.digest_length as usize).collect(); self.raw_result(&mut mac); MacResult::new_from_owned(mac) } /** * Obtain the result of a Mac computation as [u8]. This method should be used very carefully * since incorrect use of the Mac code could result in permitting a timing attack which defeats * the security provided by a Mac function. */ fn raw_result(&mut self, output: &mut [u8]) { self.finalize(output); } /** * Get the size of the Mac code, in bytes. */ fn output_bytes(&self) -> usize { self.digest_length as usize } } #[cfg(test)] mod digest_tests { //use cryptoutil::test::test_digest_1million_random; use blake2b::Blake2b; use digest::Digest; use serialize::hex::FromHex; struct Test { input: Vec<u8>, output: Vec<u8>, key: Option<Vec<u8>>, } fn test_hash(tests: &[Test]) { for t in tests { let mut sh = match t.key { Some(ref key) => Blake2b::new_keyed(64, &key), None => Blake2b::new(64) }; // Test that it works when accepting the message all at once sh.input(&t.input[..]); let mut out = [0u8; 64]; sh.result(&mut out); assert!(&out[..] == &t.output[..]); sh.reset(); // Test that it works when accepting the message in pieces let len = t.input.len(); let mut left = len; while left > 0 { let take = (left + 1) / 2; sh.input(&t.input[len - left..take + len - left]); left -= take; } let mut out = [0u8; 64]; sh.result(&mut out); assert!(&out[..] == &t.output[..]); sh.reset(); } } #[test] fn test_blake2b_digest() { let tests = vec![ // Examples from wikipedia Test { input: vec![], output: "786a02f742015903c6c6fd852552d272\ 912f4740e15847618a86e217f71f5419\ d25e1031afee585313896444934eb04b\ 903a685b1448b755d56f701afe9be2ce".from_hex().unwrap(), key: None }, Test { input: "The quick brown fox jumps over the lazy dog".as_bytes().to_vec(), output: "a8add4bdddfd93e4877d2746e62817b1\ 16364a1fa7bc148d95090bc7333b3673\ f82401cf7aa2e4cb1ecd90296e3f14cb\ 5413f8ed77be73045b13914cdcd6a918".from_hex().unwrap(), key: None }, // from: https://github.com/BLAKE2/BLAKE2/blob/master/testvectors/blake2b-test.txt Test { input: vec![0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe], output: vec![0x14, 0x27, 0x09, 0xd6, 0x2e, 0x28, 0xfc, 0xcc, 0xd0, 0xaf, 0x97, 0xfa, 0xd0, 0xf8, 0x46, 0x5b, 0x97, 0x1e, 0x82, 0x20, 0x1d, 0xc5, 0x10, 0x70, 0xfa, 0xa0, 0x37, 0x2a, 0xa4, 0x3e, 0x92, 0x48, 0x4b, 0xe1, 0xc1, 0xe7, 0x3b, 0xa1, 0x09, 0x06, 0xd5, 0xd1, 0x85, 0x3d, 0xb6, 0xa4, 0x10, 0x6e, 0x0a, 0x7b, 0xf9, 0x80, 0x0d, 0x37, 0x3d, 0x6d, 0xee, 0x2d, 0x46, 0xd6, 0x2e, 0xf2, 0xa4, 0x61], key: Some(vec![0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f]) }, ]; test_hash(&tests[..]); } } #[cfg(test)] mod mac_tests { use blake2b::Blake2b; use mac::Mac; #[test] fn test_blake2b_mac() { let key: Vec<u8> = (0..64).map(|i| i).collect(); let mut m = Blake2b::new_keyed(64, &key[..]); m.input(&[1,2,4,8]); let expected = [ 0x8e, 0xc6, 0xcb, 0x71, 0xc4, 0x5c, 0x3c, 0x90, 0x91, 0xd0, 0x8a, 0x37, 0x1e, 0xa8, 0x5d, 0xc1, 0x22, 0xb5, 0xc8, 0xe2, 0xd9, 0xe5, 0x71, 0x42, 0xbf, 0xef, 0xce, 0x42, 0xd7, 0xbc, 0xf8, 0x8b, 0xb0, 0x31, 0x27, 0x88, 0x2e, 0x51, 0xa9, 0x21, 0x44, 0x62, 0x08, 0xf6, 0xa3, 0x58, 0xa9, 0xe0, 0x7d, 0x35, 0x3b, 0xd3, 0x1c, 0x41, 0x70, 0x15, 0x62, 0xac, 0xd5, 0x39, 0x4e, 0xee, 0x73, 0xae, ]; assert_eq!(m.result().code().to_vec(), expected.to_vec()); } } #[cfg(all(test, feature = "with-bench"))] mod bench { use test::Bencher; use digest::Digest; use blake2b::Blake2b; #[bench] pub fn blake2b_10(bh: & mut Bencher) { let mut sh = Blake2b::new(64); let bytes = [1u8; 10]; bh.iter( || { sh.input(&bytes); }); bh.bytes = bytes.len() as u64; } #[bench] pub fn blake2b_1k(bh: & mut Bencher) { let mut sh = Blake2b::new(64); let bytes = [1u8; 1024]; bh.iter( || { sh.input(&bytes); }); bh.bytes = bytes.len() as u64; } #[bench] pub fn blake2b_64k(bh: & mut Bencher) { let mut sh = Blake2b::new(64); let bytes = [1u8; 65536]; bh.iter( || { sh.input(&bytes); }); bh.bytes = bytes.len() as u64; } }
34.953901
124
0.500406
67229a9234d6805b121ec354a910525b4407ef19
11,563
use colored::*; use std::collections::{HashMap, HashSet}; use std::fmt; use std::fmt::Write; use std::fs; use std::path::PathBuf; use diplomat_core::ast; use diplomat_core::Env; use indenter::indented; #[cfg(test)] #[macro_use] mod test_util; mod types; mod structs; use structs::*; use crate::cpp::util::gen_comment_block; mod conversions; pub mod docs; mod config; mod util; static RUNTIME_HPP: &str = include_str!("runtime.hpp"); pub fn gen_bindings( env: &Env, library_config_path: &Option<PathBuf>, outs: &mut HashMap<String, String>, ) -> fmt::Result { super::c::gen_bindings(env, outs)?; let mut library_config = config::LibraryConfig::default(); if let Some(path) = library_config_path { // Should be fine, we've already verified the path if let Ok(contents) = fs::read_to_string(path) { match toml::from_str(&contents) { Ok(config) => library_config = config, Err(err) => { eprintln!( "{}Unable to parse library configuration file: {:?}\n{}", "Error: ".red().bold(), path, err, ); std::process::exit(1); } } } } let diplomat_runtime_out = outs .entry("diplomat_runtime.hpp".to_string()) .or_insert_with(String::new); write!(diplomat_runtime_out, "{}", RUNTIME_HPP)?; let all_types = crate::util::get_all_custom_types(env); for (in_path, typ) in &all_types { let out = outs .entry(format!("{}.hpp", typ.name())) .or_insert_with(String::new); writeln!(out, "#ifndef {}_HPP", typ.name())?; writeln!(out, "#define {}_HPP", typ.name())?; writeln!(out, "#include <stdint.h>")?; writeln!(out, "#include <stddef.h>")?; writeln!(out, "#include <stdbool.h>")?; writeln!(out, "#include <algorithm>")?; writeln!(out, "#include <memory>")?; writeln!(out, "#include <variant>")?; for header in &library_config.headers { writeln!(out, "{}", header)?; } writeln!(out, "#include \"diplomat_runtime.hpp\"")?; writeln!(out)?; writeln!(out, "namespace capi {{")?; writeln!(out, "#include \"{}.h\"", typ.name())?; writeln!(out, "}}")?; writeln!(out)?; let mut seen_includes = HashSet::new(); seen_includes.insert(format!("#include \"{}.hpp\"", typ.name())); match typ { ast::CustomType::Opaque(_) => {} ast::CustomType::Enum(enm) => { writeln!(out)?; gen_comment_block(out, &enm.doc_lines)?; writeln!(out, "enum struct {} {{", enm.name)?; let mut enm_indent = indented(out).with_str(" "); for (name, discriminant, doc_lines) in enm.variants.iter() { gen_comment_block(&mut enm_indent, doc_lines)?; writeln!(&mut enm_indent, "{} = {},", name, discriminant)?; } writeln!(out, "}};")?; } ast::CustomType::Struct(strct) => { for (_, typ, _) in &strct.fields { gen_includes( typ, in_path, true, false, true, env, &mut seen_includes, out, )?; } } } for method in typ.methods() { for param in &method.params { gen_includes( &param.ty, in_path, true, false, false, env, &mut seen_includes, out, )?; } if let Some(return_type) = method.return_type.as_ref() { gen_includes( return_type, in_path, true, false, false, env, &mut seen_includes, out, )?; } } match typ { ast::CustomType::Opaque(_) => { writeln!(out)?; gen_struct(typ, in_path, true, env, &library_config, out)?; } ast::CustomType::Enum(_) => {} ast::CustomType::Struct(_) => { writeln!(out)?; gen_struct(typ, in_path, true, env, &library_config, out)?; } } writeln!(out)?; for method in typ.methods() { for param in &method.params { gen_includes( &param.ty, in_path, false, false, false, env, &mut seen_includes, out, )?; } if let Some(return_type) = method.return_type.as_ref() { gen_includes( return_type, in_path, false, false, false, env, &mut seen_includes, out, )?; } } match typ { ast::CustomType::Opaque(_) => { writeln!(out)?; gen_struct(typ, in_path, false, env, &library_config, out)?; } ast::CustomType::Enum(_) => {} ast::CustomType::Struct(_) => { writeln!(out)?; gen_struct(typ, in_path, false, env, &library_config, out)?; } } writeln!(out, "#endif")? } Ok(()) } #[allow(clippy::too_many_arguments)] fn gen_includes<W: fmt::Write>( typ: &ast::TypeName, in_path: &ast::Path, pre_struct: bool, behind_ref: bool, for_field: bool, env: &Env, seen_includes: &mut HashSet<String>, out: &mut W, ) -> fmt::Result { match typ { ast::TypeName::Named(_) => { let (_, custom_typ) = typ.resolve_with_path(in_path, env); match custom_typ { ast::CustomType::Opaque(_) => { if pre_struct { let decl = format!("class {};", custom_typ.name()); if !seen_includes.contains(&decl) { writeln!(out, "{}", decl)?; seen_includes.insert(decl); } } else { let include = format!("#include \"{}.hpp\"", custom_typ.name()); if !seen_includes.contains(&include) { writeln!(out, "{}", include)?; seen_includes.insert(include); } } } ast::CustomType::Struct(_) => { if pre_struct && (!for_field || behind_ref) { let decl = format!("struct {};", custom_typ.name()); if !seen_includes.contains(&decl) { writeln!(out, "{}", decl)?; seen_includes.insert(decl); } } else { let include = format!("#include \"{}.hpp\"", custom_typ.name()); if !seen_includes.contains(&include) { writeln!(out, "{}", include)?; seen_includes.insert(include); } } } ast::CustomType::Enum(_) => { let include = format!("#include \"{}.hpp\"", custom_typ.name()); if !seen_includes.contains(&include) { writeln!(out, "{}", include)?; seen_includes.insert(include); } } } } ast::TypeName::Box(underlying) => { gen_includes( underlying, in_path, pre_struct, true, for_field, env, seen_includes, out, )?; } ast::TypeName::Reference(underlying, _mut, _lt) => { gen_includes( underlying, in_path, pre_struct, true, for_field, env, seen_includes, out, )?; } ast::TypeName::Primitive(_) => {} ast::TypeName::Option(underlying) => { gen_includes( underlying, in_path, pre_struct, behind_ref, for_field, env, seen_includes, out, )?; } ast::TypeName::Result(ok, err) => { gen_includes( ok.as_ref(), in_path, pre_struct, behind_ref, for_field, env, seen_includes, out, )?; gen_includes( err.as_ref(), in_path, pre_struct, behind_ref, for_field, env, seen_includes, out, )?; } ast::TypeName::Writeable => {} ast::TypeName::StrReference => {} ast::TypeName::PrimitiveSlice(_) => {} ast::TypeName::Unit => {} } Ok(()) } #[cfg(test)] mod tests { #[test] fn test_cross_module_struct_fields() { test_file! { #[diplomat::bridge] mod mod1 { use super::mod2::Bar; struct Foo { x: Bar, } } #[diplomat::bridge] mod mod2 { use super::mod1::Foo; struct Bar { y: Box<Foo>, } } } } #[test] fn test_cross_module_struct_methods() { test_file! { #[diplomat::bridge] mod mod1 { use super::mod2::Bar; #[diplomat::opaque] struct Foo; impl Foo { pub fn to_bar(&self) -> Bar { unimplemented!() } } } #[diplomat::bridge] mod mod2 { use super::mod1::Foo; struct Bar { y: Box<Foo>, } } } } #[test] fn test_enum_documentation() { test_file! { #[diplomat::bridge] mod ffi { /// Documentation for MyEnum. enum MyEnum { /// All about A. A, /// All about B. B, /// All about C. C } } } } }
27.862651
88
0.393237
5bf2919af360f294b32537a787770d849f7e805d
5,801
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use crate::EventController; use crate::Gesture; use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; glib::glib_wrapper! { pub struct GestureSingle(Object<ffi::GtkGestureSingle, ffi::GtkGestureSingleClass>) @extends Gesture, EventController; match fn { get_type => || ffi::gtk_gesture_single_get_type(), } } pub const NONE_GESTURE_SINGLE: Option<&GestureSingle> = None; pub trait GestureSingleExt: 'static { fn get_button(&self) -> u32; fn get_current_button(&self) -> u32; fn get_current_sequence(&self) -> Option<gdk::EventSequence>; fn get_exclusive(&self) -> bool; fn get_touch_only(&self) -> bool; fn set_button(&self, button: u32); fn set_exclusive(&self, exclusive: bool); fn set_touch_only(&self, touch_only: bool); fn connect_property_button_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_exclusive_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_touch_only_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<GestureSingle>> GestureSingleExt for O { fn get_button(&self) -> u32 { unsafe { ffi::gtk_gesture_single_get_button(self.as_ref().to_glib_none().0) } } fn get_current_button(&self) -> u32 { unsafe { ffi::gtk_gesture_single_get_current_button(self.as_ref().to_glib_none().0) } } fn get_current_sequence(&self) -> Option<gdk::EventSequence> { unsafe { from_glib_full(ffi::gtk_gesture_single_get_current_sequence( self.as_ref().to_glib_none().0, )) } } fn get_exclusive(&self) -> bool { unsafe { from_glib(ffi::gtk_gesture_single_get_exclusive( self.as_ref().to_glib_none().0, )) } } fn get_touch_only(&self) -> bool { unsafe { from_glib(ffi::gtk_gesture_single_get_touch_only( self.as_ref().to_glib_none().0, )) } } fn set_button(&self, button: u32) { unsafe { ffi::gtk_gesture_single_set_button(self.as_ref().to_glib_none().0, button); } } fn set_exclusive(&self, exclusive: bool) { unsafe { ffi::gtk_gesture_single_set_exclusive( self.as_ref().to_glib_none().0, exclusive.to_glib(), ); } } fn set_touch_only(&self, touch_only: bool) { unsafe { ffi::gtk_gesture_single_set_touch_only( self.as_ref().to_glib_none().0, touch_only.to_glib(), ); } } fn connect_property_button_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_button_trampoline<P, F: Fn(&P) + 'static>( this: *mut ffi::GtkGestureSingle, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) where P: IsA<GestureSingle>, { let f: &F = &*(f as *const F); f(&GestureSingle::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::button\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_button_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } fn connect_property_exclusive_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_exclusive_trampoline<P, F: Fn(&P) + 'static>( this: *mut ffi::GtkGestureSingle, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) where P: IsA<GestureSingle>, { let f: &F = &*(f as *const F); f(&GestureSingle::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::exclusive\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_exclusive_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } fn connect_property_touch_only_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_touch_only_trampoline<P, F: Fn(&P) + 'static>( this: *mut ffi::GtkGestureSingle, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) where P: IsA<GestureSingle>, { let f: &F = &*(f as *const F); f(&GestureSingle::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::touch-only\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_touch_only_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } } impl fmt::Display for GestureSingle { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("GestureSingle") } }
31.356757
122
0.553698
647f382999353bbecfdf5c337cf48b46d0cd3004
13,358
// A drawer struct for drawing the map and battle items use super::map::*; use super::responses::*; use super::Battle; use colours; use context::Context; use resources::Image; use utils::convert_rotation; const TILE_WIDTH: f32 = 48.0; const TILE_HEIGHT: f32 = 24.0; // Convert coordinates from isometric pub fn from_map_coords(x: f32, y: f32) -> (f32, f32) { (x - y, -(x + y)) } // Convert coordinates to isometric pub fn to_map_coords(x: f32, y: f32) -> (f32, f32) { (y + x, y - x) } // A camera for drawing the map with #[derive(Serialize, Deserialize)] pub struct Camera { pub x: f32, pub y: f32, zoom: f32, } impl Camera { const SPEED: f32 = 10.0; const ZOOM_SPEED: f32 = 1.0; const DEFAULT_ZOOM: f32 = 2.0; const ZOOM_MAX: f32 = 10.0; const ZOOM_MIN: f32 = 1.0; pub fn new() -> Camera { Camera { x: 0.0, y: 0.0, zoom: Self::DEFAULT_ZOOM, } } pub fn move_x(&mut self, step: f32, map: &Map) { let (x, y) = self.map_location(); let width = map.tiles.width() as f32; let height = map.tiles.height() as f32; if step > 0.0 { if x < width && y > 0.0 { self.x += step * Self::SPEED; } } else if x > 0.0 && y < height { self.x += step * Self::SPEED; } } pub fn move_y(&mut self, step: f32, map: &Map) { let (x, y) = self.map_location(); let width = map.tiles.width() as f32; let height = map.tiles.height() as f32; if step > 0.0 { if x > 0.0 && y > 0.0 { self.y += step * Self::SPEED; } } else if x < width && y < height { self.y += step * Self::SPEED; } } // Zoom in the camera by a particular amount, checking if it's zoomed in/out too far pub fn zoom(&mut self, amount: f32) { self.zoom += amount * self.zoom * Self::ZOOM_SPEED; if self.zoom > Self::ZOOM_MAX { self.zoom = Self::ZOOM_MAX; } if self.zoom < Self::ZOOM_MIN { self.zoom = Self::ZOOM_MIN; } } pub fn set_to(&mut self, x: usize, y: usize) { let (x, y) = (x as f32, y as f32); let (x, y) = from_map_coords(x, y); self.x = x; self.y = y + 0.5; } pub fn map_location(&self) -> (f32, f32) { let x = self.x / 2.0; let y = -self.y / 2.0 - 0.5; to_map_coords(x, y) } pub fn tile_under_cursor( &self, mut mouse_x: f32, mut mouse_y: f32, width: f32, height: f32, ) -> (usize, usize) { mouse_x -= width / 2.0; mouse_y -= height / 2.0; // Work out the position of the mouse on the screen relative to the camera let x = mouse_x / TILE_WIDTH / self.zoom + self.x / 2.0; let y = mouse_y / TILE_HEIGHT / self.zoom - self.y / 2.0; // Account for the images being square let y = y - 0.5; // Convert to map coordinates let (x, y) = to_map_coords(x, y); // And then to usize (x.round() as usize, y.round() as usize) } } // If a tile is visible, get it's location on the screen fn draw_location(ctx: &Context, camera: &Camera, x: f32, y: f32) -> Option<[f32; 2]> { // Get the maximum x and y values (given that (0, 0) is at the center) let (max_x, max_y) = (ctx.width, ctx.height); // The x and y difference of a tile compared to another tile on the same row/col let (x_size, y_size) = ( TILE_WIDTH / 2.0 * camera.zoom, TILE_HEIGHT / 2.0 * camera.zoom, ); // Convert the location from the map coords to the screen coords let (x, y) = from_map_coords(x, y); // Get the correct position let x = (x - camera.x) * x_size + ctx.width / 2.0; let y = -(y - camera.y) * y_size + ctx.height / 2.0; // Check if the tile is onscreen if x > -x_size && y > -y_size * 2.0 && x < max_x + x_size && y < max_y + y_size * 2.0 { Some([x, y]) } else { None } } // Draw all the elements of a particular map tile fn draw_tile(x: usize, y: usize, ctx: &mut Context, battle: &Battle) { let camera = &battle.camera; let debugging = battle.visual_debugging; let map = &battle.client.map; let responses = battle.client.responses(); let side = battle.client.side; let tiles = &map.tiles; let light = map.light; // Get the tile let visibility = tiles.visibility_at(x, y, side); let overlay = visibility.colour(light, debugging); let tile = tiles.at(x, y); // If the tile is on the screen, draw it if let Some(dest) = draw_location(ctx, camera, x as f32, y as f32) { ctx.render_with_overlay(tile.base, dest, camera.zoom, overlay); // Draw the left wall if let Some(ref wall) = tile.walls.left { let visibility = tiles.left_wall_visibility(x, y, side); ctx.render_with_overlay( wall.tag.left_image(), dest, camera.zoom, visibility.colour(light, debugging), ); } // Draw the right wall if let Some(ref wall) = tile.walls.top { let visibility = tiles.top_wall_visibility(x, y, side); ctx.render_with_overlay( wall.tag.top_image(), dest, camera.zoom, visibility.colour(light, debugging), ); } if let Obstacle::Pit(image) = tile.obstacle { ctx.render_with_overlay(image, dest, camera.zoom, overlay); } // Draw the cursor if it isn't on an ai unit and or a unit isn't selected if !battle.cursor_active() { if let Some((cursor_x, cursor_y)) = battle.cursor { if cursor_x == x && cursor_y == y { // Determine the cursor type // Grey if the tile is not visible let colour = if !visibility.is_visible() { colours::GREY // Red if the tile has an obstacle } else if !tile.obstacle.is_empty() { colours::RED // Orange if it has a unit } else if battle.client.map.units.at(x, y).is_some() { colours::ORANGE // Yellow by default } else { colours::YELLOW }; ctx.render_with_overlay(Image::Cursor, dest, camera.zoom, colour); } } } // Draw the tile decoration if let Some(decoration) = tile.decoration { ctx.render_with_overlay(decoration, dest, camera.zoom, overlay); } // Draw the tile items for item in &tile.items { ctx.render_with_overlay(item.image(), dest, camera.zoom, overlay); } // Draw a unit at the position if let Some(unit) = battle.client.map.units.at(x, y) { // Draw the cursor to show that the unit is selected if battle.selected == Some(unit.id) { ctx.render_with_overlay(Image::Cursor, dest, camera.zoom, colours::ORANGE); } unit.render(ctx, dest, camera.zoom, overlay); } // If the tile has an obstacle on it, draw it if let Obstacle::Object(image) = tile.obstacle { ctx.render_with_overlay(image, dest, camera.zoom, overlay); } // Draw explosions on the tile responses .iter() .filter_map(Response::as_explosion) .filter(|explosion| explosion.x() == x && explosion.y() == y) .for_each(|explosion| ctx.render(explosion.image(), dest, camera.zoom)); } } pub fn draw_map(ctx: &mut Context, battle: &Battle) { let camera = &battle.camera; let debugging = battle.visual_debugging; let map = &battle.client.map; let side = battle.client.side; let width = map.tiles.width(); let height = map.tiles.height(); let light = map.light; // Draw all the tiles for (x, y) in map.tiles.iter() { draw_tile(x, y, ctx, battle); } // Draw the edge edges for x in 0..width { let visibility = map.tiles.visibility_at(x, height - 1, side); if let Some(dest) = draw_location(ctx, camera, (x + 1) as f32, height as f32) { ctx.render_with_overlay( Image::LeftEdge, dest, camera.zoom, visibility.colour(light, debugging), ); } } for y in 0..height { let visibility = map.tiles.visibility_at(width - 1, y, side); if let Some(dest) = draw_location(ctx, camera, width as f32, (y + 1) as f32) { ctx.render_with_overlay( Image::RightEdge, dest, camera.zoom, visibility.colour(light, debugging), ); } } } // Draw the whole battle pub fn draw_battle(ctx: &mut Context, battle: &Battle) { let camera = &battle.camera; let map = &battle.client.map; let responses = &battle.client.responses(); let side = battle.client.side; draw_map(ctx, battle); // Draw the path if there is one if let Some(ref points) = battle.path { if let Some(unit) = battle.selected() { let mut unit_moves = i32::from(unit.moves); // Draw the path tiles for point in points { unit_moves -= i32::from(point.cost); if let Some(dest) = draw_location(ctx, camera, point.x as f32, point.y as f32) { // Render the path tile let colour = if unit_moves < 0 { colours::RED } else if unit_moves < i32::from(unit.weapon.tag.cost()) { colours::ORANGE } else { colours::WHITE }; ctx.render_with_overlay(Image::Path, dest, camera.zoom, colour); } } // Draw the path costs unit_moves = i32::from(unit.moves); for point in points { unit_moves -= i32::from(point.cost); if unit_moves >= 0 { if let Some(dest) = draw_location(ctx, camera, point.x as f32, point.y as f32) { // Render the path cost ctx.render_text(&unit_moves.to_string(), dest[0], dest[1], colours::WHITE); } } } } } // Draw the firing crosshair if the cursor is on an ai unit and a unit is selected if battle.cursor_active() { if let Some(firing) = battle.selected() { if let Some((x, y)) = battle.cursor { if let Some(dest) = draw_location(ctx, camera, x as f32, y as f32) { // Draw the crosshair ctx.render(Image::CursorCrosshair, dest, camera.zoom); let colour = if map.tiles.visibility_at(x, y, side).is_invisible() { colours::GREY } else if !firing.weapon.can_fire() { colours::RED } else if map.tiles.line_of_fire(firing.x, firing.y, x, y).is_some() { colours::ORANGE } else { colours::WHITE }; // Draw the chance-to-hit ctx.render_text( &format!("{:0.3}%", firing.chance_to_hit(x, y) * 100.0), dest[0], dest[1] + TILE_HEIGHT * camera.zoom, colour, ); } } } } // Draw all the visible bullets in the response queue responses .iter() .filter_map(Response::as_bullet) .for_each(|bullet| { // If the bullet is on screen, draw it with the right rotation if let Some(dest) = draw_location(ctx, camera, bullet.x(), bullet.y()) { ctx.render_with_rotation( bullet.image(), dest, camera.zoom, convert_rotation(bullet.direction()), ); } }); responses .iter() .filter_map(Response::as_thrown_item) .for_each(|thrown_item| { if let Some(dest) = draw_location(ctx, camera, thrown_item.x(), thrown_item.y()) { ctx.render( thrown_item.image(), [ dest[0], dest[1] - thrown_item.height() * camera.zoom * TILE_HEIGHT, ], camera.zoom, ); } }); } #[test] fn default_camera_pos() { // If the cursor is in the center of the screen and the camera is // the default, the tile under the cursor should be at (0, 0) assert_eq!( Camera::new().tile_under_cursor(501.0, 501.0, 1000.0, 1000.0), (0, 0) ); }
32.033573
100
0.508759
e9c457aab407f9b25e6827bf336c7c6c49b62e40
6,117
use std::ops::Range; use ucsf_nmr::{Tiles, UcsfFile}; #[test] fn correct_axis_tiles_1() { let contents = include_bytes!("./data/15n_hsqc.ucsf"); let (_, file) = UcsfFile::parse(&contents[..]).expect("Failed parsing"); assert_eq!(file.axis_tiles()[0], 2); assert_eq!(file.axis_tiles()[1], 2); } #[test] fn correct_axis_tiles_padded() { let contents = include_bytes!("./data/Nhsqc_highres_600MHz.ucsf"); let (_, file) = UcsfFile::parse(&contents[..]).expect("Failed parsing"); assert_eq!(file.axis_tiles()[0], 4); assert_eq!(file.axis_tiles()[1], 5); } #[test] fn correct_num_tiles_1() { let contents = include_bytes!("./data/15n_hsqc.ucsf"); let (_, contents) = UcsfFile::parse(&contents[..]).expect("Failed parsing"); let tile_count = contents.tiles().count(); assert_eq!(tile_count, 4); } #[test] fn correct_num_tiles_2() { let contents = include_bytes!("./data/Nhsqc_highres_600MHz.ucsf"); let (_, contents) = UcsfFile::parse(&contents[..]).expect("Failed parsing"); let tile_count = contents.tiles().count(); assert_eq!(tile_count, 20); } #[test] fn correct_padded_tiles() { let contents = include_bytes!("./data/Nhsqc_highres_600MHz.ucsf"); let (_, contents) = UcsfFile::parse(&contents[..]).expect("Failed parsing"); assert_eq!(false, contents.axis_headers[0].tile_is_padded(0)); assert_eq!(false, contents.axis_headers[0].tile_is_padded(1)); assert_eq!(false, contents.axis_headers[0].tile_is_padded(2)); assert_eq!(false, contents.axis_headers[0].tile_is_padded(3)); assert_eq!(false, contents.axis_headers[1].tile_is_padded(0)); assert_eq!(false, contents.axis_headers[1].tile_is_padded(1)); assert_eq!(false, contents.axis_headers[1].tile_is_padded(2)); assert_eq!(false, contents.axis_headers[1].tile_is_padded(3)); assert_eq!(true, contents.axis_headers[1].tile_is_padded(4)); assert_eq!(0, contents.axis_headers[0].tile_padding(0)); assert_eq!(0, contents.axis_headers[0].tile_padding(1)); assert_eq!(0, contents.axis_headers[0].tile_padding(2)); assert_eq!(0, contents.axis_headers[0].tile_padding(3)); assert_eq!(0, contents.axis_headers[1].tile_padding(0)); assert_eq!(0, contents.axis_headers[1].tile_padding(1)); assert_eq!(0, contents.axis_headers[1].tile_padding(2)); assert_eq!(0, contents.axis_headers[1].tile_padding(3)); assert_eq!(63, contents.axis_headers[1].tile_padding(4)); } #[test] fn correct_tiles_absolute_positions() { let contents = include_bytes!("./data/Nhsqc_highres_600MHz.ucsf"); let (_, contents) = UcsfFile::parse(&contents[..]).expect("Failed parsing"); let mut tiles = contents.tiles(); let assert_absolute_pos = |tiles: &mut Tiles, absolute_pos| { assert_eq!( absolute_pos, tiles .next() .unwrap() .iter_with_abolute_pos() .as_2d() .next() .unwrap() .0 ); }; assert_absolute_pos(&mut tiles, (0, 0)); assert_absolute_pos(&mut tiles, (0, 64)); assert_absolute_pos(&mut tiles, (0, 128)); assert_absolute_pos(&mut tiles, (0, 192)); assert_absolute_pos(&mut tiles, (0, 256)); assert_absolute_pos(&mut tiles, (128, 0)); assert_absolute_pos(&mut tiles, (128, 64)); assert_absolute_pos(&mut tiles, (128, 128)); assert_absolute_pos(&mut tiles, (128, 192)); assert_absolute_pos(&mut tiles, (128, 256)); assert_absolute_pos(&mut tiles, (256, 0)); assert_absolute_pos(&mut tiles, (256, 64)); assert_absolute_pos(&mut tiles, (256, 128)); assert_absolute_pos(&mut tiles, (256, 192)); assert_absolute_pos(&mut tiles, (256, 256)); assert_absolute_pos(&mut tiles, (384, 0)); assert_absolute_pos(&mut tiles, (384, 64)); assert_absolute_pos(&mut tiles, (384, 128)); assert_absolute_pos(&mut tiles, (384, 192)); assert_absolute_pos(&mut tiles, (384, 256)); let mut tiles = contents.tiles(); let assert_absolute_pos_range = |tiles: &mut Tiles, range_axis_1: Range<_>, range_axis_2: Range<_>| { let tile = tiles.next().unwrap(); for (pos, _) in tile.iter_with_abolute_pos().as_2d() { assert!(range_axis_1.contains(&pos.0)); assert!(range_axis_2.contains(&pos.1)); } }; assert_absolute_pos_range(&mut tiles, 0..128, 0..64); assert_absolute_pos_range(&mut tiles, 0..128, 64..128); assert_absolute_pos_range(&mut tiles, 0..128, 128..192); assert_absolute_pos_range(&mut tiles, 0..128, 192..256); assert_absolute_pos_range(&mut tiles, 0..128, 256..257); } #[test] fn correct_tiles_padding() { let contents = include_bytes!("./data/Nhsqc_highres_600MHz.ucsf"); let (_, contents) = UcsfFile::parse(&contents[..]).expect("Failed parsing"); let mut tiles = contents.tiles(); let assert_absolute_pos = |tiles: &mut Tiles, padding| { let tile = tiles.next().unwrap(); let tile_padding = (tile.axis_lengths[0], tile.axis_lengths[1]); assert_eq!(padding, tile_padding); }; assert_absolute_pos(&mut tiles, (128, 64)); assert_absolute_pos(&mut tiles, (128, 64)); assert_absolute_pos(&mut tiles, (128, 64)); assert_absolute_pos(&mut tiles, (128, 64)); assert_absolute_pos(&mut tiles, (128, 1)); assert_absolute_pos(&mut tiles, (128, 64)); assert_absolute_pos(&mut tiles, (128, 64)); assert_absolute_pos(&mut tiles, (128, 64)); assert_absolute_pos(&mut tiles, (128, 64)); assert_absolute_pos(&mut tiles, (128, 1)); assert_absolute_pos(&mut tiles, (128, 64)); assert_absolute_pos(&mut tiles, (128, 64)); assert_absolute_pos(&mut tiles, (128, 64)); assert_absolute_pos(&mut tiles, (128, 64)); assert_absolute_pos(&mut tiles, (128, 1)); assert_absolute_pos(&mut tiles, (128, 64)); assert_absolute_pos(&mut tiles, (128, 64)); assert_absolute_pos(&mut tiles, (128, 64)); assert_absolute_pos(&mut tiles, (128, 64)); assert_absolute_pos(&mut tiles, (128, 1)); }
37.759259
80
0.653425
ac47a555ab70b22bdac625882f9c34763b2691c2
524
// vim: tw=80 //! generic structs with bounds on their generic parameters #![deny(warnings)] use mockall::*; #[allow(unused)] struct GenericStruct<T: Copy, V: Clone> { t: T, v: V } #[automock] impl<T: Copy + 'static, V: Clone + 'static> GenericStruct<T, V> { #[allow(unused)] fn foo(&self, _x: u32) -> i64 { 42 } } #[test] fn returning() { let mut mock = MockGenericStruct::<u8, i8>::new(); mock.expect_foo() .returning(|x| i64::from(x) + 1); assert_eq!(5, mock.foo(4)); }
19.407407
65
0.576336
e42865507f2b991795cf1a8e2bfb76e7253ba6a1
6,791
#[test] fn test_env() { for test_case in build_usize_test_cases() { test_case.assert_default(); test_case.assert_env_key(); } for test_case in build_u64_test_cases() { test_case.assert_default(); test_case.assert_env_key(); } } fn build_usize_test_cases() -> Vec<USizeEnvValue> { vec![ USizeEnvValue { expected_default: 60 * 60 * 1000, env_key: String::from("SAFE_INFO_CACHE_DURATION"), generator: Box::new(super::safe_info_cache_duration), }, USizeEnvValue { expected_default: 60 * 60 * 1000, env_key: String::from("ADDRESS_INFO_CACHE_DURATION"), generator: Box::new(super::address_info_cache_duration), }, USizeEnvValue { expected_default: 60 * 60 * 24 * 1000, env_key: String::from("TOKEN_INFO_CACHE_DURATION"), generator: Box::new(super::token_info_cache_duration), }, USizeEnvValue { expected_default: 60 * 60 * 1000, env_key: String::from("CHAIN_INFO_CACHE_DURATION"), generator: Box::new(super::chain_info_cache_duration), }, USizeEnvValue { expected_default: 60 * 60 * 12 * 1000, env_key: String::from("EXCHANGE_API_CACHE_DURATION"), generator: Box::new(super::exchange_api_cache_duration), }, USizeEnvValue { expected_default: 60 * 60 * 1000, env_key: String::from("REQUEST_CACHE_DURATION"), generator: Box::new(super::request_cache_duration), }, USizeEnvValue { expected_default: 60 * 15 * 1000, env_key: String::from("ABOUT_CACHE_DURATION"), generator: Box::new(super::about_cache_duration), }, USizeEnvValue { expected_default: 60 * 1000, env_key: String::from("BALANCES_REQUEST_CACHE_DURATION"), generator: Box::new(super::balances_cache_duration), }, USizeEnvValue { expected_default: 60 * 60 * 1000, env_key: String::from("SAFE_APP_MANIFEST_CACHE_DURATION"), generator: Box::new(super::safe_app_manifest_cache_duration), }, USizeEnvValue { expected_default: 60 * 1000, env_key: String::from("OWNERS_FOR_SAFES_CACHE_DURATION"), generator: Box::new(super::owners_for_safes_cache_duration), }, USizeEnvValue { expected_default: 60 * 60 * 1000, env_key: String::from("BALANCES_CORE_REQUEST_CACHE_DURATION"), generator: Box::new(super::balances_core_request_cache_duration), }, USizeEnvValue { expected_default: 10 * 1000, env_key: String::from("TOKEN_PRICE_CACHE_DURATION"), generator: Box::new(super::token_price_cache_duration), }, USizeEnvValue { expected_default: super::request_cache_duration(), env_key: String::from("TX_QUEUED_CACHE_DURATION"), generator: Box::new(super::tx_queued_cache_duration), }, ] } fn build_u64_test_cases() -> Vec<U64EnvValue> { vec![ U64EnvValue { expected_default: 1000, env_key: String::from("INTERNAL_CLIENT_CONNECT_TIMEOUT"), generator: Box::new(super::internal_client_connect_timeout), }, U64EnvValue { expected_default: 3000, env_key: String::from("SAFE_APP_INFO_REQUEST_TIMEOUT"), generator: Box::new(super::safe_app_info_request_timeout), }, U64EnvValue { expected_default: 30000, env_key: String::from("TRANSACTION_REQUEST_TIMEOUT"), generator: Box::new(super::transaction_request_timeout), }, U64EnvValue { expected_default: 10000, env_key: String::from("SAFE_INFO_REQUEST_TIMEOUT"), generator: Box::new(super::safe_info_request_timeout), }, U64EnvValue { expected_default: 15000, env_key: String::from("TOKEN_INFO_REQUEST_TIMEOUT"), generator: Box::new(super::token_info_request_timeout), }, U64EnvValue { expected_default: 3000, env_key: String::from("CONTRACT_INFO_REQUEST_TIMEOUT"), generator: Box::new(super::contract_info_request_timeout), }, U64EnvValue { expected_default: 20000, env_key: String::from("BALANCES_REQUEST_TIMEOUT"), generator: Box::new(super::balances_request_timeout), }, U64EnvValue { expected_default: 20000, env_key: String::from("COLLECTIBLES_REQUEST_TIMEOUT"), generator: Box::new(super::collectibles_request_timeout), }, U64EnvValue { expected_default: 10000, env_key: String::from("DEFAULT_REQUEST_TIMEOUT"), generator: Box::new(super::default_request_timeout), }, ] } trait TestCase { fn assert_default(&self); fn assert_env_key(&self); } struct USizeEnvValue { expected_default: usize, env_key: String, generator: Box<dyn Fn() -> usize>, } impl TestCase for USizeEnvValue { fn assert_default(&self) { std::env::remove_var(&self.env_key); let actual_default = (&self.generator)(); assert_eq!( self.expected_default, actual_default, "Test default value for env key: {}", &self.env_key ); } fn assert_env_key(&self) { let mock_env_var_value = 1; std::env::set_var(&self.env_key, &mock_env_var_value.to_string()); let actual_env = (&self.generator)(); std::env::remove_var(&self.env_key); assert_eq!( mock_env_var_value, actual_env, "Test env var for env key: {}", &self.env_key ); } } struct U64EnvValue { expected_default: u64, env_key: String, generator: Box<dyn Fn() -> u64>, } impl TestCase for U64EnvValue { fn assert_default(&self) { std::env::remove_var(&self.env_key); let actual_default = (&self.generator)(); assert_eq!( self.expected_default, actual_default, "Test default value for env key: {}", &self.env_key ); } fn assert_env_key(&self) { let mock_env_var_value = 1; std::env::set_var(&self.env_key, &mock_env_var_value.to_string()); let actual_env = (&self.generator)(); std::env::remove_var(&self.env_key); assert_eq!( mock_env_var_value, actual_env, "Test env var for env key: {}", &self.env_key ); } }
34.29798
77
0.59196
6938b3d9059f9530cf55a499fb5c0e7cc1ea8b51
19,323
// Copyright 2020 ZomboDB, LLC <zombodb@gmail.com>. All rights reserved. Use of this source code is // governed by the MIT license that can be found in the LICENSE file. // // we allow improper_ctypes just to eliminate these warnings: // = note: `#[warn(improper_ctypes)]` on by default // = note: 128-bit integers don't currently have a known stable ABI #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(dead_code)] #![allow(non_upper_case_globals)] #![allow(improper_ctypes)] #![allow(clippy::unneeded_field_pattern)] #[cfg( any( // no features at all will cause problems not(any(feature = "pg10", feature = "pg11", feature = "pg12", feature = "pg13")), ))] std::compile_error!("exactly one one feature must be provided (pg10, pg11, or pg12)"); pub mod submodules; pub use submodules::guard; pub use submodules::*; // // our actual bindings modules -- these are generated by build.rs // // feature gate each pg version module #[cfg(feature = "pg10")] mod pg10; #[cfg(feature = "pg11")] mod pg11; #[cfg(feature = "pg12")] mod pg12; #[cfg(feature = "pg13")] mod pg13; // export each module publicly #[cfg(feature = "pg10")] pub use pg10::*; #[cfg(feature = "pg11")] pub use pg11::*; #[cfg(feature = "pg12")] pub use pg12::*; #[cfg(feature = "pg13")] pub use pg13::*; // feature gate each pg-specific oid module #[cfg(feature = "pg10")] mod pg10_oids; #[cfg(feature = "pg11")] mod pg11_oids; #[cfg(feature = "pg12")] mod pg12_oids; #[cfg(feature = "pg13")] mod pg13_oids; // export that module publicly #[cfg(feature = "pg10")] pub use pg10_oids::*; #[cfg(feature = "pg11")] pub use pg11_oids::*; #[cfg(feature = "pg12")] pub use pg12_oids::*; #[cfg(feature = "pg13")] pub use pg13_oids::*; // expose things we want available for all versions pub use all_versions::*; // and things that are version-specific #[cfg(feature = "pg10")] pub use internal::pg10::add_bool_reloption; #[cfg(feature = "pg10")] pub use internal::pg10::add_int_reloption; #[cfg(feature = "pg10")] pub use internal::pg10::add_string_reloption; #[cfg(feature = "pg10")] pub use internal::pg10::IndexBuildHeapScan; #[cfg(feature = "pg10")] pub use internal::pg10::*; #[cfg(feature = "pg11")] pub use internal::pg11::IndexBuildHeapScan; #[cfg(feature = "pg11")] pub use internal::pg11::*; #[cfg(feature = "pg12")] pub use internal::pg12::*; #[cfg(feature = "pg13")] pub use internal::pg13::*; /// A trait applied to all of Postgres' `pg_sys::Node` types and its subtypes pub trait PgNode { type NodeType; /// Represent this node as a mutable pointer of its type #[inline] fn as_node_ptr(&self) -> *mut Self::NodeType { self as *const _ as *mut Self::NodeType } } /// implementation function for `impl Display for $NodeType` pub(crate) fn node_to_string_for_display(node: *mut crate::Node) -> String { unsafe { // crate::nodeToString() will never return a null pointer let node_to_string = crate::nodeToString(node as *mut std::ffi::c_void); let result = match std::ffi::CStr::from_ptr(node_to_string).to_str() { Ok(cstr) => cstr.to_string(), Err(e) => format!("<ffi error: {:?}>", e), }; crate::pfree(node_to_string as *mut std::ffi::c_void); result } } /// A trait for converting a thing into a `char *` that is allocated by Postgres' palloc pub trait AsPgCStr { fn as_pg_cstr(&self) -> *mut std::os::raw::c_char; } impl<'a> AsPgCStr for &'a str { fn as_pg_cstr(&self) -> *mut std::os::raw::c_char { let self_bytes = self.as_bytes(); let pg_cstr = unsafe { crate::palloc0(self_bytes.len() + 1) as *mut std::os::raw::c_uchar }; let slice = unsafe { std::slice::from_raw_parts_mut(pg_cstr, self_bytes.len()) }; slice.copy_from_slice(self_bytes); pg_cstr as *mut std::os::raw::c_char } } impl AsPgCStr for String { fn as_pg_cstr(&self) -> *mut std::os::raw::c_char { self.as_str().as_pg_cstr() } } /// item declarations we want to add to all versions mod all_versions { use crate as pg_sys; use pgx_macros::*; use memoffset::*; use std::str::FromStr; /// this comes from `postgres_ext.h` pub const InvalidOid: super::Oid = 0; pub const InvalidOffsetNumber: super::OffsetNumber = 0; pub const FirstOffsetNumber: super::OffsetNumber = 1; pub const MaxOffsetNumber: super::OffsetNumber = (super::BLCKSZ as usize / std::mem::size_of::<super::ItemIdData>()) as super::OffsetNumber; pub const InvalidBlockNumber: u32 = 0xFFFF_FFFF as crate::BlockNumber; pub const VARHDRSZ: usize = std::mem::size_of::<super::int32>(); pub const InvalidTransactionId: super::TransactionId = 0 as super::TransactionId; pub const InvalidCommandId: super::CommandId = (!(0 as super::CommandId)) as super::CommandId; pub const FirstCommandId: super::CommandId = 0 as super::CommandId; pub const BootstrapTransactionId: super::TransactionId = 1 as super::TransactionId; pub const FrozenTransactionId: super::TransactionId = 2 as super::TransactionId; pub const FirstNormalTransactionId: super::TransactionId = 3 as super::TransactionId; pub const MaxTransactionId: super::TransactionId = 0xFFFF_FFFF as super::TransactionId; #[pgx_macros::pg_guard] extern "C" { pub fn pgx_list_nth(list: *mut super::List, nth: i32) -> *mut std::os::raw::c_void; pub fn pgx_list_nth_int(list: *mut super::List, nth: i32) -> i32; pub fn pgx_list_nth_oid(list: *mut super::List, nth: i32) -> super::Oid; pub fn pgx_list_nth_cell(list: *mut super::List, nth: i32) -> *mut super::ListCell; pub fn pgx_GETSTRUCT(tuple: pg_sys::HeapTuple) -> *mut std::os::raw::c_char; } #[inline] pub fn VARHDRSZ_EXTERNAL() -> usize { offset_of!(super::varattrib_1b_e, va_data) } #[inline] pub fn VARHDRSZ_SHORT() -> usize { offset_of!(super::varattrib_1b, va_data) } #[inline] pub fn get_pg_major_version_string() -> &'static str { let mver = std::ffi::CStr::from_bytes_with_nul(super::PG_MAJORVERSION).unwrap(); mver.to_str().unwrap() } #[inline] pub fn get_pg_major_version_num() -> u16 { u16::from_str(super::get_pg_major_version_string()).unwrap() } #[inline] pub fn get_pg_version_string() -> &'static str { let ver = std::ffi::CStr::from_bytes_with_nul(super::PG_VERSION_STR).unwrap(); ver.to_str().unwrap() } #[inline] pub fn get_pg_major_minor_version_string() -> &'static str { let mver = std::ffi::CStr::from_bytes_with_nul(super::PG_VERSION).unwrap(); mver.to_str().unwrap() } #[inline] pub fn TransactionIdIsNormal(xid: super::TransactionId) -> bool { xid >= FirstNormalTransactionId } /// ```c /// #define type_is_array(typid) (get_element_type(typid) != InvalidOid) /// ``` #[inline] pub unsafe fn type_is_array(typoid: super::Oid) -> bool { super::get_element_type(typoid) != InvalidOid } #[inline] pub unsafe fn planner_rt_fetch( index: super::Index, root: *mut super::PlannerInfo, ) -> *mut super::RangeTblEntry { extern "C" { pub fn pgx_planner_rt_fetch( index: super::Index, root: *mut super::PlannerInfo, ) -> *mut super::RangeTblEntry; } pgx_planner_rt_fetch(index, root) } /// ```c /// #define rt_fetch(rangetable_index, rangetable) \ /// ((RangeTblEntry *) list_nth(rangetable, (rangetable_index)-1)) /// ``` #[inline] pub unsafe fn rt_fetch( index: super::Index, range_table: *mut super::List, ) -> *mut super::RangeTblEntry { pgx_list_nth(range_table, index as i32 - 1) as *mut super::RangeTblEntry } #[inline] pub fn HeapTupleHeaderGetXmin( htup_header: super::HeapTupleHeader, ) -> Option<super::TransactionId> { extern "C" { pub fn pgx_HeapTupleHeaderGetXmin( htup_header: super::HeapTupleHeader, ) -> super::TransactionId; } if htup_header.is_null() { None } else { Some(unsafe { pgx_HeapTupleHeaderGetXmin(htup_header) }) } } #[inline] pub fn HeapTupleHeaderGetRawCommandId( htup_header: super::HeapTupleHeader, ) -> Option<super::CommandId> { extern "C" { pub fn pgx_HeapTupleHeaderGetRawCommandId( htup_header: super::HeapTupleHeader, ) -> super::CommandId; } if htup_header.is_null() { None } else { Some(unsafe { pgx_HeapTupleHeaderGetRawCommandId(htup_header) }) } } /// #define HeapTupleHeaderIsHeapOnly(tup) \ /// ( \ /// ((tup)->t_infomask2 & HEAP_ONLY_TUPLE) != 0 \ /// ) #[inline] pub unsafe fn HeapTupleHeaderIsHeapOnly(htup_header: super::HeapTupleHeader) -> bool { ((*htup_header).t_infomask2 & crate::HEAP_ONLY_TUPLE as u16) != 0 } /// #define HeapTupleHeaderIsHotUpdated(tup) \ /// ( \ /// ((tup)->t_infomask2 & HEAP_HOT_UPDATED) != 0 && \ /// ((tup)->t_infomask & HEAP_XMAX_INVALID) == 0 && \ /// !HeapTupleHeaderXminInvalid(tup) \ /// ) #[inline] pub unsafe fn HeapTupleHeaderIsHotUpdated(htup_header: super::HeapTupleHeader) -> bool { (*htup_header).t_infomask2 & crate::HEAP_HOT_UPDATED as u16 != 0 && (*htup_header).t_infomask & crate::HEAP_XMAX_INVALID as u16 == 0 && !HeapTupleHeaderXminInvalid(htup_header) } /// #define HeapTupleHeaderXminInvalid(tup) \ /// ( \ /// ((tup)->t_infomask & (HEAP_XMIN_COMMITTED|HEAP_XMIN_INVALID)) == \ /// HEAP_XMIN_INVALID \ /// ) #[inline] pub unsafe fn HeapTupleHeaderXminInvalid(htup_header: super::HeapTupleHeader) -> bool { (*htup_header).t_infomask & (crate::HEAP_XMIN_COMMITTED as u16 | crate::HEAP_XMIN_INVALID as u16) == crate::HEAP_XMIN_INVALID as u16 } /// #define BufferGetPage(buffer) ((Page)BufferGetBlock(buffer)) #[inline] pub unsafe fn BufferGetPage(buffer: crate::Buffer) -> crate::Page { BufferGetBlock(buffer) as crate::Page } /// #define BufferGetBlock(buffer) \ /// ( \ /// AssertMacro(BufferIsValid(buffer)), \ /// BufferIsLocal(buffer) ? \ /// LocalBufferBlockPointers[-(buffer) - 1] \ /// : \ /// (Block) (BufferBlocks + ((Size) ((buffer) - 1)) * BLCKSZ) \ /// ) #[inline] pub unsafe fn BufferGetBlock(buffer: crate::Buffer) -> crate::Block { if BufferIsLocal(buffer) { *crate::LocalBufferBlockPointers.offset(((-buffer) - 1) as isize) } else { crate::BufferBlocks .offset((((buffer as crate::Size) - 1) * crate::BLCKSZ as usize) as isize) as crate::Block } } /// #define BufferIsLocal(buffer) ((buffer) < 0) #[inline] pub unsafe fn BufferIsLocal(buffer: crate::Buffer) -> bool { buffer < 0 } #[inline] pub fn heap_tuple_get_struct<T>(htup: super::HeapTuple) -> *mut T { if htup.is_null() { 0 as *mut T } else { unsafe { pgx_GETSTRUCT(htup) as *mut T } } } #[pg_guard] extern "C" { pub fn query_tree_walker( query: *mut super::Query, walker: ::std::option::Option< unsafe extern "C" fn(*mut super::Node, *mut ::std::os::raw::c_void) -> bool, >, context: *mut ::std::os::raw::c_void, flags: ::std::os::raw::c_int, ) -> bool; } #[pg_guard] extern "C" { pub fn expression_tree_walker( node: *mut super::Node, walker: ::std::option::Option< unsafe extern "C" fn(*mut super::Node, *mut ::std::os::raw::c_void) -> bool, >, context: *mut ::std::os::raw::c_void, ) -> bool; } } mod internal { // // for specific versions // #[cfg(feature = "pg10")] pub(crate) mod pg10 { use crate::pg10::*; pub use crate::pg10::tupleDesc as TupleDescData; pub use crate::pg10::AllocSetContextCreate as AllocSetContextCreateExtended; pub type QueryCompletion = std::os::raw::c_char; pub unsafe fn add_string_reloption( kinds: bits32, name: *const ::std::os::raw::c_char, desc: *const ::std::os::raw::c_char, default_val: *const ::std::os::raw::c_char, validator: ::std::option::Option< unsafe extern "C" fn(value: *const ::std::os::raw::c_char), >, ) { // PG10 defines the validator function as taking a "*mut c_char" // whereas PG11/12 want a "*const c_char". // // For ease of use by users of this crate, we cast the provided // 'validator' function to what PG10 wants, using transmute // // If there's a better way to do this, I'ld love to know! let func_as_mut_arg = match validator { Some(func) => { let func_ptr = std::mem::transmute::< unsafe extern "C" fn(*const ::std::os::raw::c_char), unsafe extern "C" fn(*mut ::std::os::raw::c_char), >(func); Some(func_ptr) } None => None, }; crate::pg10::add_string_reloption( kinds, name as *mut std::os::raw::c_char, desc as *mut std::os::raw::c_char, default_val as *mut std::os::raw::c_char, func_as_mut_arg, ); } pub unsafe fn add_int_reloption( kinds: bits32, name: *const ::std::os::raw::c_char, desc: *const ::std::os::raw::c_char, default_val: ::std::os::raw::c_int, min_val: ::std::os::raw::c_int, max_val: ::std::os::raw::c_int, ) { crate::pg10::add_int_reloption( kinds, name as *mut std::os::raw::c_char, desc as *mut std::os::raw::c_char, default_val, min_val, max_val, ); } pub unsafe fn add_bool_reloption( kinds: bits32, name: *const ::std::os::raw::c_char, desc: *const ::std::os::raw::c_char, default_val: bool, ) { crate::pg10::add_bool_reloption( kinds, name as *mut std::os::raw::c_char, desc as *mut std::os::raw::c_char, default_val, ); } /// # Safety /// /// This function wraps Postgres' internal `IndexBuildHeapScan` method, and therefore, is /// inherently unsafe pub unsafe fn IndexBuildHeapScan<T>( heap_relation: crate::Relation, index_relation: crate::Relation, index_info: *mut crate::pg10::IndexInfo, build_callback: crate::IndexBuildCallback, build_callback_state: *mut T, ) { crate::pg10::IndexBuildHeapScan( heap_relation, index_relation, index_info, true, build_callback, build_callback_state as *mut std::os::raw::c_void, ); } } #[cfg(feature = "pg11")] pub(crate) mod pg11 { pub use crate::pg11::tupleDesc as TupleDescData; pub type QueryCompletion = std::os::raw::c_char; /// # Safety /// /// This function wraps Postgres' internal `IndexBuildHeapScan` method, and therefore, is /// inherently unsafe pub unsafe fn IndexBuildHeapScan<T>( heap_relation: crate::Relation, index_relation: crate::Relation, index_info: *mut crate::pg11::IndexInfo, build_callback: crate::IndexBuildCallback, build_callback_state: *mut T, ) { crate::pg11::IndexBuildHeapScan( heap_relation, index_relation, index_info, true, build_callback, build_callback_state as *mut std::os::raw::c_void, std::ptr::null_mut(), ); } } #[cfg(feature = "pg12")] pub(crate) mod pg12 { pub use crate::pg12::AllocSetContextCreateInternal as AllocSetContextCreateExtended; pub type QueryCompletion = std::os::raw::c_char; pub const QTW_EXAMINE_RTES: u32 = crate::pg12::QTW_EXAMINE_RTES_BEFORE; /// # Safety /// /// This function wraps Postgres' internal `IndexBuildHeapScan` method, and therefore, is /// inherently unsafe pub unsafe fn IndexBuildHeapScan<T>( heap_relation: crate::Relation, index_relation: crate::Relation, index_info: *mut crate::pg12::IndexInfo, build_callback: crate::IndexBuildCallback, build_callback_state: *mut T, ) { let heap_relation_ref = heap_relation.as_ref().unwrap(); let table_am = heap_relation_ref.rd_tableam.as_ref().unwrap(); table_am.index_build_range_scan.unwrap()( heap_relation, index_relation, index_info, true, false, true, 0, crate::InvalidBlockNumber, build_callback, build_callback_state as *mut std::os::raw::c_void, std::ptr::null_mut(), ); } } #[cfg(feature = "pg13")] pub(crate) mod pg13 { pub use crate::pg13::AllocSetContextCreateInternal as AllocSetContextCreateExtended; pub const QTW_EXAMINE_RTES: u32 = crate::pg13::QTW_EXAMINE_RTES_BEFORE; /// # Safety /// /// This function wraps Postgres' internal `IndexBuildHeapScan` method, and therefore, is /// inherently unsafe pub unsafe fn IndexBuildHeapScan<T>( heap_relation: crate::Relation, index_relation: crate::Relation, index_info: *mut crate::IndexInfo, build_callback: crate::IndexBuildCallback, build_callback_state: *mut T, ) { let heap_relation_ref = heap_relation.as_ref().unwrap(); let table_am = heap_relation_ref.rd_tableam.as_ref().unwrap(); table_am.index_build_range_scan.unwrap()( heap_relation, index_relation, index_info, true, false, true, 0, crate::InvalidBlockNumber, build_callback, build_callback_state as *mut std::os::raw::c_void, std::ptr::null_mut(), ); } } }
32.918228
100
0.574134
4873a4538c4c5a50dfba2c2f470f31dde2325b72
5,461
#[macro_use] extern crate lazy_static; extern crate pest; #[macro_use] extern crate pest_derive; use yew::ComponentLink; use yew::prelude::*; use yew::ShouldRender; mod convert_chart; mod parser; mod test; enum Msg { AddText(String), } struct Model { // `ComponentLink` is like a reference to a component. // It can be used to send messages to the component link: ComponentLink<Self>, text: String, total: f64, } fn transform(c: f64) -> String { use float_pretty_print::PrettyPrintFloat; if c.is_nan() { return "-".to_string(); } if c.fract() == 0.0 { return c.to_string().trim().to_string(); } return PrettyPrintFloat(c).to_string().trim().to_string(); } impl Component for Model { type Message = Msg; type Properties = (); fn create(_props: Self::Properties, link: ComponentLink<Self>) -> Self { Self { link, text: String::from(""), total: 0.0, } } fn update(&mut self, msg: Self::Message) -> ShouldRender { match msg { Msg::AddText(input) => { let mut output = "".to_string(); let mut total = 0.0; let split = input.split('\n'); // for s in split { // let p = parser::parse(s); // if p.is_normal() { // total = total + p; // } // output = format!("{}{}", output, transform(p) + "\n"); // } // self.total = total; // self.text = output; self.total = parser::solve_rb(); self.text = parser::solve_rb().to_string(); true } } } fn change(&mut self, _props: Self::Properties) -> ShouldRender { // Should only return "true" if new properties are different to // previously received properties. // This component has no properties so we will always return "false". false } // fn view(&self) -> Html { // let title = "e".to_string(); // html! { // <p>{ "Hello world!" }</p> // } // } fn view(&self) -> Html { let title = "qubit2".to_string(); return html! { <div class="min-h-screen px-3 bg-gray-100 md:px-0"> <div class="flex flex-col items-center justify-center w-full h-full space-y-8"> <div class="flex items-center justify-between w-full max-w-lg px-4 py-4 -mx-4 border-b border-gray-200 sm:mx-0 sm:px-0"> <h1 class="text-2xl font-extrabold tracking-tight text-gray-900">{ title }</h1> <div class="flex items-center ml-6 space-x-6 sm:space-x-10 sm:ml-10"> <a href="https://github.com/abhimanyu003/qubit" target="_blank" class="text-gray-600 transition-colors duration-200 hover:text-gray-900"> { "Documentation" } </a> <a href="https://github.com/abhimanyu003/qubit" target="_blank" class="text-gray-600 transition-colors duration-200 hover:text-gray-900"> <span class="hidden sm:inline"></span> <svg width="24" height="24" viewBox="0 0 16 16" fill="currentColor"><path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"></path></svg> </a> </div> </div> <div class="w-full max-w-lg subpixel-antialiased tracking-tight text-gray-500 bg-gray-900 rounded-md shadow-2xl text-md"> <div class="grid h-full grid-cols-4 p-4"> <div class="col-span-3"> <textarea oninput=self.link.callback(|e: InputData| Msg::AddText(e.value)) class="w-full h-full text-gray-200 placeholder-gray-500 placeholder-opacity-50 bg-transparent border-0 appearance-none resize-none focus:outline-none focus:ring-0 focus:border-0 active:border-0" style="resize: none" data-gramm="false" placeholder="2 + 2 + sin ( 90 )\n12 kg to g"></textarea> </div> <div class="col-span-1 overflow-x-auto text-right text-green-300 border-l border-opacity-10"> <div> { for self.text.split('\n').into_iter().map(|v| { html!{ <div class="w-full ">{ v }</div> } }) } </div> <div class="pt-5 text-sm text-gray-600">{ "Total: " }{ self.total }</div> </div> </div> </div> </div> </div> }; } } fn main() { yew::start_app::<Model>(); }
40.753731
704
0.504486
6196b8cabf875ae21023b897058117a115bbdd4e
1,840
//! Everything related to web token handling use actix_web::{HttpResponse, ResponseError}; use jsonwebtoken::{decode, encode, Header, Validation}; use time::get_time; use uuid::Uuid; mod test; const SECRET: &[u8] = b"my_secret"; #[derive(Debug, Fail)] /// Token handling related errors pub enum TokenError { #[fail(display = "unable to create session token")] /// Session token creation failed Create, #[fail(display = "unable to verify session token")] /// Session token verification failed Verify, } impl ResponseError for TokenError { fn error_response(&self) -> HttpResponse { match self { TokenError::Create => HttpResponse::InternalServerError().into(), TokenError::Verify => HttpResponse::Unauthorized().into(), } } } #[derive(Deserialize, Serialize)] /// A web token pub struct Token { /// The subject of the token sub: String, /// The exipration date of the token exp: i64, /// The issued at field iat: i64, /// The token id jti: String, } impl Token { /// Create a new default token for a given username pub fn create(username: &str) -> Result<String, TokenError> { const DEFAULT_TOKEN_VALIDITY: i64 = 3600; let claim = Token { sub: username.to_owned(), exp: get_time().sec + DEFAULT_TOKEN_VALIDITY, iat: get_time().sec, jti: Uuid::new_v4().to_string(), }; encode(&Header::default(), &claim, SECRET).map_err(|_| TokenError::Create) } /// Verify the validity of a token and get a new one pub fn verify(token: &str) -> Result<String, TokenError> { let data = decode::<Token>(token, SECRET, &Validation::default()) .map_err(|_| TokenError::Verify)?; Self::create(&data.claims.sub) } }
26.666667
82
0.622283
0143a4ababd2547bafce61d57c4ae57c606711ff
1,555
/** * [303] Range Sum Query - Immutable * * Given an integer array nums, find the sum of the elements between indices i and j (i &le; j), inclusive. * * Example:<br> * * Given nums = [-2, 0, 3, -5, 2, -1] * * sumRange(0, 2) -> 1 * sumRange(2, 5) -> -1 * sumRange(0, 5) -> -3 * * * * Note:<br> * <ol> * You may assume that the array does not change. * There are many calls to sumRange function. * </ol> * */ pub struct Solution {} // submission codes start here struct NumArray { nums: Vec<i32>, } /** * `&self` means the method takes an immutable reference. * If you need a mutable reference, change it to `&mut self` instead. */ impl NumArray { fn new(nums: Vec<i32>) -> Self { let mut res = 0; let mut vec = Vec::with_capacity(nums.len()); for &num in nums.iter() { res += num; vec.push(res); } NumArray { nums: vec } } fn sum_range(&self, i: i32, j: i32) -> i32 { let (i, j) = (i as usize, j as usize); self.nums[j] - if i > 0 { self.nums[i - 1] } else { 0 } } } /** * Your NumArray object will be instantiated and called as such: * let obj = NumArray::new(nums); * let ret_1: i32 = obj.sum_range(i, j); */ // submission codes end #[cfg(test)] mod tests { use super::*; #[test] fn test_303() { let mut nums = NumArray::new(vec![-2, 0, 3, -5, 2, -1]); assert_eq!(nums.sum_range(0, 2), 1); assert_eq!(nums.sum_range(2, 5), -1); assert_eq!(nums.sum_range(0, 5), -3); } }
21.597222
107
0.54791
088fce9de82ac87977e768a0534d2dd808254370
5,233
use criterion::{criterion_group, criterion_main, Criterion}; use serde::de::DeserializeSeed; use serde_json::Deserializer; use twilight_model::{ channel::Reaction, gateway::{ event::GatewayEventDeserializer, payload::incoming::{MemberChunk, TypingStart}, }, }; fn gateway_event_role_delete() { let input = r##"{ "op": 0, "s": 2, "d": { "guild_id": "1", "role_id": "2" }, "t": "GUILD_ROLE_DELETE" }"##; let mut json_deserializer = Deserializer::from_str(input); let gateway_deserializer = GatewayEventDeserializer::from_json(input).unwrap(); gateway_deserializer .deserialize(&mut json_deserializer) .unwrap(); } fn member_chunk() { let input = r#"{ "chunk_count": 1, "chunk_index": 0, "guild_id": "1", "members": [{ "deaf": false, "hoisted_role": "6", "joined_at": "2020-04-04T04:04:04.000000+00:00", "mute": false, "nick": "chunk", "roles": ["6"], "user": { "avatar": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "discriminator": "0001", "id": "5", "public_flags": 131072, "username": "test" } }, { "deaf": false, "hoisted_role": "6", "joined_at": "2020-04-04T04:04:04.000000+00:00", "mute": false, "nick": "chunk", "roles": ["6"], "user": { "avatar": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "discriminator": "0001", "id": "6", "username": "test" } }, { "deaf": false, "hoisted_role": "6", "joined_at": "2020-04-04T04:04:04.000000+00:00", "mute": false, "nick": "chunk", "roles": ["6"], "user": { "avatar": "cccccccccccccccccccccccccccccccc", "bot": true, "discriminator": "0001", "id": "3", "username": "test" } }, { "deaf": false, "hoisted_role": "6", "joined_at": "2020-04-04T04:04:04.000000+00:00", "mute": false, "nick": "chunk", "roles": [ "6", "7" ], "user": { "avatar": "dddddddddddddddddddddddddddddddd", "bot": true, "discriminator": "0001", "id": "2", "username": "test" } }], "presences": [{ "activities": [], "client_status": { "web": "online" }, "status": "online", "user": { "id": "2" } }, { "activities": [], "client_status": { "web": "online" }, "status": "online", "user": { "id": "3" } }, { "activities": [], "client_status": { "desktop": "dnd" }, "status": "dnd", "user": { "id": "5" } }] }"#; serde_json::from_str::<MemberChunk>(input).unwrap(); } fn reaction() { let input = r#"{ "channel_id": "2", "emoji": { "id": null, "name": "🙂" }, "guild_id": "1", "member": { "deaf": false, "hoisted_role": "5", "joined_at": "2020-01-01T00:00:00.000000+00:00", "mute": false, "nick": "typing", "roles": ["5"], "user": { "username": "test", "id": "4", "discriminator": "0001", "avatar": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" } }, "message_id": "3", "user_id": "4" }"#; serde_json::from_str::<Reaction>(input).unwrap(); } fn typing_start() { let input = r#"{ "channel_id": "2", "guild_id": "1", "member": { "deaf": false, "hoisted_role": "4", "joined_at": "2020-01-01T00:00:00.000000+00:00", "mute": false, "nick": "typing", "roles": ["4"], "user": { "username": "test", "id": "3", "discriminator": "0001", "avatar": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" } }, "timestamp": 1500000000, "user_id": "3" }"#; serde_json::from_str::<TypingStart>(input).unwrap(); } fn criterion_benchmark(c: &mut Criterion) { c.bench_function("gateway event role delete", |b| { b.iter(gateway_event_role_delete) }); c.bench_function("member chunk", |b| b.iter(member_chunk)); c.bench_function("reaction", |b| b.iter(reaction)); c.bench_function("typing start", |b| b.iter(typing_start)); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches);
27.11399
83
0.419836
db851fb73b550fb240af7e8c5b189717f16c4365
177
#![cfg_attr(not(feature = "std"), no_std)] pub mod fbridge; use rstd::prelude::*; #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } }
16.090909
42
0.536723
28a41438ebba5936bd9b1049ba5dc513bbb5878a
76,562
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use codespan::{ByteIndex, Span}; use move_ir_types::location::*; use std::str::FromStr; use crate::{ errors::*, parser::{ast::*, lexer::*}, shared::*, }; use std::collections::BTreeMap; // In the informal grammar comments in this file, Comma<T> is shorthand for: // (<T> ",")* <T>? // Note that this allows an optional trailing comma. //************************************************************************************************** // Error Handling //************************************************************************************************** fn unexpected_token_error<'input>(tokens: &Lexer<'input>, expected: &str) -> Error { let loc = current_token_loc(tokens); let unexpected = if tokens.peek() == Tok::EOF { "end-of-file".to_string() } else { format!("'{}'", tokens.content()) }; vec![ (loc, format!("Unexpected {}", unexpected)), (loc, format!("Expected {}", expected)), ] } //************************************************************************************************** // Miscellaneous Utilities //************************************************************************************************** pub fn make_loc(file: &'static str, start: usize, end: usize) -> Loc { Loc::new( file, Span::new(ByteIndex(start as u32), ByteIndex(end as u32)), ) } fn current_token_loc<'input>(tokens: &Lexer<'input>) -> Loc { let start_loc = tokens.start_loc(); make_loc( tokens.file_name(), start_loc, start_loc + tokens.content().len(), ) } fn spanned<T>(file: &'static str, start: usize, end: usize, value: T) -> Spanned<T> { Spanned { loc: make_loc(file, start, end), value, } } // Check for the specified token and consume it if it matches. // Returns true if the token matches. fn match_token<'input>(tokens: &mut Lexer<'input>, tok: Tok) -> Result<bool, Error> { if tokens.peek() == tok { tokens.advance()?; Ok(true) } else { Ok(false) } } // Check for the specified token and return an error if it does not match. fn consume_token<'input>(tokens: &mut Lexer<'input>, tok: Tok) -> Result<(), Error> { if tokens.peek() != tok { let expected = format!("'{}'", &tok.to_string()); return Err(unexpected_token_error(tokens, &expected)); } tokens.advance()?; Ok(()) } // Check for the identifier token with specified value and return an error if it does not match. fn consume_identifier<'input>(tokens: &mut Lexer<'input>, value: &str) -> Result<(), Error> { if tokens.peek() == Tok::IdentifierValue && tokens.content() == value { tokens.advance() } else { let expected = format!("'{}'", value); Err(unexpected_token_error(tokens, &expected)) } } // If the next token is the specified kind, consume it and return // its source location. fn consume_optional_token_with_loc<'input>( tokens: &mut Lexer<'input>, tok: Tok, ) -> Result<Option<Loc>, Error> { if tokens.peek() == tok { let start_loc = tokens.start_loc(); tokens.advance()?; let end_loc = tokens.previous_end_loc(); Ok(Some(make_loc(tokens.file_name(), start_loc, end_loc))) } else { Ok(None) } } // While parsing a list and expecting a ">" token to mark the end, replace // a ">>" token with the expected ">". This handles the situation where there // are nested type parameters that result in two adjacent ">" tokens, e.g., // "A<B<C>>". fn adjust_token<'input>(tokens: &mut Lexer<'input>, end_token: Tok) { if tokens.peek() == Tok::GreaterGreater && end_token == Tok::Greater { tokens.replace_token(Tok::Greater, 1); } } // Parse a comma-separated list of items, including the specified starting and // ending tokens. fn parse_comma_list<'input, F, R>( tokens: &mut Lexer<'input>, start_token: Tok, end_token: Tok, parse_list_item: F, item_description: &str, ) -> Result<Vec<R>, Error> where F: Fn(&mut Lexer<'input>) -> Result<R, Error>, { let start_loc = tokens.start_loc(); consume_token(tokens, start_token)?; parse_comma_list_after_start( tokens, start_loc, start_token, end_token, parse_list_item, item_description, ) } // Parse a comma-separated list of items, including the specified ending token, but // assuming that the starting token has already been consumed. fn parse_comma_list_after_start<'input, F, R>( tokens: &mut Lexer<'input>, start_loc: usize, start_token: Tok, end_token: Tok, parse_list_item: F, item_description: &str, ) -> Result<Vec<R>, Error> where F: Fn(&mut Lexer<'input>) -> Result<R, Error>, { adjust_token(tokens, end_token); if match_token(tokens, end_token)? { return Ok(vec![]); } let mut v = vec![]; loop { if tokens.peek() == Tok::Comma { let current_loc = tokens.start_loc(); let loc = make_loc(tokens.file_name(), current_loc, current_loc); return Err(vec![(loc, format!("Expected {}", item_description))]); } v.push(parse_list_item(tokens)?); adjust_token(tokens, end_token); if match_token(tokens, end_token)? { break Ok(v); } if !match_token(tokens, Tok::Comma)? { let current_loc = tokens.start_loc(); let loc = make_loc(tokens.file_name(), current_loc, current_loc); let loc2 = make_loc(tokens.file_name(), start_loc, start_loc); return Err(vec![ (loc, format!("Expected '{}'", end_token)), (loc2, format!("To match this '{}'", start_token)), ]); } adjust_token(tokens, end_token); if match_token(tokens, end_token)? { break Ok(v); } } } // Parse a list of items, without specified start and end tokens, and the separator determined by // the passed function `parse_list_continue`. fn parse_list<'input, C, F, R>( tokens: &mut Lexer<'input>, mut parse_list_continue: C, parse_list_item: F, ) -> Result<Vec<R>, Error> where C: FnMut(&mut Lexer<'input>) -> Result<bool, Error>, F: Fn(&mut Lexer<'input>) -> Result<R, Error>, { let mut v = vec![]; loop { v.push(parse_list_item(tokens)?); if !parse_list_continue(tokens)? { break Ok(v); } } } //************************************************************************************************** // Identifiers, Addresses, and Names //************************************************************************************************** // Parse an identifier: // Identifier = <IdentifierValue> fn parse_identifier<'input>(tokens: &mut Lexer<'input>) -> Result<Name, Error> { if tokens.peek() != Tok::IdentifierValue { return Err(unexpected_token_error(tokens, "an identifier")); } let start_loc = tokens.start_loc(); let id = tokens.content().to_string(); tokens.advance()?; let end_loc = tokens.previous_end_loc(); Ok(spanned(tokens.file_name(), start_loc, end_loc, id)) } // Parse an account address: // Address = <AddressValue> fn parse_address<'input>(tokens: &mut Lexer<'input>) -> Result<Address, Error> { if tokens.peek() != Tok::AddressValue { return Err(unexpected_token_error(tokens, "an account address value")); } let addr = Address::parse_str(&tokens.content()).map_err(|msg| vec![(current_token_loc(tokens), msg)]); tokens.advance()?; addr } // Parse a variable name: // Var = <Identifier> fn parse_var<'input>(tokens: &mut Lexer<'input>) -> Result<Var, Error> { Ok(Var(parse_identifier(tokens)?)) } // Parse a field name: // Field = <Identifier> fn parse_field<'input>(tokens: &mut Lexer<'input>) -> Result<Field, Error> { Ok(Field(parse_identifier(tokens)?)) } // Parse a module name: // ModuleName = <Identifier> fn parse_module_name<'input>(tokens: &mut Lexer<'input>) -> Result<ModuleName, Error> { Ok(ModuleName(parse_identifier(tokens)?)) } // Parse a module identifier: // ModuleIdent = <Address> "::" <ModuleName> fn parse_module_ident<'input>(tokens: &mut Lexer<'input>) -> Result<ModuleIdent, Error> { let start_loc = tokens.start_loc(); let address = parse_address(tokens)?; consume_token(tokens, Tok::ColonColon)?; let name = parse_module_name(tokens)?; let end_loc = tokens.previous_end_loc(); let m = ModuleIdent_ { address, name }; Ok(ModuleIdent(spanned( tokens.file_name(), start_loc, end_loc, m, ))) } // Parse a module access (a variable, struct type, or function): // ModuleAccess = // <Identifier> // | <ModuleName> "::" <Identifier> // | <ModuleIdent> "::" <Identifier> fn parse_module_access<'input, F: FnOnce() -> String>( tokens: &mut Lexer<'input>, item_description: F, ) -> Result<ModuleAccess, Error> { let start_loc = tokens.start_loc(); let acc = match tokens.peek() { Tok::IdentifierValue => { // Check if this is a ModuleName followed by "::". let m = parse_identifier(tokens)?; if match_token(tokens, Tok::ColonColon)? { let n = parse_identifier(tokens)?; ModuleAccess_::ModuleAccess(ModuleName(m), n) } else { ModuleAccess_::Name(m) } } Tok::AddressValue => { let m = parse_module_ident(tokens)?; consume_token(tokens, Tok::ColonColon)?; let n = parse_identifier(tokens)?; ModuleAccess_::QualifiedModuleAccess(m, n) } _ => { return Err(unexpected_token_error(tokens, &item_description())); } }; let end_loc = tokens.previous_end_loc(); Ok(spanned(tokens.file_name(), start_loc, end_loc, acc)) } //************************************************************************************************** // Fields and Bindings //************************************************************************************************** // Parse a field name optionally followed by a colon and an expression argument: // ExpField = <Field> <":" <Exp>>? fn parse_exp_field<'input>(tokens: &mut Lexer<'input>) -> Result<(Field, Exp), Error> { let f = parse_field(tokens)?; let arg = if match_token(tokens, Tok::Colon)? { parse_exp(tokens)? } else { sp( f.loc(), Exp_::Name(sp(f.loc(), ModuleAccess_::Name(f.0.clone())), None), ) }; Ok((f, arg)) } // Parse a field name optionally followed by a colon and a binding: // BindField = <Field> <":" <Bind>>? // // If the binding is not specified, the default is to use a variable // with the same name as the field. fn parse_bind_field<'input>(tokens: &mut Lexer<'input>) -> Result<(Field, Bind), Error> { let f = parse_field(tokens)?; let arg = if match_token(tokens, Tok::Colon)? { parse_bind(tokens)? } else { let v = Var(f.0.clone()); sp(v.loc(), Bind_::Var(v)) }; Ok((f, arg)) } // Parse a binding: // Bind = // <Var> // | <ModuleAccess> <OptionalTypeArgs> "{" Comma<BindField> "}" fn parse_bind<'input>(tokens: &mut Lexer<'input>) -> Result<Bind, Error> { let start_loc = tokens.start_loc(); if tokens.peek() == Tok::IdentifierValue { let next_tok = tokens.lookahead()?; if next_tok != Tok::LBrace && next_tok != Tok::Less && next_tok != Tok::ColonColon { let v = Bind_::Var(parse_var(tokens)?); let end_loc = tokens.previous_end_loc(); return Ok(spanned(tokens.file_name(), start_loc, end_loc, v)); } } // The item description specified here should include the special case above for // variable names, because if the current tokens cannot be parsed as a struct name // it is possible that the user intention was to use a variable name. let ty = parse_module_access(tokens, || "a variable or struct name".to_string())?; let ty_args = parse_optional_type_args(tokens)?; let args = parse_comma_list( tokens, Tok::LBrace, Tok::RBrace, parse_bind_field, "a field binding", )?; let end_loc = tokens.previous_end_loc(); let unpack = Bind_::Unpack(ty, ty_args, args); Ok(spanned(tokens.file_name(), start_loc, end_loc, unpack)) } // Parse a list of bindings, which can be zero, one, or more bindings: // BindList = // <Bind> // | "(" Comma<Bind> ")" // // The list is enclosed in parenthesis, except that the parenthesis are // optional if there is a single Bind. fn parse_bind_list<'input>(tokens: &mut Lexer<'input>) -> Result<BindList, Error> { let start_loc = tokens.start_loc(); let b = if tokens.peek() != Tok::LParen { vec![parse_bind(tokens)?] } else { parse_comma_list( tokens, Tok::LParen, Tok::RParen, parse_bind, "a variable or structure binding", )? }; let end_loc = tokens.previous_end_loc(); Ok(spanned(tokens.file_name(), start_loc, end_loc, b)) } // Parse a list of bindings for lambda. // LambdaBindList = // "|" Comma<Bind> "|" fn parse_lambda_bind_list<'input>(tokens: &mut Lexer<'input>) -> Result<BindList, Error> { let start_loc = tokens.start_loc(); let b = parse_comma_list( tokens, Tok::Pipe, Tok::Pipe, parse_bind, "a variable or structure binding", )?; let end_loc = tokens.previous_end_loc(); Ok(spanned(tokens.file_name(), start_loc, end_loc, b)) } //************************************************************************************************** // Values //************************************************************************************************** // Parse a byte string: // ByteString = <ByteStringValue> fn parse_byte_string<'input>(tokens: &mut Lexer<'input>) -> Result<Value_, Error> { if tokens.peek() != Tok::ByteStringValue { return Err(unexpected_token_error(tokens, "a byte string value")); } let s = tokens.content(); let text = s[2..s.len() - 1].to_owned(); let value_ = if s.starts_with("x\"") { Value_::HexString(text) } else { assert!(s.starts_with("b\"")); Value_::ByteString(text) }; tokens.advance()?; Ok(value_) } // Parse a value: // Value = // <Address> // | "true" // | "false" // | <U8Value> // | <U64Value> // | <U128Value> // | <ByteString> fn parse_value<'input>(tokens: &mut Lexer<'input>) -> Result<Value, Error> { let start_loc = tokens.start_loc(); let val = match tokens.peek() { Tok::AddressValue => { let addr = parse_address(tokens)?; Value_::Address(addr) } Tok::True => { tokens.advance()?; Value_::Bool(true) } Tok::False => { tokens.advance()?; Value_::Bool(false) } Tok::U8Value => { let mut s = tokens.content(); if s.ends_with("u8") { s = &s[..s.len() - 2] } let i = u8::from_str(s).unwrap(); tokens.advance()?; Value_::U8(i) } Tok::U64Value => { let mut s = tokens.content(); if s.ends_with("u64") { s = &s[..s.len() - 3] } let i = u64::from_str(s).unwrap(); tokens.advance()?; Value_::U64(i) } Tok::U128Value => { let mut s = tokens.content(); if s.ends_with("u128") { s = &s[..s.len() - 4] } let i = u128::from_str(s).unwrap(); tokens.advance()?; Value_::U128(i) } Tok::ByteStringValue => parse_byte_string(tokens)?, _ => unreachable!("parse_value called with invalid token"), }; let end_loc = tokens.previous_end_loc(); Ok(spanned(tokens.file_name(), start_loc, end_loc, val)) } // Parse a num value: // Num = <NumValue> fn parse_num(tokens: &mut Lexer) -> Result<u128, Error> { let start_loc = tokens.start_loc(); assert_eq!(tokens.peek(), Tok::NumValue); let res = match u128::from_str(tokens.content()) { Ok(i) => Ok(i), Err(_) => { let end_loc = start_loc + tokens.content().len(); let loc = make_loc(tokens.file_name(), start_loc, end_loc); let msg = "Invalid number literal. The given literal is too large to fit into the \ largest number type 'u128'"; Err(vec![(loc, msg.to_owned())]) } }; tokens.advance()?; res } //************************************************************************************************** // Sequences //************************************************************************************************** // Parse a sequence item: // SequenceItem = // <Exp> // | "let" <BindList> (":" <Type>)? ("=" <Exp>)? fn parse_sequence_item<'input>(tokens: &mut Lexer<'input>) -> Result<SequenceItem, Error> { let start_loc = tokens.start_loc(); let item = if match_token(tokens, Tok::Let)? { let b = parse_bind_list(tokens)?; let ty_opt = if match_token(tokens, Tok::Colon)? { Some(parse_type(tokens)?) } else { None }; if match_token(tokens, Tok::Equal)? { let e = parse_exp(tokens)?; SequenceItem_::Bind(b, ty_opt, Box::new(e)) } else { SequenceItem_::Declare(b, ty_opt) } } else { let e = parse_exp(tokens)?; SequenceItem_::Seq(Box::new(e)) }; let end_loc = tokens.previous_end_loc(); Ok(spanned(tokens.file_name(), start_loc, end_loc, item)) } // Parse a sequence: // Sequence = <UseDecl>* (<SequenceItem> ";")* <Exp>? "}" // // Note that this does not include the opening brace of a block but it // does consume the closing right brace. fn parse_sequence<'input>(tokens: &mut Lexer<'input>) -> Result<Sequence, Error> { let mut uses = vec![]; while tokens.peek() == Tok::Use { uses.push(parse_use_decl(tokens)?); } let mut seq: Vec<SequenceItem> = vec![]; let mut last_semicolon_loc = None; let mut eopt = None; while tokens.peek() != Tok::RBrace { let item = parse_sequence_item(tokens)?; if tokens.peek() == Tok::RBrace { // If the sequence ends with an expression that is not // followed by a semicolon, split out that expression // from the rest of the SequenceItems. if let SequenceItem_::Seq(e) = item.value { eopt = Some(Spanned { loc: item.loc, value: e.value, }); } else { seq.push(item); } break; } seq.push(item); last_semicolon_loc = Some(current_token_loc(&tokens)); consume_token(tokens, Tok::Semicolon)?; } tokens.advance()?; // consume the RBrace Ok((uses, seq, last_semicolon_loc, Box::new(eopt))) } //************************************************************************************************** // Expressions //************************************************************************************************** // Parse an expression term: // Term = // "break" // | "continue" // | <NameExp> // | <Value> // | <Num> // | "(" Comma<Exp> ")" // | "(" <Exp> ":" <Type> ")" // | "(" <Exp> "as" <Type> ")" // | "{" <Sequence> fn parse_term<'input>(tokens: &mut Lexer<'input>) -> Result<Exp, Error> { let start_loc = tokens.start_loc(); let term = match tokens.peek() { Tok::Break => { tokens.advance()?; Exp_::Break } Tok::Continue => { tokens.advance()?; Exp_::Continue } Tok::IdentifierValue => parse_name_exp(tokens)?, Tok::AddressValue => { // Check if this is a ModuleIdent (in a ModuleAccess). if tokens.lookahead()? == Tok::ColonColon { parse_name_exp(tokens)? } else { Exp_::Value(parse_value(tokens)?) } } Tok::True | Tok::False | Tok::U8Value | Tok::U64Value | Tok::U128Value | Tok::ByteStringValue => Exp_::Value(parse_value(tokens)?), Tok::NumValue => Exp_::InferredNum(parse_num(tokens)?), // "(" Comma<Exp> ")" // "(" <Exp> ":" <Type> ")" // "(" <Exp> "as" <Type> ")" Tok::LParen => { let list_loc = tokens.start_loc(); tokens.advance()?; // consume the LParen if match_token(tokens, Tok::RParen)? { Exp_::Unit } else { // If there is a single expression inside the parens, // then it may be followed by a colon and a type annotation. let e = parse_exp(tokens)?; if match_token(tokens, Tok::Colon)? { let ty = parse_type(tokens)?; consume_token(tokens, Tok::RParen)?; Exp_::Annotate(Box::new(e), ty) } else if match_token(tokens, Tok::As)? { let ty = parse_type(tokens)?; consume_token(tokens, Tok::RParen)?; Exp_::Cast(Box::new(e), ty) } else { if tokens.peek() != Tok::RParen { consume_token(tokens, Tok::Comma)?; } let mut es = parse_comma_list_after_start( tokens, list_loc, Tok::LParen, Tok::RParen, parse_exp, "an expression", )?; if es.is_empty() { e.value } else { es.insert(0, e); Exp_::ExpList(es) } } } } // "{" <Sequence> Tok::LBrace => { tokens.advance()?; // consume the LBrace Exp_::Block(parse_sequence(tokens)?) } Tok::Spec => { let spec_block = parse_spec_block(tokens)?; Exp_::Spec(spec_block) } _ => { return Err(unexpected_token_error(tokens, "an expression term")); } }; let end_loc = tokens.previous_end_loc(); Ok(spanned(tokens.file_name(), start_loc, end_loc, term)) } // Parse a pack, call, or other reference to a name: // NameExp = // <ModuleAccess> <OptionalTypeArgs> "{" Comma<ExpField> "}" // | <ModuleAccess> <OptionalTypeArgs> "(" Comma<Exp> ")" // | <ModuleAccess> <OptionalTypeArgs> fn parse_name_exp<'input>(tokens: &mut Lexer<'input>) -> Result<Exp_, Error> { let n = parse_module_access(tokens, || { panic!("parse_name_exp with something other than a ModuleAccess") })?; // There's an ambiguity if the name is followed by a "<". If there is no whitespace // after the name, treat it as the start of a list of type arguments. Otherwise // assume that the "<" is a boolean operator. let mut tys = None; let start_loc = tokens.start_loc(); if tokens.peek() == Tok::Less && start_loc == n.loc.span().end().to_usize() { let loc = make_loc(tokens.file_name(), start_loc, start_loc); tys = parse_optional_type_args(tokens).map_err(|mut e| { let msg = "Perhaps you need a blank space before this '<' operator?"; e.push((loc, msg.to_owned())); e })?; } match tokens.peek() { // Pack: "{" Comma<ExpField> "}" Tok::LBrace => { let fs = parse_comma_list( tokens, Tok::LBrace, Tok::RBrace, parse_exp_field, "a field expression", )?; Ok(Exp_::Pack(n, tys, fs)) } // Call: "(" Comma<Exp> ")" Tok::LParen => { let rhs = parse_call_args(tokens)?; Ok(Exp_::Call(n, tys, rhs)) } // Other name reference... _ => Ok(Exp_::Name(n, tys)), } } // Parse the arguments to a call: "(" Comma<Exp> ")" fn parse_call_args<'input>(tokens: &mut Lexer<'input>) -> Result<Spanned<Vec<Exp>>, Error> { let start_loc = tokens.start_loc(); let args = parse_comma_list( tokens, Tok::LParen, Tok::RParen, parse_exp, "a call argument expression", )?; let end_loc = tokens.previous_end_loc(); Ok(spanned(tokens.file_name(), start_loc, end_loc, args)) } // Return true if the current token is one that might occur after an Exp. // This is needed, for example, to check for the optional Exp argument to // a return (where "return" is itself an Exp). fn at_end_of_exp<'input>(tokens: &mut Lexer<'input>) -> bool { matches!( tokens.peek(), // These are the tokens that can occur after an Exp. If the grammar // changes, we need to make sure that these are kept up to date and that // none of these tokens can occur at the beginning of an Exp. Tok::Else | Tok::RBrace | Tok::RParen | Tok::Comma | Tok::Colon | Tok::Semicolon ) } // Parse an expression: // Exp = // <LambdaBindList> <Exp> spec only // | <Quantifier> spec only // | "if" "(" <Exp> ")" <Exp> ("else" <Exp>)? // | "while" "(" <Exp> ")" <Exp> // | "loop" <Exp> // | "return" <Exp>? // | "abort" <Exp> // | <BinOpExp> // | <UnaryExp> "=" <Exp> fn parse_exp<'input>(tokens: &mut Lexer<'input>) -> Result<Exp, Error> { let start_loc = tokens.start_loc(); let exp = match tokens.peek() { Tok::Pipe => { let bindings = parse_lambda_bind_list(tokens)?; let body = Box::new(parse_exp(tokens)?); Exp_::Lambda(bindings, body) } Tok::IdentifierValue if is_quant(tokens) => parse_quant(tokens)?, Tok::If => { tokens.advance()?; consume_token(tokens, Tok::LParen)?; let eb = Box::new(parse_exp(tokens)?); consume_token(tokens, Tok::RParen)?; let et = Box::new(parse_exp(tokens)?); let ef = if match_token(tokens, Tok::Else)? { Some(Box::new(parse_exp(tokens)?)) } else { None }; Exp_::IfElse(eb, et, ef) } Tok::While => { tokens.advance()?; consume_token(tokens, Tok::LParen)?; let eb = Box::new(parse_exp(tokens)?); consume_token(tokens, Tok::RParen)?; let eloop = Box::new(parse_exp(tokens)?); Exp_::While(eb, eloop) } Tok::Loop => { tokens.advance()?; let eloop = Box::new(parse_exp(tokens)?); Exp_::Loop(eloop) } Tok::Return => { tokens.advance()?; let e = if at_end_of_exp(tokens) { None } else { Some(Box::new(parse_exp(tokens)?)) }; Exp_::Return(e) } Tok::Abort => { tokens.advance()?; let e = Box::new(parse_exp(tokens)?); Exp_::Abort(e) } _ => { // This could be either an assignment or a binary operator // expression. let lhs = parse_unary_exp(tokens)?; if tokens.peek() != Tok::Equal { return parse_binop_exp(tokens, lhs, /* min_prec */ 1); } tokens.advance()?; // consume the "=" let rhs = Box::new(parse_exp(tokens)?); Exp_::Assign(Box::new(lhs), rhs) } }; let end_loc = tokens.previous_end_loc(); Ok(spanned(tokens.file_name(), start_loc, end_loc, exp)) } // Get the precedence of a binary operator. The minimum precedence value // is 1, and larger values have higher precedence. For tokens that are not // binary operators, this returns a value of zero so that they will be // below the minimum value and will mark the end of the binary expression // for the code in parse_binop_exp. fn get_precedence(token: Tok) -> u32 { match token { // Reserved minimum precedence value is 1 Tok::EqualEqualGreater => 2, Tok::PipePipe => 3, Tok::AmpAmp => 4, Tok::EqualEqual => 5, Tok::ExclaimEqual => 5, Tok::Less => 5, Tok::Greater => 5, Tok::LessEqual => 5, Tok::GreaterEqual => 5, Tok::PeriodPeriod => 6, Tok::Pipe => 7, Tok::Caret => 8, Tok::Amp => 9, Tok::LessLess => 10, Tok::GreaterGreater => 10, Tok::Plus => 11, Tok::Minus => 11, Tok::Star => 12, Tok::Slash => 12, Tok::Percent => 12, _ => 0, // anything else is not a binary operator } } // Parse a binary operator expression: // BinOpExp = // <BinOpExp> <BinOp> <BinOpExp> // | <UnaryExp> // BinOp = (listed from lowest to highest precedence) // "==>" spec only // | "||" // | "&&" // | "==" | "!=" | "<" | ">" | "<=" | ">=" // | ".." spec only // | "|" // | "^" // | "&" // | "<<" | ">>" // | "+" | "-" // | "*" | "/" | "%" // // This function takes the LHS of the expression as an argument, and it // continues parsing binary expressions as long as they have at least the // specified "min_prec" minimum precedence. fn parse_binop_exp<'input>( tokens: &mut Lexer<'input>, lhs: Exp, min_prec: u32, ) -> Result<Exp, Error> { let mut result = lhs; let mut next_tok_prec = get_precedence(tokens.peek()); while next_tok_prec >= min_prec { // Parse the operator. let op_start_loc = tokens.start_loc(); let op_token = tokens.peek(); tokens.advance()?; let op_end_loc = tokens.previous_end_loc(); let mut rhs = parse_unary_exp(tokens)?; // If the next token is another binary operator with a higher // precedence, then recursively parse that expression as the RHS. let this_prec = next_tok_prec; next_tok_prec = get_precedence(tokens.peek()); if this_prec < next_tok_prec { rhs = parse_binop_exp(tokens, rhs, this_prec + 1)?; next_tok_prec = get_precedence(tokens.peek()); } let op = match op_token { Tok::EqualEqual => BinOp_::Eq, Tok::ExclaimEqual => BinOp_::Neq, Tok::Less => BinOp_::Lt, Tok::Greater => BinOp_::Gt, Tok::LessEqual => BinOp_::Le, Tok::GreaterEqual => BinOp_::Ge, Tok::PipePipe => BinOp_::Or, Tok::AmpAmp => BinOp_::And, Tok::Caret => BinOp_::Xor, Tok::Pipe => BinOp_::BitOr, Tok::Amp => BinOp_::BitAnd, Tok::LessLess => BinOp_::Shl, Tok::GreaterGreater => BinOp_::Shr, Tok::Plus => BinOp_::Add, Tok::Minus => BinOp_::Sub, Tok::Star => BinOp_::Mul, Tok::Slash => BinOp_::Div, Tok::Percent => BinOp_::Mod, Tok::PeriodPeriod => BinOp_::Range, Tok::EqualEqualGreater => BinOp_::Implies, _ => panic!("Unexpected token that is not a binary operator"), }; let sp_op = spanned(tokens.file_name(), op_start_loc, op_end_loc, op); let start_loc = result.loc.span().start().to_usize(); let end_loc = tokens.previous_end_loc(); let e = Exp_::BinopExp(Box::new(result), sp_op, Box::new(rhs)); result = spanned(tokens.file_name(), start_loc, end_loc, e); } Ok(result) } // Parse a unary expression: // UnaryExp = // "!" <UnaryExp> // | "&mut" <UnaryExp> // | "&" <UnaryExp> // | "*" <UnaryExp> // | "move" <Var> // | "copy" <Var> // | <DotOrIndexChain> fn parse_unary_exp<'input>(tokens: &mut Lexer<'input>) -> Result<Exp, Error> { let start_loc = tokens.start_loc(); let exp = match tokens.peek() { Tok::Exclaim => { tokens.advance()?; let op_end_loc = tokens.previous_end_loc(); let op = spanned(tokens.file_name(), start_loc, op_end_loc, UnaryOp_::Not); let e = parse_unary_exp(tokens)?; Exp_::UnaryExp(op, Box::new(e)) } Tok::AmpMut => { tokens.advance()?; let e = parse_unary_exp(tokens)?; Exp_::Borrow(true, Box::new(e)) } Tok::Amp => { tokens.advance()?; let e = parse_unary_exp(tokens)?; Exp_::Borrow(false, Box::new(e)) } Tok::Star => { tokens.advance()?; let e = parse_unary_exp(tokens)?; Exp_::Dereference(Box::new(e)) } Tok::Move => { tokens.advance()?; Exp_::Move(parse_var(tokens)?) } Tok::Copy => { tokens.advance()?; Exp_::Copy(parse_var(tokens)?) } _ => { return parse_dot_or_index_chain(tokens); } }; let end_loc = tokens.previous_end_loc(); Ok(spanned(tokens.file_name(), start_loc, end_loc, exp)) } // Parse an expression term optionally followed by a chain of dot or index accesses: // DotOrIndexChain = // <DotOrIndexChain> "." <Identifier> // | <DotOrIndexChain> "[" <Exp> "]" spec only // | <Term> fn parse_dot_or_index_chain<'input>(tokens: &mut Lexer<'input>) -> Result<Exp, Error> { let start_loc = tokens.start_loc(); let mut lhs = parse_term(tokens)?; loop { let exp = match tokens.peek() { Tok::Period => { tokens.advance()?; let n = parse_identifier(tokens)?; Exp_::Dot(Box::new(lhs), n) } Tok::LBracket => { tokens.advance()?; let index = parse_exp(tokens)?; let exp = Exp_::Index(Box::new(lhs), Box::new(index)); consume_token(tokens, Tok::RBracket)?; exp } _ => break, }; let end_loc = tokens.previous_end_loc(); lhs = spanned(tokens.file_name(), start_loc, end_loc, exp); } Ok(lhs) } // Lookahead to determine whether this is a quantifier. This matches // // ( "exists" | "forall" ) <Identifier> ( ":" | <Identifier> ) ... // // as a sequence to identify a quantifier. While the <Identifier> after // the exists/forall would by syntactically sufficient (Move does not // have affixed identifiers in expressions), we add another token // of lookahead to keep the result more precise in the presence of // syntax errors. fn is_quant<'input>(tokens: &mut Lexer<'input>) -> bool { if !matches!(tokens.content(), "exists" | "forall") { return false; } match tokens.lookahead2() { Err(_) => false, Ok((tok1, tok2)) => { tok1 == Tok::IdentifierValue && matches!(tok2, Tok::Colon | Tok::IdentifierValue) } } } // Parses a quantifier expressions, assuming is_quant(tokens) is true. // // <Quantifier> = ( "forall" | "exists" ) <QuantifierBindings> ("where" <Exp>)? ":" Exp // <QuantifierBindings> = <QuantifierBind> ("," <QuantifierBind>)* // <QuantifierBind> = <Identifier> ":" <Type> | <Identifier> "in" <Exp> // // Parsing happens recursively and quantifiers are immediately reduced as syntactic sugar // for lambdas. fn parse_quant<'input>(tokens: &mut Lexer<'input>) -> Result<Exp_, Error> { let is_forall = matches!(tokens.content(), "forall"); tokens.advance()?; parse_quant_cont(is_forall, tokens) } // Parses quantifier bindings recursively until the body is reached. fn parse_quant_cont<'input>(is_forall: bool, tokens: &mut Lexer<'input>) -> Result<Exp_, Error> { // Parse the next quantifier variable binding let start_loc = tokens.start_loc(); let ident = parse_identifier(tokens)?; let ident_end_loc = tokens.previous_end_loc(); let range = if tokens.peek() == Tok::Colon { // This is a quantifier over the full domain of a type. // Built `domain<ty>()` expression. tokens.advance()?; let ty = parse_type(tokens)?; make_builtin_call(ty.loc, "$spec_domain", Some(vec![ty]), vec![]) } else { // This is a quantifier over a value, like a vector or a range. consume_identifier(tokens, "in")?; parse_exp(tokens)? }; // Continue parsing more bindings or the body of the quantifier let (body_loc, body_) = if tokens.peek() == Tok::Comma { tokens.advance()?; (tokens.start_loc(), parse_quant_cont(is_forall, tokens)?) } else { (tokens.start_loc(), parse_quant_body(is_forall, tokens)?) }; let body = spanned( tokens.file_name(), body_loc, tokens.previous_end_loc(), body_, ); // Construct ::<all|any>(range, |ident| body) as the result let bind = spanned( tokens.file_name(), start_loc, ident_end_loc, Bind_::Var(Var(ident)), ); let bind_list = sp(bind.loc, vec![bind]); let lambda = spanned( tokens.file_name(), start_loc, tokens.previous_end_loc(), Exp_::Lambda(bind_list, Box::new(body)), ); Ok(make_builtin_call( lambda.loc, if is_forall { "$spec_all" } else { "$spec_any" }, None, vec![range, lambda], ) .value) } // Parse quantifier body. fn parse_quant_body<'input>(is_forall: bool, tokens: &mut Lexer<'input>) -> Result<Exp_, Error> { let opt_cond = match tokens.peek() { Tok::IdentifierValue if tokens.content() == "where" => { tokens.advance()?; Some(parse_exp(tokens)?) } _ => None, }; consume_token(tokens, Tok::Colon)?; let body = parse_exp(tokens)?; if let Some(cond) = opt_cond { let op = sp( cond.loc, if is_forall { BinOp_::Implies } else { BinOp_::And }, ); Ok(Exp_::BinopExp(Box::new(cond), op, Box::new(body))) } else { Ok(body.value) } } fn make_builtin_call(loc: Loc, name: &str, type_args: Option<Vec<Type>>, args: Vec<Exp>) -> Exp { let maccess = sp(loc, ModuleAccess_::Name(sp(loc, name.to_string()))); sp(loc, Exp_::Call(maccess, type_args, sp(loc, args))) } //************************************************************************************************** // Types //************************************************************************************************** // Parse a Type: // Type = // <ModuleAccess> ("<" Comma<Type> ">")? // | "&" <Type> // | "&mut" <Type> // | "|" Comma<Type> "|" Type (spec only) // | "(" Comma<Type> ")" fn parse_type<'input>(tokens: &mut Lexer<'input>) -> Result<Type, Error> { let start_loc = tokens.start_loc(); let t = match tokens.peek() { Tok::LParen => { let mut ts = parse_comma_list(tokens, Tok::LParen, Tok::RParen, parse_type, "a type")?; match ts.len() { 0 => Type_::Unit, 1 => ts.pop().unwrap().value, _ => Type_::Multiple(ts), } } Tok::Amp => { tokens.advance()?; let t = parse_type(tokens)?; Type_::Ref(false, Box::new(t)) } Tok::AmpMut => { tokens.advance()?; let t = parse_type(tokens)?; Type_::Ref(true, Box::new(t)) } Tok::Pipe => { let args = parse_comma_list(tokens, Tok::Pipe, Tok::Pipe, parse_type, "a type")?; let result = parse_type(tokens)?; return Ok(spanned( tokens.file_name(), start_loc, tokens.previous_end_loc(), Type_::Fun(args, Box::new(result)), )); } _ => { let tn = parse_module_access(tokens, || "a type name".to_string())?; let tys = if tokens.peek() == Tok::Less { parse_comma_list(tokens, Tok::Less, Tok::Greater, parse_type, "a type")? } else { vec![] }; Type_::Apply(Box::new(tn), tys) } }; let end_loc = tokens.previous_end_loc(); Ok(spanned(tokens.file_name(), start_loc, end_loc, t)) } // Parse an optional list of type arguments. // OptionalTypeArgs = "<" Comma<Type> ">" | <empty> fn parse_optional_type_args<'input>( tokens: &mut Lexer<'input>, ) -> Result<Option<Vec<Type>>, Error> { if tokens.peek() == Tok::Less { Ok(Some(parse_comma_list( tokens, Tok::Less, Tok::Greater, parse_type, "a type", )?)) } else { Ok(None) } } // Parse a type parameter: // TypeParameter = // <Identifier> <Constraint>? // Constraint = // ":" "copyable" // | ":" "resource" fn parse_type_parameter<'input>(tokens: &mut Lexer<'input>) -> Result<(Name, Kind), Error> { let n = parse_identifier(tokens)?; let kind = if match_token(tokens, Tok::Colon)? { let start_loc = tokens.start_loc(); let k = match tokens.peek() { Tok::Copyable => Kind_::Affine, Tok::Resource => Kind_::Resource, _ => { let expected = "either 'copyable' or 'resource'"; return Err(unexpected_token_error(tokens, expected)); } }; tokens.advance()?; let end_loc = tokens.previous_end_loc(); spanned(tokens.file_name(), start_loc, end_loc, k) } else { sp(n.loc, Kind_::Unknown) }; Ok((n, kind)) } // Parse optional type parameter list. // OptionalTypeParameters = "<" Comma<TypeParameter> ">" | <empty> fn parse_optional_type_parameters<'input>( tokens: &mut Lexer<'input>, ) -> Result<Vec<(Name, Kind)>, Error> { if tokens.peek() == Tok::Less { parse_comma_list( tokens, Tok::Less, Tok::Greater, parse_type_parameter, "a type parameter", ) } else { Ok(vec![]) } } //************************************************************************************************** // Functions //************************************************************************************************** // Parse a function declaration: // FunctionDecl = // <NativeFunctionDecl> // | <MoveFunctionDecl> // NativeFunctionDecl = // <DocComments> "native" ( "public" )? "fun" // <FunctionDefName> "(" Comma<Parameter> ")" // (":" <Type>)? // ("acquires" <ModuleAccess> ("," <ModuleAccess>)*)? // ";" // MoveFunctionDecl = // <DocComments> ( "public" )? "fun" // <FunctionDefName> "(" Comma<Parameter> ")" // (":" <Type>)? // ("acquires" <ModuleAccess> ("," <ModuleAccess>)*)? // "{" <Sequence> // FunctionDefName = // <Identifier> <OptionalTypeParameters> // // If the "allow_native" parameter is false, this will only accept Move // functions. fn parse_function_decl<'input>( tokens: &mut Lexer<'input>, allow_native: bool, ) -> Result<Function, Error> { tokens.match_doc_comments(); let start_loc = tokens.start_loc(); // Record the source location of the "native" keyword (if there is one). let native_opt = if allow_native { consume_optional_token_with_loc(tokens, Tok::Native)? } else { if tokens.peek() == Tok::Native { let loc = current_token_loc(tokens); return Err(vec![( loc, "Native functions can only be declared inside a module".to_string(), )]); } None }; // (<Public>)? let public_opt = consume_optional_token_with_loc(tokens, Tok::Public)?; let visibility = if let Some(loc) = public_opt { FunctionVisibility::Public(loc) } else { FunctionVisibility::Internal }; // "fun" <FunctionDefName> consume_token(tokens, Tok::Fun)?; let name = FunctionName(parse_identifier(tokens)?); let type_parameters = parse_optional_type_parameters(tokens)?; // "(" Comma<Parameter> ")" let parameters = parse_comma_list( tokens, Tok::LParen, Tok::RParen, parse_parameter, "a function parameter", )?; // (":" <Type>)? let return_type = if match_token(tokens, Tok::Colon)? { parse_type(tokens)? } else { sp(name.loc(), Type_::Unit) }; // ("acquires" (<ModuleAccess> ",")* <ModuleAccess> ","? let mut acquires = vec![]; if match_token(tokens, Tok::Acquires)? { let follows_acquire = |tok| matches!(tok, Tok::Semicolon | Tok::LBrace); loop { acquires.push(parse_module_access(tokens, || { "a resource struct name".to_string() })?); if follows_acquire(tokens.peek()) { break; } consume_token(tokens, Tok::Comma)?; if follows_acquire(tokens.peek()) { break; } } } let body = match native_opt { Some(loc) => { consume_token(tokens, Tok::Semicolon)?; sp(loc, FunctionBody_::Native) } _ => { let start_loc = tokens.start_loc(); consume_token(tokens, Tok::LBrace)?; let seq = parse_sequence(tokens)?; let end_loc = tokens.previous_end_loc(); sp( make_loc(tokens.file_name(), start_loc, end_loc), FunctionBody_::Defined(seq), ) } }; let signature = FunctionSignature { type_parameters, parameters, return_type, }; let loc = make_loc(tokens.file_name(), start_loc, tokens.previous_end_loc()); Ok(Function { loc, visibility, signature, acquires, name, body, }) } // Parse a function parameter: // Parameter = <Var> ":" <Type> fn parse_parameter<'input>(tokens: &mut Lexer<'input>) -> Result<(Var, Type), Error> { let v = parse_var(tokens)?; consume_token(tokens, Tok::Colon)?; let t = parse_type(tokens)?; Ok((v, t)) } //************************************************************************************************** // Structs //************************************************************************************************** // Parse a struct definition: // StructDefinition = // <DocComments> "resource"? "struct" <StructDefName> "{" Comma<FieldAnnot> "}" // | <DocComments> "native" "resource"? "struct" <StructDefName> ";" // StructDefName = // <Identifier> <OptionalTypeParameters> fn parse_struct_definition<'input>(tokens: &mut Lexer<'input>) -> Result<StructDefinition, Error> { tokens.match_doc_comments(); let start_loc = tokens.start_loc(); // Record the source location of the "native" keyword (if there is one). let native_opt = consume_optional_token_with_loc(tokens, Tok::Native)?; // Record the source location of the "resource" keyword (if there is one). let resource_opt = consume_optional_token_with_loc(tokens, Tok::Resource)?; consume_token(tokens, Tok::Struct)?; // <StructDefName> let name = StructName(parse_identifier(tokens)?); let type_parameters = parse_optional_type_parameters(tokens)?; let fields = match native_opt { Some(loc) => { consume_token(tokens, Tok::Semicolon)?; StructFields::Native(loc) } _ => { let list = parse_comma_list( tokens, Tok::LBrace, Tok::RBrace, parse_field_annot, "a field", )?; StructFields::Defined(list) } }; let loc = make_loc(tokens.file_name(), start_loc, tokens.previous_end_loc()); Ok(StructDefinition { loc, resource_opt, name, type_parameters, fields, }) } // Parse a field annotated with a type: // FieldAnnot = <DocComments> <Field> ":" <Type> fn parse_field_annot<'input>(tokens: &mut Lexer<'input>) -> Result<(Field, Type), Error> { tokens.match_doc_comments(); let f = parse_field(tokens)?; consume_token(tokens, Tok::Colon)?; let st = parse_type(tokens)?; Ok((f, st)) } //************************************************************************************************** // Constants //************************************************************************************************** // Parse a constant: // ConstantDecl = "const" <Identifier> ":" <Type> "=" <Exp> ";" fn parse_constant<'input>(tokens: &mut Lexer<'input>) -> Result<Constant, Error> { tokens.match_doc_comments(); let start_loc = tokens.start_loc(); consume_token(tokens, Tok::Const)?; let name = ConstantName(parse_identifier(tokens)?); consume_token(tokens, Tok::Colon)?; let signature = parse_type(tokens)?; consume_token(tokens, Tok::Equal)?; let value = parse_exp(tokens)?; consume_token(tokens, Tok::Semicolon)?; let loc = make_loc(tokens.file_name(), start_loc, tokens.previous_end_loc()); Ok(Constant { loc, name, signature, value, }) } //************************************************************************************************** // AddressBlock //************************************************************************************************** // Parse an address block: // AddressBlock = // "address" <Address> "{" // <Module>* // "}" // // Note that "address" is not a token. fn parse_address_block<'input>( tokens: &mut Lexer<'input>, ) -> Result<(Loc, Address, Vec<ModuleDefinition>), Error> { const UNEXPECTED_TOKEN: &str = "Invalid code unit. Expected 'address', 'module', or 'script'"; if tokens.peek() != Tok::IdentifierValue { let start = tokens.start_loc(); let end = start + tokens.content().len(); let loc = make_loc(tokens.file_name(), start, end); return Err(vec![( loc, format!("{}. Got '{}'", UNEXPECTED_TOKEN, tokens.content()), )]); } let addr_name = parse_identifier(tokens)?; if addr_name.value != "address" { return Err(vec![( addr_name.loc, format!("{}. Got '{}'", UNEXPECTED_TOKEN, addr_name.value), )]); } let start_loc = tokens.start_loc(); let addr = parse_address(tokens)?; let end_loc = tokens.previous_end_loc(); let loc = make_loc(tokens.file_name(), start_loc, end_loc); consume_token(tokens, Tok::LBrace)?; let mut modules = vec![]; while tokens.peek() != Tok::RBrace { modules.push(parse_module(tokens)?); } consume_token(tokens, Tok::RBrace)?; Ok((loc, addr, modules)) } //************************************************************************************************** // Modules //************************************************************************************************** // Parse a use declaration: // UseDecl = // "use" <ModuleIdent> <UseAlias> ";" | // "use" <ModuleIdent> :: <UseMember> ";" | // "use" <ModuleIdent> :: "{" Comma<UseMember> "}" ";" fn parse_use_decl<'input>(tokens: &mut Lexer<'input>) -> Result<Use, Error> { consume_token(tokens, Tok::Use)?; let ident = parse_module_ident(tokens)?; let alias_opt = parse_use_alias(tokens)?; let use_ = match (&alias_opt, tokens.peek()) { (None, Tok::ColonColon) => { consume_token(tokens, Tok::ColonColon)?; let sub_uses = match tokens.peek() { Tok::LBrace => parse_comma_list( tokens, Tok::LBrace, Tok::RBrace, parse_use_member, "a module member alias", )?, _ => vec![parse_use_member(tokens)?], }; Use::Members(ident, sub_uses) } _ => Use::Module(ident, alias_opt.map(ModuleName)), }; consume_token(tokens, Tok::Semicolon)?; Ok(use_) } // Parse an alias for a module member: // UseMember = <Identifier> <UseAlias> fn parse_use_member<'input>(tokens: &mut Lexer<'input>) -> Result<(Name, Option<Name>), Error> { let member = parse_identifier(tokens)?; let alias_opt = parse_use_alias(tokens)?; Ok((member, alias_opt)) } // Parse an 'as' use alias: // UseAlias = ("as" <Identifier>)? fn parse_use_alias<'input>(tokens: &mut Lexer<'input>) -> Result<Option<Name>, Error> { Ok(if tokens.peek() == Tok::As { tokens.advance()?; Some(parse_identifier(tokens)?) } else { None }) } // TODO rework parsing modifiers fn is_struct_definition<'input>(tokens: &mut Lexer<'input>) -> Result<bool, Error> { let mut t = tokens.peek(); if t == Tok::Native { t = tokens.lookahead()?; } Ok(t == Tok::Struct || t == Tok::Resource) } // Parse a module: // Module = // <DocComments> "module" <ModuleName> "{" // <UseDecl>* // ( <ConstantDecl> | <StructDefinition> | <FunctionDecl> | <Spec> )* // "}" fn parse_module<'input>(tokens: &mut Lexer<'input>) -> Result<ModuleDefinition, Error> { tokens.match_doc_comments(); let start_loc = tokens.start_loc(); consume_token(tokens, Tok::Module)?; let name = parse_module_name(tokens)?; consume_token(tokens, Tok::LBrace)?; let mut members = vec![]; while tokens.peek() != Tok::RBrace { members.push(match tokens.peek() { Tok::Spec => ModuleMember::Spec(parse_spec_block(tokens)?), Tok::Use => ModuleMember::Use(parse_use_decl(tokens)?), Tok::Const => ModuleMember::Constant(parse_constant(tokens)?), // TODO rework parsing modifiers _ if is_struct_definition(tokens)? => { ModuleMember::Struct(parse_struct_definition(tokens)?) } _ => ModuleMember::Function(parse_function_decl(tokens, /* allow_native */ true)?), }) } consume_token(tokens, Tok::RBrace)?; let loc = make_loc(tokens.file_name(), start_loc, tokens.previous_end_loc()); Ok(ModuleDefinition { loc, name, members }) } //************************************************************************************************** // Scripts //************************************************************************************************** // Parse a script: // Script = // "script" "{" // <UseDecl>* // <ConstantDecl>* // <MoveFunctionDecl> // "}" fn parse_script<'input>(tokens: &mut Lexer<'input>) -> Result<Script, Error> { let start_loc = tokens.start_loc(); consume_token(tokens, Tok::Script)?; consume_token(tokens, Tok::LBrace)?; let mut uses = vec![]; while tokens.peek() == Tok::Use { uses.push(parse_use_decl(tokens)?); } let mut constants = vec![]; while tokens.peek() == Tok::Const { constants.push(parse_constant(tokens)?); } let function = parse_function_decl(tokens, /* allow_native */ false)?; let mut specs = vec![]; while tokens.peek() == Tok::Spec { specs.push(parse_spec_block(tokens)?) } if tokens.peek() != Tok::RBrace { let loc = current_token_loc(tokens); return Err(vec![( loc, "Unexpected characters after end of 'script' function".to_string(), )]); } consume_token(tokens, Tok::RBrace)?; let loc = make_loc(tokens.file_name(), start_loc, tokens.previous_end_loc()); Ok(Script { loc, uses, constants, function, specs, }) } //************************************************************************************************** // Specification Blocks //************************************************************************************************** // Parse an optional specification block: // SpecBlockTarget = // "fun" <Identifier> // | "struct <Identifier> // | "module" // | "schema" <Identifier> <OptionalTypeParameters> // | <empty> // SpecBlock = // <DocComments> "spec" ( <SpecFunction> | <SpecBlockTarget> "{" SpecBlockMember* "}" ) fn parse_spec_block<'input>(tokens: &mut Lexer<'input>) -> Result<SpecBlock, Error> { tokens.match_doc_comments(); let start_loc = tokens.start_loc(); consume_token(tokens, Tok::Spec)?; let target_start_loc = tokens.start_loc(); let target_end_loc = target_start_loc + tokens.content().len(); if matches!(tokens.peek(), Tok::Define | Tok::Native) { // Special treatment of the 'spec [native] define ..` short form. This is mapped into an AST // which matches 'spec module { [native] define .. }`. let define = parse_spec_function(tokens)?; return Ok(spanned( tokens.file_name(), start_loc, tokens.previous_end_loc(), SpecBlock_ { target: spanned( tokens.file_name(), target_start_loc, target_end_loc, SpecBlockTarget_::Module, ), uses: vec![], members: vec![define], }, )); } let target_ = match tokens.peek() { Tok::Fun => { tokens.advance()?; let name = FunctionName(parse_identifier(tokens)?); SpecBlockTarget_::Function(name) } Tok::Struct => { tokens.advance()?; let name = StructName(parse_identifier(tokens)?); SpecBlockTarget_::Structure(name) } Tok::Module => { tokens.advance()?; SpecBlockTarget_::Module } Tok::IdentifierValue if tokens.content() == "schema" => { tokens.advance()?; let name = parse_identifier(tokens)?; let type_parameters = parse_optional_type_parameters(tokens)?; SpecBlockTarget_::Schema(name, type_parameters) } Tok::LBrace => SpecBlockTarget_::Code, _ => { return Err(unexpected_token_error( tokens, "one of `module`, `struct`, `fun`, `schema`, or `{`", )); } }; let target = spanned( tokens.file_name(), target_start_loc, match target_ { SpecBlockTarget_::Code => target_start_loc, _ => tokens.previous_end_loc(), }, target_, ); consume_token(tokens, Tok::LBrace)?; let mut uses = vec![]; while tokens.peek() == Tok::Use { uses.push(parse_use_decl(tokens)?); } let mut members = vec![]; while tokens.peek() != Tok::RBrace { members.push(parse_spec_block_member(tokens)?); } consume_token(tokens, Tok::RBrace)?; Ok(spanned( tokens.file_name(), start_loc, tokens.previous_end_loc(), SpecBlock_ { target, uses, members, }, )) } // Parse a spec block member: // SpecBlockMember = <DocComments ( <Invariant> | <Condition> | <SpecFunction> | <SpecVariable> // | <SpecInclude> | <SpecApply> | <SpecPragma> | <SpecLet> ) fn parse_spec_block_member<'input>(tokens: &mut Lexer<'input>) -> Result<SpecBlockMember, Error> { tokens.match_doc_comments(); match tokens.peek() { Tok::Invariant => parse_invariant(tokens), Tok::Let => parse_spec_let(tokens), Tok::Define | Tok::Native => parse_spec_function(tokens), Tok::IdentifierValue => match tokens.content() { "assert" | "assume" | "decreases" | "aborts_if" | "succeeds_if" | "ensures" | "requires" => parse_condition(tokens), "include" => parse_spec_include(tokens), "apply" => parse_spec_apply(tokens), "pragma" => parse_spec_pragma(tokens), "global" | "local" => parse_spec_variable(tokens), _ => { // local is optional but supported to be able to declare variables which are // named like the weak keywords above parse_spec_variable(tokens) } }, _ => Err(unexpected_token_error( tokens, "one of `assert`, `assume`, `decreases`, `aborts_if`, `succeeds_if`, `ensures`, \ `requires`, `include`, `apply`, `pragma`, `global`, or a name", )), } } // Parse a specification condition: // SpecCondition = // ("assert" | "assume" | "decreases" | "aborts_if" | "ensures" | "requires" ) // <ConditionProperties> <Exp> ";" fn parse_condition<'input>(tokens: &mut Lexer<'input>) -> Result<SpecBlockMember, Error> { let start_loc = tokens.start_loc(); let kind = match tokens.content() { "assert" => SpecConditionKind::Assert, "assume" => SpecConditionKind::Assume, "decreases" => SpecConditionKind::Decreases, "aborts_if" => SpecConditionKind::AbortsIf, "succeeds_if" => SpecConditionKind::SucceedsIf, "ensures" => SpecConditionKind::Ensures, "requires" => { if tokens.lookahead()? == Tok::Module { tokens.advance()?; SpecConditionKind::RequiresModule } else { SpecConditionKind::Requires } } _ => unreachable!(), }; tokens.advance()?; let properties = parse_condition_properties(tokens)?; let exp = parse_exp(tokens)?; consume_token(tokens, Tok::Semicolon)?; let end_loc = tokens.previous_end_loc(); Ok(spanned( tokens.file_name(), start_loc, end_loc, SpecBlockMember_::Condition { kind, properties, exp, }, )) } // Parse properties in a condition. // ConditionProperties = ( "[" Comma<SpecPragmaProperty> "]" )? fn parse_condition_properties<'input>( tokens: &mut Lexer<'input>, ) -> Result<Vec<PragmaProperty>, Error> { let properties = if tokens.peek() == Tok::LBracket { parse_comma_list( tokens, Tok::LBracket, Tok::RBracket, parse_spec_property, "a condition property", )? } else { vec![] }; Ok(properties) } // Parse an invariant: // Invariant = "invariant" ( "update" | "pack" | "unpack" | "module" )? // <ConditionProperties> <Exp> ";" fn parse_invariant<'input>(tokens: &mut Lexer<'input>) -> Result<SpecBlockMember, Error> { let start_loc = tokens.start_loc(); consume_token(tokens, Tok::Invariant)?; let kind = match tokens.peek() { Tok::IdentifierValue => { // The update/pack/unpack modifiers are 'weak' keywords. They are reserved // only when following an "invariant" token. One can use "invariant (update ...)" to // force interpretation as identifiers in expressions. match tokens.content() { "update" => { tokens.advance()?; SpecConditionKind::InvariantUpdate } "pack" => { tokens.advance()?; SpecConditionKind::InvariantPack } "unpack" => { tokens.advance()?; SpecConditionKind::InvariantUnpack } _ => SpecConditionKind::Invariant, } } Tok::Module => { tokens.advance()?; SpecConditionKind::InvariantModule } _ => SpecConditionKind::Invariant, }; let properties = parse_condition_properties(tokens)?; let exp = parse_exp(tokens)?; consume_token(tokens, Tok::Semicolon)?; Ok(spanned( tokens.file_name(), start_loc, tokens.previous_end_loc(), SpecBlockMember_::Condition { kind, properties, exp, }, )) } // Parse a specification function. // SpecFunction = "define" <SpecFunctionSignature> ( "{" <Sequence> "}" | ";" ) // | "native" "define" <SpecFunctionSignature> ";" // SpecFunctionSignature = // <Identifier> <OptionalTypeParameters> "(" Comma<Parameter> ")" ":" <Type> fn parse_spec_function<'input>(tokens: &mut Lexer<'input>) -> Result<SpecBlockMember, Error> { let start_loc = tokens.start_loc(); let native_opt = consume_optional_token_with_loc(tokens, Tok::Native)?; consume_token(tokens, Tok::Define)?; let name = FunctionName(parse_identifier(tokens)?); let type_parameters = parse_optional_type_parameters(tokens)?; // "(" Comma<Parameter> ")" let parameters = parse_comma_list( tokens, Tok::LParen, Tok::RParen, parse_parameter, "a function parameter", )?; // ":" <Type>) consume_token(tokens, Tok::Colon)?; let return_type = parse_type(tokens)?; let body_start_loc = tokens.start_loc(); let no_body = tokens.peek() != Tok::LBrace; let (uninterpreted, body_) = if native_opt.is_some() || no_body { consume_token(tokens, Tok::Semicolon)?; (native_opt.is_none(), FunctionBody_::Native) } else { consume_token(tokens, Tok::LBrace)?; let seq = parse_sequence(tokens)?; (false, FunctionBody_::Defined(seq)) }; let body = spanned( tokens.file_name(), body_start_loc, tokens.previous_end_loc(), body_, ); let signature = FunctionSignature { type_parameters, parameters, return_type, }; Ok(spanned( tokens.file_name(), start_loc, tokens.previous_end_loc(), SpecBlockMember_::Function { signature, uninterpreted, name, body, }, )) } // Parse a specification variable. // SpecVariable = ( "global" | "local" )? <Identifier> <OptionalTypeParameters> ":" <Type> ";" fn parse_spec_variable<'input>(tokens: &mut Lexer<'input>) -> Result<SpecBlockMember, Error> { let start_loc = tokens.start_loc(); let is_global = match tokens.content() { "global" => { consume_token(tokens, Tok::IdentifierValue)?; true } "local" => { consume_token(tokens, Tok::IdentifierValue)?; false } _ => false, }; let name = parse_identifier(tokens)?; let type_parameters = parse_optional_type_parameters(tokens)?; consume_token(tokens, Tok::Colon)?; let type_ = parse_type(tokens)?; consume_token(tokens, Tok::Semicolon)?; Ok(spanned( tokens.file_name(), start_loc, tokens.previous_end_loc(), SpecBlockMember_::Variable { is_global, name, type_parameters, type_, }, )) } // Parse a specification let. // SpecLet = "let" <Identifier> "=" <Exp> ";" fn parse_spec_let<'input>(tokens: &mut Lexer<'input>) -> Result<SpecBlockMember, Error> { let start_loc = tokens.start_loc(); tokens.advance()?; let name = parse_identifier(tokens)?; consume_token(tokens, Tok::Equal)?; let def = parse_exp(tokens)?; consume_token(tokens, Tok::Semicolon)?; Ok(spanned( tokens.file_name(), start_loc, tokens.previous_end_loc(), SpecBlockMember_::Let { name, def }, )) } // Parse a specification schema include. // SpecInclude = "include" <Exp> fn parse_spec_include<'input>(tokens: &mut Lexer<'input>) -> Result<SpecBlockMember, Error> { let start_loc = tokens.start_loc(); consume_identifier(tokens, "include")?; let exp = parse_exp(tokens)?; consume_token(tokens, Tok::Semicolon)?; Ok(spanned( tokens.file_name(), start_loc, tokens.previous_end_loc(), SpecBlockMember_::Include { exp }, )) } // Parse a specification schema apply. // SpecApply = "apply" <Exp> "to" Comma<SpecApplyPattern> // ( "except" Comma<SpecApplyPattern> )? ";" fn parse_spec_apply<'input>(tokens: &mut Lexer<'input>) -> Result<SpecBlockMember, Error> { let start_loc = tokens.start_loc(); consume_identifier(tokens, "apply")?; let exp = parse_exp(tokens)?; consume_identifier(tokens, "to")?; let parse_patterns = |tokens: &mut Lexer<'input>| { parse_list( tokens, |tokens| { if tokens.peek() == Tok::Comma { tokens.advance()?; Ok(true) } else { Ok(false) } }, parse_spec_apply_pattern, ) }; let patterns = parse_patterns(tokens)?; let exclusion_patterns = if tokens.peek() == Tok::IdentifierValue && tokens.content() == "except" { tokens.advance()?; parse_patterns(tokens)? } else { vec![] }; consume_token(tokens, Tok::Semicolon)?; Ok(spanned( tokens.file_name(), start_loc, tokens.previous_end_loc(), SpecBlockMember_::Apply { exp, patterns, exclusion_patterns, }, )) } // Parse a function pattern: // SpecApplyPattern = <SpecApplyFragment>+ <OptionalTypeArgs> fn parse_spec_apply_pattern<'input>(tokens: &mut Lexer<'input>) -> Result<SpecApplyPattern, Error> { let start_loc = tokens.start_loc(); let public_opt = consume_optional_token_with_loc(tokens, Tok::Public)?; let visibility = if let Some(loc) = public_opt { Some(FunctionVisibility::Public(loc)) } else if tokens.peek() == Tok::IdentifierValue && tokens.content() == "internal" { // Its not ideal right now that we do not have a loc here, but acceptable for what // we are doing with this in specs. tokens.advance()?; Some(FunctionVisibility::Internal) } else { None }; let mut last_end = tokens.start_loc() + tokens.content().len(); let name_pattern = parse_list( tokens, |tokens| { // We need name fragments followed by each other without space. So we do some // magic here similar as with `>>` based on token distance. let start_loc = tokens.start_loc(); let adjacent = last_end == start_loc; last_end = start_loc + tokens.content().len(); Ok(adjacent && [Tok::IdentifierValue, Tok::Star].contains(&tokens.peek())) }, parse_spec_apply_fragment, )?; let type_parameters = parse_optional_type_parameters(tokens)?; Ok(spanned( tokens.file_name(), start_loc, tokens.previous_end_loc(), SpecApplyPattern_ { visibility, name_pattern, type_parameters, }, )) } // Parse a name pattern fragment // SpecApplyFragment = <Identifier> | "*" fn parse_spec_apply_fragment<'input>( tokens: &mut Lexer<'input>, ) -> Result<SpecApplyFragment, Error> { let start_loc = tokens.start_loc(); let fragment = match tokens.peek() { Tok::IdentifierValue => SpecApplyFragment_::NamePart(parse_identifier(tokens)?), Tok::Star => { tokens.advance()?; SpecApplyFragment_::Wildcard } _ => return Err(unexpected_token_error(tokens, "a name fragment or `*`")), }; Ok(spanned( tokens.file_name(), start_loc, tokens.previous_end_loc(), fragment, )) } // Parse a specification pragma: // SpecPragma = "pragma" Comma<SpecPragmaProperty> ";" fn parse_spec_pragma<'input>(tokens: &mut Lexer<'input>) -> Result<SpecBlockMember, Error> { let start_loc = tokens.start_loc(); consume_identifier(tokens, "pragma")?; let properties = parse_comma_list_after_start( tokens, start_loc, Tok::IdentifierValue, Tok::Semicolon, parse_spec_property, "a pragma property", )?; Ok(spanned( tokens.file_name(), start_loc, tokens.previous_end_loc(), SpecBlockMember_::Pragma { properties }, )) } // Parse a specification pragma property: // SpecPragmaProperty = <Identifier> ( "=" Value )? fn parse_spec_property<'input>(tokens: &mut Lexer<'input>) -> Result<PragmaProperty, Error> { let start_loc = tokens.start_loc(); let name = parse_identifier(tokens)?; let value = if tokens.peek() == Tok::Equal { tokens.advance()?; match tokens.peek() { Tok::True | Tok::False | Tok::U8Value | Tok::U64Value | Tok::U128Value | Tok::ByteStringValue | Tok::AddressValue => Some(parse_value(tokens)?), Tok::NumValue => { let i = parse_num(tokens)?; Some(spanned( tokens.file_name(), start_loc, tokens.previous_end_loc(), Value_::U128(i), )) } _ => return Err(unexpected_token_error(tokens, "a value")), } } else { None }; Ok(spanned( tokens.file_name(), start_loc, tokens.previous_end_loc(), PragmaProperty_ { name, value }, )) } //************************************************************************************************** // File //************************************************************************************************** // Parse a file: // File = // (<AddressBlock> | <Module> | <Script>)* fn parse_file<'input>(tokens: &mut Lexer<'input>) -> Result<Vec<Definition>, Error> { let mut defs = vec![]; while tokens.peek() != Tok::EOF { defs.push(match tokens.peek() { Tok::Module => Definition::Module(parse_module(tokens)?), Tok::Script => Definition::Script(parse_script(tokens)?), _ => { let (loc, addr, modules) = parse_address_block(tokens)?; Definition::Address(loc, addr, modules) } }) } Ok(defs) } /// Parse the `input` string as a file of Move source code and return the /// result as either a pair of FileDefinition and doc comments or some Errors. The `file` name /// is used to identify source locations in error messages. pub fn parse_file_string( file: &'static str, input: &str, comment_map: BTreeMap<Span, String>, ) -> Result<(Vec<Definition>, BTreeMap<ByteIndex, String>), Errors> { let mut tokens = Lexer::new(input, file, comment_map); match tokens.advance() { Err(err) => Err(vec![err]), Ok(..) => Ok(()), }?; match parse_file(&mut tokens) { Err(err) => Err(vec![err]), Ok(def) => { let doc_comments = tokens.check_and_get_doc_comments()?; Ok((def, doc_comments)) } } }
33.876991
100
0.529323
0104b3ea34e038d032b7b9c296d4b6c7c5767c0a
12,935
use anyhow::Result; use crate::Client; pub struct Contacts { pub client: Client, } impl Contacts { #[doc(hidden)] pub fn new(client: Client) -> Self { Contacts { client } } /** * Search company contacts. * * This function performs a `GET` to the `/contacts` endpoint. * * A user under an organization's Zoom account has internal users listed under Company Contacts in the Zoom Client. Use this API to search users that are in the company contacts of a Zoom account. Using the `search_key` query parameter, provide either first name, last name or the email address of the user that you would like to search for. Optionally, set `query_presence_status` to `true` in order to include the presence status of a contact. <br><br> * * **Scopes:** `contact:read:admin`, `contact:read`<br> * * **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Medium` * * **Parameters:** * * * `search_key: &str` -- Provide the keyword - either first name, last name or email of the contact whom you have to search for. * * `query_presence_status: &str` -- Set `query_presence_status` to `true` in order to include the presence status of a contact in the response. * * `page_size: i64` -- The number of records to be returned with a single API call. * * `next_page_token: &str` -- The next page token is used to paginate through large result sets. A next page token will be returned whenever the set of available results exceeds the current page size. The expiration period for this token is 15 minutes. */ pub async fn search_company( &self, search_key: &str, query_presence_status: &str, page_size: i64, next_page_token: &str, ) -> Result<Vec<crate::types::Contacts>> { let mut query_args: Vec<(String, String)> = Default::default(); if !next_page_token.is_empty() { query_args.push(("next_page_token".to_string(), next_page_token.to_string())); } if page_size > 0 { query_args.push(("page_size".to_string(), page_size.to_string())); } if !query_presence_status.is_empty() { query_args.push(( "query_presence_status".to_string(), query_presence_status.to_string(), )); } if !search_key.is_empty() { query_args.push(("search_key".to_string(), search_key.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/contacts?{}", query_); let resp: crate::types::SearchCompanyContactsResponse = self.client.get(&url, None).await?; // Return our response data. Ok(resp.contacts) } /** * Search company contacts. * * This function performs a `GET` to the `/contacts` endpoint. * * As opposed to `search_company`, this function returns all the pages of the request at once. * * A user under an organization's Zoom account has internal users listed under Company Contacts in the Zoom Client. Use this API to search users that are in the company contacts of a Zoom account. Using the `search_key` query parameter, provide either first name, last name or the email address of the user that you would like to search for. Optionally, set `query_presence_status` to `true` in order to include the presence status of a contact. <br><br> * * **Scopes:** `contact:read:admin`, `contact:read`<br> * * **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Medium` */ pub async fn get_all_search_company( &self, search_key: &str, query_presence_status: &str, ) -> Result<Vec<crate::types::Contacts>> { let mut query_args: Vec<(String, String)> = Default::default(); if !query_presence_status.is_empty() { query_args.push(( "query_presence_status".to_string(), query_presence_status.to_string(), )); } if !search_key.is_empty() { query_args.push(("search_key".to_string(), search_key.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/contacts?{}", query_); let mut resp: crate::types::SearchCompanyContactsResponse = self.client.get(&url, None).await?; let mut contacts = resp.contacts; let mut page = resp.next_page_token; // Paginate if we should. while !page.is_empty() { // Check if we already have URL params and need to concat the token. if !url.contains('?') { resp = self .client .get(&format!("{}?next_page_token={}", url, page), None) .await?; } else { resp = self .client .get(&format!("{}&next_page_token={}", url, page), None) .await?; } contacts.append(&mut resp.contacts); if !resp.next_page_token.is_empty() && resp.next_page_token != page { page = resp.next_page_token.to_string(); } else { page = "".to_string(); } } // Return our response data. Ok(contacts) } /** * List user's contacts. * * This function performs a `GET` to the `/chat/users/me/contacts` endpoint. * * A user under an organization’s Zoom account has internal users listed under Company Contacts in the Zoom Client. A Zoom user can also add another Zoom user as a [contact](https://support.zoom.us/hc/en-us/articles/115004055706-Managing-Contacts). Call this API to list all the contacts of a Zoom user. Zoom contacts are categorized into "company contacts" and "external contacts". You must specify the contact type in the `type` query parameter. If you do not specify, by default, the type will be set as company contact. * * <p style="background-color:#e1f5fe; color:#01579b; padding:8px"> <b>Note: </b> This API only supports <b>user-managed</b> <a href="https://marketplace.zoom.us/docs/guides/getting-started/app-types/create-oauth-app">OAuth app</a>.</p><br> * * **Scope**: `chat_contact:read`<br> * * **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Medium` * * **Parameters:** * * * `type_: &str` -- The type of contact. The value can be one of the following: * `company`: Contacts from the user's organization. * `external`: External contacts. . * * `page_size: i64` -- The number of records returned with a single API call. * * `next_page_token: &str` -- The next page token is used to paginate through large result sets. A next page token will be returned whenever the set of available results exceeds the current page size. The expiration period for this token is 15 minutes. */ pub async fn get_user( &self, type_: &str, page_size: i64, next_page_token: &str, ) -> Result<Vec<crate::types::GetUserContactsResponse>> { let mut query_args: Vec<(String, String)> = Default::default(); if !next_page_token.is_empty() { query_args.push(("next_page_token".to_string(), next_page_token.to_string())); } if page_size > 0 { query_args.push(("page_size".to_string(), page_size.to_string())); } if !type_.is_empty() { query_args.push(("type".to_string(), type_.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/chat/users/me/contacts?{}", query_); let resp: crate::types::GetUserContactsResponseData = self.client.get(&url, None).await?; // Return our response data. Ok(resp.contacts) } /** * List user's contacts. * * This function performs a `GET` to the `/chat/users/me/contacts` endpoint. * * As opposed to `get_user`, this function returns all the pages of the request at once. * * A user under an organization’s Zoom account has internal users listed under Company Contacts in the Zoom Client. A Zoom user can also add another Zoom user as a [contact](https://support.zoom.us/hc/en-us/articles/115004055706-Managing-Contacts). Call this API to list all the contacts of a Zoom user. Zoom contacts are categorized into "company contacts" and "external contacts". You must specify the contact type in the `type` query parameter. If you do not specify, by default, the type will be set as company contact. * * <p style="background-color:#e1f5fe; color:#01579b; padding:8px"> <b>Note: </b> This API only supports <b>user-managed</b> <a href="https://marketplace.zoom.us/docs/guides/getting-started/app-types/create-oauth-app">OAuth app</a>.</p><br> * * **Scope**: `chat_contact:read`<br> * * **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Medium` */ pub async fn get_all_user( &self, type_: &str, ) -> Result<Vec<crate::types::GetUserContactsResponse>> { let mut query_args: Vec<(String, String)> = Default::default(); if !type_.is_empty() { query_args.push(("type".to_string(), type_.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!("/chat/users/me/contacts?{}", query_); let mut resp: crate::types::GetUserContactsResponseData = self.client.get(&url, None).await?; let mut contacts = resp.contacts; let mut page = resp.next_page_token; // Paginate if we should. while !page.is_empty() { // Check if we already have URL params and need to concat the token. if !url.contains('?') { resp = self .client .get(&format!("{}?next_page_token={}", url, page), None) .await?; } else { resp = self .client .get(&format!("{}&next_page_token={}", url, page), None) .await?; } contacts.append(&mut resp.contacts); if !resp.next_page_token.is_empty() && resp.next_page_token != page { page = resp.next_page_token.to_string(); } else { page = "".to_string(); } } // Return our response data. Ok(contacts) } /** * Get user's contact details. * * This function performs a `GET` to the `/chat/users/me/contacts/{contactId}` endpoint. * * A user under an organization’s Zoom account has internal users listed under Company Contacts in the Zoom Client. A Zoom user can also add another Zoom user as a [contact](https://support.zoom.us/hc/en-us/articles/115004055706-Managing-Contacts). Call this API to get information on a specific contact of the Zoom user. * * <p style="background-color:#e1f5fe; color:#01579b; padding:8px"> <b>Note: </b>This API only supports <b>user-managed</b> <a href="https://marketplace.zoom.us/docs/guides/getting-started/app-types/create-oauth-app">OAuth app</a>.</p><br> * * **Scope**: `chat_contact:read`<br> * * **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Medium` * * **Parameters:** * * * `contact_id: &str` -- The user's contact Id or email address. The contact can be either a company contact or an external contact. * * `query_presence_status: bool` -- Enable/disable the option for a sub account to use shared [Virtual Room Connector(s)](https://support.zoom.us/hc/en-us/articles/202134758-Getting-Started-With-Virtual-Room-Connector) that are set up by the master account. Virtual Room Connectors can only be used by On-prem users. */ pub async fn get_user_contacts( &self, contact_id: &str, query_presence_status: bool, ) -> Result<crate::types::GetUserContactResponse> { let mut query_args: Vec<(String, String)> = Default::default(); if query_presence_status { query_args.push(( "query_presence_status".to_string(), query_presence_status.to_string(), )); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!( "/chat/users/me/contacts/{}?{}", crate::progenitor_support::encode_path(&contact_id.to_string()), query_ ); self.client.get(&url, None).await } }
46.865942
527
0.61639
ab03aa58d41513c7543e8a477f171fb712f295e8
3,478
/* raylib-rs lib.rs - Main library code (the safe layer) Copyright (c) 2018-2019 Paul Clement (@deltaphc) This software is provided "as-is", without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ //! # raylib-rs //! //! `raylib` is a safe Rust binding to [Raylib](https://www.raylib.com/), a C library for enjoying games programming. //! //! To get started, take a look at the [`init_window`] function. This initializes Raylib and shows a window, and returns a [`RaylibHandle`]. This handle is very important, because it is the way in which one accesses the vast majority of Raylib's functionality. This means that it must not go out of scope until the game is ready to exit. You will also recieve a !Send and !Sync [`RaylibThread`] required for thread local functions. //! //! For more control over the game window, the [`init`] function will return a [`RaylibBuilder`] which allows for tweaking various settings such as VSync, anti-aliasing, fullscreen, and so on. Calling [`RaylibBuilder::build`] will then provide a [`RaylibHandle`]. //! //! Some useful constants can be found in the [`consts`] module, which is also re-exported in the [`prelude`] module. In most cases you will probably want to `use raylib::prelude::*;` to make your experience more smooth. //! //! [`init_window`]: fn.init_window.html //! [`init`]: fn.init.html //! [`RaylibHandle`]: struct.RaylibHandle.html //! [`RaylibThread`]: struct.RaylibThread.html //! [`RaylibBuilder`]: struct.RaylibBuilder.html //! [`RaylibBuilder::build`]: struct.RaylibBuilder.html#method.build //! [`consts`]: consts/index.html //! [`prelude`]: prelude/index.html //! //! # Examples //! //! The classic "Hello, world": //! //! ``` //! use raylib::prelude::*; //! //! fn main() { //! let (mut rl, thread) = raylib::init() //! .size(640, 480) //! .title("Hello, World") //! .build(); //! //! while !rl.window_should_close() { //! let mut d = rl.begin_drawing(&thread); //! //! d.clear_background(Color::WHITE); //! d.draw_text("Hello, world!", 12, 12, 20, Color::BLACK); //! } //! } //! ``` #![cfg_attr(feature = "nightly", feature(optin_builtin_traits))] #![allow(dead_code)] pub mod consts; pub mod core; pub mod ease; pub mod prelude; pub mod rgui; /// The raw, unsafe FFI binding, in case you need that escape hatch or the safe layer doesn't provide something you need. pub mod ffi { pub use raylib_sys::*; } pub use crate::core::collision::*; pub use crate::core::file::*; pub use crate::core::logging::*; pub use crate::core::misc::{get_random_value, open_url}; pub use crate::core::*; // Re-exports #[cfg(feature = "nalgebra_interop")] pub use nalgebra as na; #[cfg(feature = "with_serde")] pub use serde;
42.938272
431
0.696952
4bdc770657e13f107599649f094c9d66cded9d6c
8,838
// 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. use std::any::Any; use std::cell::RefCell; use std::rc::Rc; use differential_dataflow::operators::arrange::ArrangeByKey; use differential_dataflow::trace::cursor::Cursor; use differential_dataflow::trace::BatchReader; use differential_dataflow::Collection; use timely::dataflow::channels::pact::Pipeline; use timely::dataflow::operators::Operator; use timely::dataflow::Scope; use timely::progress::frontier::AntichainRef; use timely::progress::timestamp::Timestamp as TimelyTimestamp; use timely::progress::Antichain; use timely::PartialOrder; use dataflow_types::{SinkAsOf, SinkDesc, TailResponse, TailSinkConnector}; use expr::GlobalId; use repr::{Diff, Row, Timestamp}; use crate::render::sinks::SinkRender; use crate::render::RenderState; use super::SinkBaseMetrics; impl<G> SinkRender<G> for TailSinkConnector where G: Scope<Timestamp = Timestamp>, { fn uses_keys(&self) -> bool { false } fn get_key_indices(&self) -> Option<&[usize]> { None } fn get_relation_key_indices(&self) -> Option<&[usize]> { None } fn render_continuous_sink( &self, render_state: &mut RenderState, sink: &SinkDesc, sink_id: GlobalId, sinked_collection: Collection<G, (Option<Row>, Option<Row>), Diff>, _metrics: &SinkBaseMetrics, ) -> Option<Box<dyn Any>> where G: Scope<Timestamp = Timestamp>, { tail( sinked_collection, sink_id, render_state.tail_response_buffer.clone(), sink.as_of.clone(), ); // no sink token None } } fn tail<G>( sinked_collection: Collection<G, (Option<Row>, Option<Row>), Diff>, sink_id: GlobalId, tail_response_buffer: Rc<RefCell<Vec<(GlobalId, TailResponse)>>>, as_of: SinkAsOf, ) where G: Scope<Timestamp = Timestamp>, { // `active_worker` indicates the index of the worker that receives all data. // This should line up with the exchange just below, but we test in the implementation // just to be certain. let scope = sinked_collection.scope(); use differential_dataflow::Hashable; let active_worker = (sink_id.hashed() as usize) % scope.peers() == scope.index(); // make sure all data is routed to one worker by keying on the sink id let batches = sinked_collection .map(move |(k, v)| { assert!(k.is_none(), "tail does not support keys"); let v = v.expect("tail must have values"); (sink_id, v) }) .arrange_by_key() .stream; // Initialize to the minimal input frontier. let mut input_frontier = Antichain::from_elem(<G::Timestamp as TimelyTimestamp>::minimum()); // An encapsulation of the Tail response protocol. // Used to send rows and eventually mark complete. // Set to `None` for instances that should not produce output. let mut tail_protocol = if active_worker { Some(TailProtocol { sink_id, tail_response_buffer: Some(tail_response_buffer), }) } else { None }; batches.sink(Pipeline, &format!("tail-{}", sink_id), move |input| { input.for_each(|_, batches| { let mut results = vec![]; for batch in batches.iter() { let mut cursor = batch.cursor(); while cursor.key_valid(&batch) { while cursor.val_valid(&batch) { let row = cursor.val(&batch); cursor.map_times(&batch, |time, diff| { let diff = *diff; let should_emit = if as_of.strict { as_of.frontier.less_than(time) } else { as_of.frontier.less_equal(time) }; if should_emit { results.push((row.clone(), *time, diff)); } }); cursor.step_val(&batch); } cursor.step_key(&batch); } } // Emit data if configured, otherwise it is an error to have data to send. if let Some(tail_protocol) = &mut tail_protocol { tail_protocol.send_rows(results); } else { assert!( results.is_empty(), "Observed data at inactive TAIL instance" ); } if let Some(batch) = batches.last() { let progress = update_progress(&mut input_frontier, batch.desc.upper().borrow()); if let (Some(tail_protocol), Some(progress)) = (&mut tail_protocol, progress) { tail_protocol.send_progress(progress); } } }); let progress = update_progress(&mut input_frontier, input.frontier().frontier()); // Only emit updates if this operator/worker received actual data for emission. if let (Some(tail_protocol), Some(progress)) = (&mut tail_protocol, progress) { tail_protocol.send_progress(progress); } // If the frontier is empty the tailing is complete. We should say so! if input.frontier().frontier().is_empty() { if let Some(tail_protocol) = tail_protocol.take() { tail_protocol.complete(); } else { // Not an error to notice the end of the stream at non-emitters, // or to notice it a second time at a previous emitter. } } }) } /// A type that guides the transmission of rows back to the coordinator. /// /// A protocol instance may `send` rows indefinitely, and is consumed by `complete`, /// which is used only to indicate the end of a stream. The `Drop` implementation /// otherwise sends an indication that the protocol has finished without completion. struct TailProtocol { pub sink_id: GlobalId, pub tail_response_buffer: Option<Rc<RefCell<Vec<(GlobalId, TailResponse)>>>>, } impl TailProtocol { /// Send the current upper frontier of the tail. /// /// Does nothing if `self.complete()` has been called. fn send_progress(&mut self, upper: Antichain<Timestamp>) { if let Some(buffer) = &mut self.tail_response_buffer { buffer .borrow_mut() .push((self.sink_id, TailResponse::Progress(upper))); } } /// Send further rows as responses. /// /// Does nothing if `self.complete()` has been called. fn send_rows(&mut self, rows: Vec<(Row, Timestamp, Diff)>) { if let Some(buffer) = &mut self.tail_response_buffer { buffer .borrow_mut() .push((self.sink_id, TailResponse::Rows(rows))); } } /// Completes the channel, preventing further transmissions. fn complete(mut self) { if let Some(buffer) = &mut self.tail_response_buffer { buffer .borrow_mut() .push((self.sink_id, TailResponse::Complete)); // Set to `None` to avoid `TailResponse::Dropped`. self.tail_response_buffer = None; } } } impl Drop for TailProtocol { fn drop(&mut self) { if let Some(buffer) = &mut self.tail_response_buffer { buffer .borrow_mut() .push((self.sink_id, TailResponse::Dropped)); self.tail_response_buffer = None; } } } // Checks if there is progress between `current_input_frontier` and // `new_input_frontier`. If yes, updates the `current_input_frontier` to // `new_input_frontier` and returns a [`Row`] that encodes this progress. If // there is no progress, returns [`None`]. fn update_progress( current_input_frontier: &mut Antichain<Timestamp>, new_input_frontier: AntichainRef<Timestamp>, ) -> Option<Antichain<Timestamp>> { // Test to see if strict progress has occurred. This is true if the new // frontier is not less or equal to the old frontier. let progress = !PartialOrder::less_equal(&new_input_frontier, &current_input_frontier.borrow()); if progress { current_input_frontier.clear(); current_input_frontier.extend(new_input_frontier.iter().cloned()); Some(new_input_frontier.to_owned()) } else { None } }
35.211155
100
0.598099
de81993daa678bd34f79be55b01006e18651ade9
10,218
use crate::prelude::*; use nu_engine::basic_evaluation_context; use nu_engine::whole_stream_command; use std::error::Error; pub fn create_default_context(interactive: bool) -> Result<EvaluationContext, Box<dyn Error>> { let context = basic_evaluation_context()?; { use crate::commands::*; context.add_commands(vec![ // Fundamentals whole_stream_command(NuPlugin), whole_stream_command(Let), whole_stream_command(LetEnv), whole_stream_command(Def), whole_stream_command(Source), // System/file operations whole_stream_command(Exec), whole_stream_command(Pwd), whole_stream_command(Ls), whole_stream_command(Du), whole_stream_command(Cd), whole_stream_command(Remove), whole_stream_command(Open), whole_stream_command(Config), whole_stream_command(ConfigGet), whole_stream_command(ConfigSet), whole_stream_command(ConfigSetInto), whole_stream_command(ConfigClear), whole_stream_command(ConfigLoad), whole_stream_command(ConfigRemove), whole_stream_command(ConfigPath), whole_stream_command(Help), whole_stream_command(History), whole_stream_command(Save), whole_stream_command(Touch), whole_stream_command(Cpy), whole_stream_command(Date), whole_stream_command(DateListTimeZone), whole_stream_command(DateNow), whole_stream_command(DateToTable), whole_stream_command(DateToTimeZone), whole_stream_command(DateFormat), whole_stream_command(Cal), whole_stream_command(Mkdir), whole_stream_command(Mv), whole_stream_command(Kill), whole_stream_command(Version), whole_stream_command(Clear), whole_stream_command(Describe), whole_stream_command(Which), whole_stream_command(Debug), whole_stream_command(WithEnv), whole_stream_command(Do), whole_stream_command(Sleep), // Statistics whole_stream_command(Size), whole_stream_command(Count), whole_stream_command(Benchmark), // Metadata whole_stream_command(Tags), // Shells whole_stream_command(Next), whole_stream_command(Previous), whole_stream_command(Shells), whole_stream_command(Enter), whole_stream_command(Exit), // Viz whole_stream_command(Chart), // Viewers whole_stream_command(Autoview), whole_stream_command(Table), // Text manipulation whole_stream_command(Hash), whole_stream_command(HashBase64), whole_stream_command(Split), whole_stream_command(SplitColumn), whole_stream_command(SplitRow), whole_stream_command(SplitChars), whole_stream_command(Lines), whole_stream_command(Echo), whole_stream_command(Parse), whole_stream_command(Str), whole_stream_command(StrToDecimal), whole_stream_command(StrToInteger), whole_stream_command(StrDowncase), whole_stream_command(StrUpcase), whole_stream_command(StrCapitalize), whole_stream_command(StrFindReplace), whole_stream_command(StrFrom), whole_stream_command(StrSubstring), whole_stream_command(StrToDatetime), whole_stream_command(StrContains), whole_stream_command(StrIndexOf), whole_stream_command(StrTrim), whole_stream_command(StrTrimLeft), whole_stream_command(StrTrimRight), whole_stream_command(StrStartsWith), whole_stream_command(StrEndsWith), whole_stream_command(StrCollect), whole_stream_command(StrLength), whole_stream_command(StrLPad), whole_stream_command(StrReverse), whole_stream_command(StrRPad), whole_stream_command(StrCamelCase), whole_stream_command(StrPascalCase), whole_stream_command(StrKebabCase), whole_stream_command(StrSnakeCase), whole_stream_command(StrScreamingSnakeCase), whole_stream_command(BuildString), whole_stream_command(Ansi), whole_stream_command(Char), // Column manipulation whole_stream_command(Move), whole_stream_command(Reject), whole_stream_command(Select), whole_stream_command(Get), whole_stream_command(Update), whole_stream_command(Insert), whole_stream_command(IntoInt), whole_stream_command(SplitBy), // Row manipulation whole_stream_command(Reverse), whole_stream_command(Append), whole_stream_command(Prepend), whole_stream_command(SortBy), whole_stream_command(GroupBy), whole_stream_command(GroupByDate), whole_stream_command(First), whole_stream_command(Last), whole_stream_command(Every), whole_stream_command(Nth), whole_stream_command(Drop), whole_stream_command(Format), whole_stream_command(FileSize), whole_stream_command(Where), whole_stream_command(If), whole_stream_command(Compact), whole_stream_command(Default), whole_stream_command(Skip), whole_stream_command(SkipUntil), whole_stream_command(SkipWhile), whole_stream_command(Keep), whole_stream_command(KeepUntil), whole_stream_command(KeepWhile), whole_stream_command(Range), whole_stream_command(Rename), whole_stream_command(Uniq), whole_stream_command(Each), whole_stream_command(EachGroup), whole_stream_command(EachWindow), whole_stream_command(Empty), // Table manipulation whole_stream_command(Flatten), whole_stream_command(Move), whole_stream_command(Merge), whole_stream_command(Shuffle), whole_stream_command(Wrap), whole_stream_command(Pivot), whole_stream_command(Headers), whole_stream_command(Reduce), // Data processing whole_stream_command(Histogram), whole_stream_command(Autoenv), whole_stream_command(AutoenvTrust), whole_stream_command(AutoenvUnTrust), whole_stream_command(Math), whole_stream_command(MathAbs), whole_stream_command(MathAverage), whole_stream_command(MathEval), whole_stream_command(MathMedian), whole_stream_command(MathMinimum), whole_stream_command(MathMode), whole_stream_command(MathMaximum), whole_stream_command(MathStddev), whole_stream_command(MathSummation), whole_stream_command(MathVariance), whole_stream_command(MathProduct), whole_stream_command(MathRound), whole_stream_command(MathFloor), whole_stream_command(MathCeil), // File format output whole_stream_command(To), whole_stream_command(ToCSV), whole_stream_command(ToHTML), whole_stream_command(ToJSON), whole_stream_command(ToMarkdown), whole_stream_command(ToTOML), whole_stream_command(ToTSV), whole_stream_command(ToURL), whole_stream_command(ToYAML), whole_stream_command(ToXML), // File format input whole_stream_command(From), whole_stream_command(FromCSV), whole_stream_command(FromEML), whole_stream_command(FromTSV), whole_stream_command(FromSSV), whole_stream_command(FromINI), whole_stream_command(FromJSON), whole_stream_command(FromODS), whole_stream_command(FromTOML), whole_stream_command(FromURL), whole_stream_command(FromXLSX), whole_stream_command(FromXML), whole_stream_command(FromYAML), whole_stream_command(FromYML), whole_stream_command(FromIcs), whole_stream_command(FromVcf), // "Private" commands (not intended to be accessed directly) whole_stream_command(RunExternalCommand { interactive }), // Random value generation whole_stream_command(Random), whole_stream_command(RandomBool), whole_stream_command(RandomDice), #[cfg(feature = "uuid_crate")] whole_stream_command(RandomUUID), whole_stream_command(RandomInteger), whole_stream_command(RandomDecimal), whole_stream_command(RandomChars), // Path whole_stream_command(PathBasename), whole_stream_command(PathCommand), whole_stream_command(PathDirname), whole_stream_command(PathExists), whole_stream_command(PathExpand), whole_stream_command(PathExtension), whole_stream_command(PathFilestem), whole_stream_command(PathType), // Url whole_stream_command(UrlCommand), whole_stream_command(UrlScheme), whole_stream_command(UrlPath), whole_stream_command(UrlHost), whole_stream_command(UrlQuery), whole_stream_command(Seq), whole_stream_command(SeqDates), ]); #[cfg(feature = "clipboard-cli")] { context.add_commands(vec![whole_stream_command(crate::commands::clip::Clip)]); } } Ok(context) }
40.872
95
0.622137
3aeaf279d735903dff9fcb3a9656beb7a1cabdc6
22,752
// 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. use { crate::{ builtin::runner::BuiltinRunnerFactory, model::{ binding::Binder, component::{ BindReason, ComponentInstance, ComponentManagerInstance, WeakComponentInstance, }, environment::{DebugRegistry, Environment, RunnerRegistry}, error::ModelError, policy::ScopedPolicyChecker, resolver::{ResolvedComponent, Resolver, ResolverError, ResolverRegistry}, runner::{Runner, RunnerError}, }, }, anyhow::format_err, async_trait::async_trait, cm_rust::{ComponentDecl, ExposeDecl, UseDecl}, directory_broker::RoutingFn, fidl::endpoints::RequestStream, fidl::{endpoints::ServerEnd, epitaph::ChannelEpitaphExt}, fidl_fidl_examples_echo::{EchoMarker, EchoRequest, EchoRequestStream}, fidl_fuchsia_component_runner as fcrunner, fidl_fuchsia_diagnostics_types::{ ComponentDiagnostics, ComponentTasks, Task as DiagnosticsTask, }, fidl_fuchsia_io::{DirectoryMarker, NodeMarker}, fidl_fuchsia_sys2 as fsys, fuchsia_async as fasync, fuchsia_zircon::{self as zx, AsHandleRef, HandleBased, Koid}, futures::{ channel::oneshot, future::{AbortHandle, Abortable}, lock::Mutex, prelude::*, }, log::warn, moniker::AbsoluteMoniker, std::{ boxed::Box, collections::{HashMap, HashSet}, convert::TryFrom, mem, sync::{Arc, Mutex as SyncMutex, Weak}, }, vfs::{ directory::entry::DirectoryEntry, execution_scope::ExecutionScope, file::vmo::asynchronous::read_only_static, path::Path, pseudo_directory, }, }; /// Creates a routing function factory for `UseDecl` that does the following: /// - Redirects all directory capabilities to a directory with the file "hello". /// - Redirects all service capabilities to the echo service. pub fn proxy_use_routing_factory() -> impl Fn(WeakComponentInstance, UseDecl) -> RoutingFn { move |_component: WeakComponentInstance, use_decl: UseDecl| { new_proxy_routing_fn(use_decl.into()) } } /// Creates a routing function factory for `ExposeDecl` that does the following: /// - Redirects all directory capabilities to a directory with the file "hello". /// - Redirects all service capabilities to the echo service. pub fn proxy_expose_routing_factory() -> impl Fn(WeakComponentInstance, ExposeDecl) -> RoutingFn { move |_component: WeakComponentInstance, expose_decl: ExposeDecl| { new_proxy_routing_fn(expose_decl.into()) } } enum CapabilityType { Service, Protocol, Directory, Storage, Runner, Resolver, Event, EventStream, } impl From<UseDecl> for CapabilityType { fn from(use_: UseDecl) -> Self { match use_ { UseDecl::Service(_) => CapabilityType::Service, UseDecl::Protocol(_) => CapabilityType::Protocol, UseDecl::Directory(_) => CapabilityType::Directory, UseDecl::Storage(_) => CapabilityType::Storage, UseDecl::Event(_) => CapabilityType::Event, UseDecl::EventStream(_) => CapabilityType::EventStream, } } } impl From<ExposeDecl> for CapabilityType { fn from(expose: ExposeDecl) -> Self { match expose { ExposeDecl::Service(_) => CapabilityType::Service, ExposeDecl::Protocol(_) => CapabilityType::Protocol, ExposeDecl::Directory(_) => CapabilityType::Directory, ExposeDecl::Runner(_) => CapabilityType::Runner, ExposeDecl::Resolver(_) => CapabilityType::Resolver, } } } fn new_proxy_routing_fn(ty: CapabilityType) -> RoutingFn { Box::new( move |flags: u32, mode: u32, relative_path: String, server_end: ServerEnd<NodeMarker>| { match ty { CapabilityType::Protocol => { fasync::Task::spawn(async move { let server_end: ServerEnd<EchoMarker> = ServerEnd::new(server_end.into_channel()); let mut stream: EchoRequestStream = server_end.into_stream().unwrap(); while let Some(EchoRequest::EchoString { value, responder }) = stream.try_next().await.unwrap() { responder.send(value.as_ref().map(|s| &**s)).unwrap(); } }) .detach(); } CapabilityType::Directory | CapabilityType::Storage => { let sub_dir = pseudo_directory!( "hello" => read_only_static(b"friend"), ); let path = Path::validate_and_split(relative_path).expect("Failed to split path"); sub_dir.open(ExecutionScope::new(), flags, mode, path, server_end); } CapabilityType::Service => panic!("service capability unsupported"), CapabilityType::Runner => panic!("runner capability unsupported"), CapabilityType::Resolver => panic!("resolver capability unsupported"), CapabilityType::Event => panic!("event capability unsupported"), CapabilityType::EventStream => panic!("event stream capability unsupported"), } }, ) } pub struct MockResolver { components: HashMap<String, ComponentDecl>, } impl MockResolver { pub fn new() -> Self { MockResolver { components: HashMap::new() } } async fn resolve_async( &self, component_url: String, ) -> Result<ResolvedComponent, ResolverError> { const NAME_PREFIX: &str = "test:///"; debug_assert!(component_url.starts_with(NAME_PREFIX), "invalid component url"); let (_, name) = component_url.split_at(NAME_PREFIX.len()); let decl = self .components .get(name) .ok_or(ResolverError::manifest_not_found(format_err!("not in the hashmap")))?; let fsys_decl = fsys::ComponentDecl::try_from(decl.clone()).expect("decl failed conversion"); Ok(ResolvedComponent { resolved_url: format!("test:///{}_resolved", name), decl: fsys_decl, package: None, }) } pub fn add_component(&mut self, name: &str, component: ComponentDecl) { self.components.insert(name.to_string(), component); } } #[async_trait] impl Resolver for MockResolver { async fn resolve(&self, component_url: &str) -> Result<ResolvedComponent, ResolverError> { self.resolve_async(component_url.to_string()).await } } pub type HostFn = Box<dyn Fn(ServerEnd<DirectoryMarker>) + Send + Sync>; pub type ManagedNamespace = Mutex<Vec<fcrunner::ComponentNamespaceEntry>>; struct MockRunnerInner { /// List of URLs started by this runner instance. urls_run: Vec<String>, /// Vector of waiters that wish to be notified when a new URL is run (used by `wait_for_urls`). url_waiters: Vec<futures::channel::oneshot::Sender<()>>, /// Namespace for each component, mapping resolved URL to the component's namespace. namespaces: HashMap<String, Arc<Mutex<Vec<fcrunner::ComponentNamespaceEntry>>>>, /// Functions for serving the `outgoing` and `runtime` directories /// of a given compoment. When a component is started, these /// functions will be called with the server end of the directories. outgoing_host_fns: HashMap<String, Arc<HostFn>>, runtime_host_fns: HashMap<String, Arc<HostFn>>, /// Set of URLs that the MockRunner will fail the `start` call for. failing_urls: HashSet<String>, /// Map from the `Koid` of `Channel` owned by a `ComponentController` to /// the messages received by that controller. runner_requests: Arc<Mutex<HashMap<Koid, Vec<ControlMessage>>>>, controllers: HashMap<Koid, AbortHandle>, last_checker: Option<ScopedPolicyChecker>, } pub struct MockRunner { // The internal runner state. // // Inner state is guarded by a std::sync::Mutex to avoid helper // functions needing "async" (and propagating to callers). // std::sync::MutexGuard doesn't have the "Send" trait, so the // compiler will prevent us calling ".await" while holding the lock. inner: SyncMutex<MockRunnerInner>, } impl MockRunner { pub fn new() -> Self { MockRunner { inner: SyncMutex::new(MockRunnerInner { urls_run: vec![], url_waiters: vec![], namespaces: HashMap::new(), outgoing_host_fns: HashMap::new(), runtime_host_fns: HashMap::new(), failing_urls: HashSet::new(), runner_requests: Arc::new(Mutex::new(HashMap::new())), controllers: HashMap::new(), last_checker: None, }), } } /// Cause the URL `url` to return an error when started. pub fn add_failing_url(&self, url: &str) { self.inner.lock().unwrap().failing_urls.insert(url.to_string()); } /// Cause the component `name` to return an error when started. pub fn cause_failure(&self, name: &str) { self.add_failing_url(&format!("test:///{}_resolved", name)) } /// Register `function` to serve the outgoing directory of component `name` pub fn add_host_fn(&self, name: &str, function: HostFn) { self.inner.lock().unwrap().outgoing_host_fns.insert(name.to_string(), Arc::new(function)); } /// Register `function` to serve the runtime directory of component `name` pub fn add_runtime_host_fn(&self, name: &str, function: HostFn) { self.inner.lock().unwrap().runtime_host_fns.insert(name.to_string(), Arc::new(function)); } /// Get the input namespace for component `name`. pub fn get_namespace(&self, name: &str) -> Option<Arc<ManagedNamespace>> { self.inner.lock().unwrap().namespaces.get(name).map(Arc::clone) } pub fn get_request_map(&self) -> Arc<Mutex<HashMap<Koid, Vec<ControlMessage>>>> { self.inner.lock().unwrap().runner_requests.clone() } /// Returns a future that completes when `expected_url` is launched by the runner. pub async fn wait_for_url(&self, expected_url: &str) { self.wait_for_urls(&[expected_url]).await } /// Returns a future that completes when `expected_urls` were launched by the runner, in any /// order. pub async fn wait_for_urls(&self, expected_urls: &[&str]) { loop { let mut inner = self.inner.lock().unwrap(); let expected_urls: HashSet<&str> = expected_urls.iter().map(|s| *s).collect(); let urls_run: HashSet<&str> = inner.urls_run.iter().map(|s| s as &str).collect(); let (sender, receiver) = oneshot::channel(); if expected_urls.is_subset(&urls_run) { return; } else { inner.url_waiters.push(sender); } drop(inner); receiver.await.expect("failed to receive url notice") } } pub fn abort_controller(&self, koid: &Koid) { let state = self.inner.lock().unwrap(); let controller = state.controllers.get(koid).expect("koid was not available"); controller.abort(); } pub fn last_checker(&self) -> Option<ScopedPolicyChecker> { self.inner.lock().unwrap().last_checker.take() } } impl BuiltinRunnerFactory for MockRunner { fn get_scoped_runner(self: Arc<Self>, checker: ScopedPolicyChecker) -> Arc<dyn Runner> { { let mut state = self.inner.lock().unwrap(); state.last_checker = Some(checker); } self } } #[async_trait] impl Runner for MockRunner { async fn start( &self, start_info: fcrunner::ComponentStartInfo, server_end: ServerEnd<fcrunner::ComponentControllerMarker>, ) { let outgoing_host_fn; let runtime_host_fn; let runner_requests; let resolved_url = start_info.resolved_url.unwrap(); // The koid is the only unique piece of information we have about a // component start request. Two start requests for the same component // URL look identical to the Runner, the only difference being the // Channel passed to the Runner to use for the ComponentController // protocol. let channel_koid = server_end.as_handle_ref().basic_info().expect("basic info failed").koid; { let mut state = self.inner.lock().unwrap(); // Trigger a failure if previously requested. if state.failing_urls.contains(&resolved_url) { let status = RunnerError::component_launch_error( resolved_url.clone(), format_err!("launch error"), ) .as_zx_status(); server_end.into_channel().close_with_epitaph(status).unwrap(); return; } // Fetch host functions, which will provide the outgoing and runtime directories // for the component. // // If functions were not provided, then start_info.outgoing_dir will be // automatically closed once it goes out of scope at the end of this // function. outgoing_host_fn = state.outgoing_host_fns.get(&resolved_url).map(Arc::clone); runtime_host_fn = state.runtime_host_fns.get(&resolved_url).map(Arc::clone); runner_requests = state.runner_requests.clone(); // Create a namespace for the component. state .namespaces .insert(resolved_url.clone(), Arc::new(Mutex::new(start_info.ns.unwrap()))); let abort_handle = MockController::new(server_end, runner_requests, channel_koid).serve(); state.controllers.insert(channel_koid, abort_handle); // Start serving the outgoing/runtime directories. if let Some(outgoing_host_fn) = outgoing_host_fn { outgoing_host_fn(start_info.outgoing_dir.unwrap()); } if let Some(runtime_host_fn) = runtime_host_fn { runtime_host_fn(start_info.runtime_dir.unwrap()); } // Record that this URL has been started. state.urls_run.push(resolved_url.clone()); let url_waiters = mem::replace(&mut state.url_waiters, vec![]); for waiter in url_waiters { waiter.send(()).expect("failed to send url notice"); } } } } /// A fake `Binder` implementation that always returns `Ok(())` in a `BoxFuture`. pub struct FakeBinder { top_instance: Arc<ComponentManagerInstance>, } impl FakeBinder { pub fn new(top_instance: Arc<ComponentManagerInstance>) -> Arc<dyn Binder> { Arc::new(Self { top_instance }) } } #[async_trait] impl Binder for FakeBinder { async fn bind<'a>( &'a self, _abs_moniker: &'a AbsoluteMoniker, _reason: &'a BindReason, ) -> Result<Arc<ComponentInstance>, ModelError> { let resolver = ResolverRegistry::new(); let root_component_url = "test:///root".to_string(); Ok(ComponentInstance::new_root( Environment::new_root( &self.top_instance, RunnerRegistry::default(), resolver, DebugRegistry::default(), ), Weak::new(), Weak::new(), root_component_url, )) } } #[derive(Debug, PartialEq, Clone)] pub enum ControlMessage { Stop, Kill, } #[derive(Clone)] /// What the MockController should do when it receives a message. pub struct ControllerActionResponse { pub close_channel: bool, pub delay: Option<zx::Duration>, } pub struct MockController { pub messages: Arc<Mutex<HashMap<Koid, Vec<ControlMessage>>>>, request_stream: fcrunner::ComponentControllerRequestStream, koid: Koid, stop_resp: ControllerActionResponse, kill_resp: ControllerActionResponse, } impl MockController { /// Create a `MockController` that listens to the `server_end` and inserts /// `ControlMessage`'s into the Vec in the HashMap keyed under the provided /// `Koid`. When either a request to stop or kill a component is received /// the `MockController` will close the control channel immediately. pub fn new( server_end: ServerEnd<fcrunner::ComponentControllerMarker>, messages: Arc<Mutex<HashMap<Koid, Vec<ControlMessage>>>>, koid: Koid, ) -> MockController { Self::new_with_responses( server_end, messages, koid, ControllerActionResponse { close_channel: true, delay: None }, ControllerActionResponse { close_channel: true, delay: None }, ) } /// Create a MockController that listens to the `server_end` and inserts /// `ControlMessage`'s into the Vec in the HashMap keyed under the provided /// `Koid`. The `stop_response` controls the delay used before taking any /// action on the control channel when a request to stop is received. The /// `kill_respone` provides the same control when the a request to kill is /// received. pub fn new_with_responses( server_end: ServerEnd<fcrunner::ComponentControllerMarker>, messages: Arc<Mutex<HashMap<Koid, Vec<ControlMessage>>>>, koid: Koid, stop_response: ControllerActionResponse, kill_response: ControllerActionResponse, ) -> MockController { MockController { messages: messages, request_stream: server_end.into_stream().expect("stream conversion failed"), koid: koid, stop_resp: stop_response, kill_resp: kill_response, } } /// Spawn an async execution context which takes ownership of `server_end` /// and inserts `ControlMessage`s into `messages` based on events sent on /// the `ComponentController` channel. This simply spawns a future which /// awaits self.run(). pub fn serve(mut self) -> AbortHandle { // Listen to the ComponentController server end and record the messages // that arrive. Exit after the first one, as this is the contract we // have implemented so far. Exiting will cause our handle to the // channel to drop and close the channel. let (handle, registration) = AbortHandle::new_pair(); // Send default job for the sake of testing only. let job_dup = fuchsia_runtime::job_default() .duplicate_handle(zx::Rights::SAME_RIGHTS) .expect("duplicate default job"); self.request_stream .control_handle() .send_on_publish_diagnostics(ComponentDiagnostics { tasks: Some(ComponentTasks { component_task: Some(DiagnosticsTask::Job(job_dup)), ..ComponentTasks::EMPTY }), ..ComponentDiagnostics::EMPTY }) .unwrap_or_else(|e| { warn!("sending diagnostics failed: {:?}", e); }); let fut = Abortable::new( async move { self.messages.lock().await.insert(self.koid, Vec::new()); while let Ok(Some(request)) = self.request_stream.try_next().await { match request { fcrunner::ComponentControllerRequest::Stop { control_handle: c } => { self.messages .lock() .await .get_mut(&self.koid) .expect("component channel koid key missing from mock runner map") .push(ControlMessage::Stop); if let Some(delay) = self.stop_resp.delay { let delay_copy = delay.clone(); let close_channel = self.stop_resp.close_channel; fasync::Task::spawn(async move { fasync::Timer::new(fasync::Time::after(delay_copy)).await; if close_channel { c.shutdown_with_epitaph(zx::Status::OK); } }) .detach(); } else if self.stop_resp.close_channel { c.shutdown_with_epitaph(zx::Status::OK); break; } } fcrunner::ComponentControllerRequest::Kill { control_handle: c } => { self.messages .lock() .await .get_mut(&self.koid) .expect("component channel koid key missing from mock runner map") .push(ControlMessage::Kill); if let Some(delay) = self.kill_resp.delay { let delay_copy = delay.clone(); let close_channel = self.kill_resp.close_channel; fasync::Task::spawn(async move { fasync::Timer::new(fasync::Time::after(delay_copy)).await; if close_channel { c.shutdown_with_epitaph(zx::Status::OK); } }) .detach(); if self.kill_resp.close_channel { break; } } else if self.kill_resp.close_channel { c.shutdown_with_epitaph(zx::Status::OK); break; } } } } }, registration, ); fasync::Task::spawn(async move { let _ = fut.await; }) .detach(); handle } }
39.706806
100
0.581971
c113716ca5c74295339868d95bda27492dbcc0d3
39,913
// Copyright 2013 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. #![allow(dead_code)] // FFI wrappers use llvm; use llvm::{AtomicRmwBinOp, AtomicOrdering, SynchronizationScope, AsmDialect}; use llvm::{Opcode, IntPredicate, RealPredicate, False, OperandBundleDef}; use llvm::{ValueRef, BasicBlockRef, BuilderRef, ModuleRef}; use common::*; use machine::llalign_of_pref; use type_::Type; use value::Value; use libc::{c_uint, c_char}; use rustc::ty::{Ty, TyCtxt, TypeFoldable}; use rustc::session::Session; use type_of; use std::borrow::Cow; use std::ffi::CString; use std::ptr; use syntax_pos::Span; // All Builders must have an llfn associated with them #[must_use] pub struct Builder<'a, 'tcx: 'a> { pub llbuilder: BuilderRef, pub ccx: &'a CrateContext<'a, 'tcx>, } impl<'a, 'tcx> Drop for Builder<'a, 'tcx> { fn drop(&mut self) { unsafe { llvm::LLVMDisposeBuilder(self.llbuilder); } } } // This is a really awful way to get a zero-length c-string, but better (and a // lot more efficient) than doing str::as_c_str("", ...) every time. fn noname() -> *const c_char { static CNULL: c_char = 0; &CNULL } impl<'a, 'tcx> Builder<'a, 'tcx> { pub fn new_block<'b>(ccx: &'a CrateContext<'a, 'tcx>, llfn: ValueRef, name: &'b str) -> Self { let builder = Builder::with_ccx(ccx); let llbb = unsafe { let name = CString::new(name).unwrap(); llvm::LLVMAppendBasicBlockInContext( ccx.llcx(), llfn, name.as_ptr() ) }; builder.position_at_end(llbb); builder } pub fn with_ccx(ccx: &'a CrateContext<'a, 'tcx>) -> Self { // Create a fresh builder from the crate context. let llbuilder = unsafe { llvm::LLVMCreateBuilderInContext(ccx.llcx()) }; Builder { llbuilder: llbuilder, ccx: ccx, } } pub fn build_sibling_block<'b>(&self, name: &'b str) -> Builder<'a, 'tcx> { Builder::new_block(self.ccx, self.llfn(), name) } pub fn sess(&self) -> &Session { self.ccx.sess() } pub fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> { self.ccx.tcx() } pub fn llfn(&self) -> ValueRef { unsafe { llvm::LLVMGetBasicBlockParent(self.llbb()) } } pub fn llbb(&self) -> BasicBlockRef { unsafe { llvm::LLVMGetInsertBlock(self.llbuilder) } } fn count_insn(&self, category: &str) { if self.ccx.sess().trans_stats() { self.ccx.stats().n_llvm_insns.set(self.ccx.stats().n_llvm_insns.get() + 1); } if self.ccx.sess().count_llvm_insns() { let mut h = self.ccx.stats().llvm_insns.borrow_mut(); *h.entry(category.to_string()).or_insert(0) += 1; } } pub fn position_before(&self, insn: ValueRef) { unsafe { llvm::LLVMPositionBuilderBefore(self.llbuilder, insn); } } pub fn position_at_end(&self, llbb: BasicBlockRef) { unsafe { llvm::LLVMPositionBuilderAtEnd(self.llbuilder, llbb); } } pub fn position_at_start(&self, llbb: BasicBlockRef) { unsafe { llvm::LLVMRustPositionBuilderAtStart(self.llbuilder, llbb); } } pub fn ret_void(&self) { self.count_insn("retvoid"); unsafe { llvm::LLVMBuildRetVoid(self.llbuilder); } } pub fn ret(&self, v: ValueRef) { self.count_insn("ret"); unsafe { llvm::LLVMBuildRet(self.llbuilder, v); } } pub fn aggregate_ret(&self, ret_vals: &[ValueRef]) { unsafe { llvm::LLVMBuildAggregateRet(self.llbuilder, ret_vals.as_ptr(), ret_vals.len() as c_uint); } } pub fn br(&self, dest: BasicBlockRef) { self.count_insn("br"); unsafe { llvm::LLVMBuildBr(self.llbuilder, dest); } } pub fn cond_br(&self, cond: ValueRef, then_llbb: BasicBlockRef, else_llbb: BasicBlockRef) { self.count_insn("condbr"); unsafe { llvm::LLVMBuildCondBr(self.llbuilder, cond, then_llbb, else_llbb); } } pub fn switch(&self, v: ValueRef, else_llbb: BasicBlockRef, num_cases: usize) -> ValueRef { unsafe { llvm::LLVMBuildSwitch(self.llbuilder, v, else_llbb, num_cases as c_uint) } } pub fn indirect_br(&self, addr: ValueRef, num_dests: usize) { self.count_insn("indirectbr"); unsafe { llvm::LLVMBuildIndirectBr(self.llbuilder, addr, num_dests as c_uint); } } pub fn invoke(&self, llfn: ValueRef, args: &[ValueRef], then: BasicBlockRef, catch: BasicBlockRef, bundle: Option<&OperandBundleDef>) -> ValueRef { self.count_insn("invoke"); debug!("Invoke {:?} with args ({})", Value(llfn), args.iter() .map(|&v| format!("{:?}", Value(v))) .collect::<Vec<String>>() .join(", ")); let args = self.check_call("invoke", llfn, args); let bundle = bundle.as_ref().map(|b| b.raw()).unwrap_or(ptr::null_mut()); unsafe { llvm::LLVMRustBuildInvoke(self.llbuilder, llfn, args.as_ptr(), args.len() as c_uint, then, catch, bundle, noname()) } } pub fn unreachable(&self) { self.count_insn("unreachable"); unsafe { llvm::LLVMBuildUnreachable(self.llbuilder); } } /* Arithmetic */ pub fn add(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("add"); unsafe { llvm::LLVMBuildAdd(self.llbuilder, lhs, rhs, noname()) } } pub fn nswadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("nswadd"); unsafe { llvm::LLVMBuildNSWAdd(self.llbuilder, lhs, rhs, noname()) } } pub fn nuwadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("nuwadd"); unsafe { llvm::LLVMBuildNUWAdd(self.llbuilder, lhs, rhs, noname()) } } pub fn fadd(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("fadd"); unsafe { llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, noname()) } } pub fn fadd_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("fadd"); unsafe { let instr = llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, noname()); llvm::LLVMRustSetHasUnsafeAlgebra(instr); instr } } pub fn sub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("sub"); unsafe { llvm::LLVMBuildSub(self.llbuilder, lhs, rhs, noname()) } } pub fn nswsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("nwsub"); unsafe { llvm::LLVMBuildNSWSub(self.llbuilder, lhs, rhs, noname()) } } pub fn nuwsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("nuwsub"); unsafe { llvm::LLVMBuildNUWSub(self.llbuilder, lhs, rhs, noname()) } } pub fn fsub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("sub"); unsafe { llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, noname()) } } pub fn fsub_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("sub"); unsafe { let instr = llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, noname()); llvm::LLVMRustSetHasUnsafeAlgebra(instr); instr } } pub fn mul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("mul"); unsafe { llvm::LLVMBuildMul(self.llbuilder, lhs, rhs, noname()) } } pub fn nswmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("nswmul"); unsafe { llvm::LLVMBuildNSWMul(self.llbuilder, lhs, rhs, noname()) } } pub fn nuwmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("nuwmul"); unsafe { llvm::LLVMBuildNUWMul(self.llbuilder, lhs, rhs, noname()) } } pub fn fmul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("fmul"); unsafe { llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, noname()) } } pub fn fmul_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("fmul"); unsafe { let instr = llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, noname()); llvm::LLVMRustSetHasUnsafeAlgebra(instr); instr } } pub fn udiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("udiv"); unsafe { llvm::LLVMBuildUDiv(self.llbuilder, lhs, rhs, noname()) } } pub fn sdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("sdiv"); unsafe { llvm::LLVMBuildSDiv(self.llbuilder, lhs, rhs, noname()) } } pub fn exactsdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("exactsdiv"); unsafe { llvm::LLVMBuildExactSDiv(self.llbuilder, lhs, rhs, noname()) } } pub fn fdiv(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("fdiv"); unsafe { llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, noname()) } } pub fn fdiv_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("fdiv"); unsafe { let instr = llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, noname()); llvm::LLVMRustSetHasUnsafeAlgebra(instr); instr } } pub fn urem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("urem"); unsafe { llvm::LLVMBuildURem(self.llbuilder, lhs, rhs, noname()) } } pub fn srem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("srem"); unsafe { llvm::LLVMBuildSRem(self.llbuilder, lhs, rhs, noname()) } } pub fn frem(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("frem"); unsafe { llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, noname()) } } pub fn frem_fast(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("frem"); unsafe { let instr = llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, noname()); llvm::LLVMRustSetHasUnsafeAlgebra(instr); instr } } pub fn shl(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("shl"); unsafe { llvm::LLVMBuildShl(self.llbuilder, lhs, rhs, noname()) } } pub fn lshr(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("lshr"); unsafe { llvm::LLVMBuildLShr(self.llbuilder, lhs, rhs, noname()) } } pub fn ashr(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("ashr"); unsafe { llvm::LLVMBuildAShr(self.llbuilder, lhs, rhs, noname()) } } pub fn and(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("and"); unsafe { llvm::LLVMBuildAnd(self.llbuilder, lhs, rhs, noname()) } } pub fn or(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("or"); unsafe { llvm::LLVMBuildOr(self.llbuilder, lhs, rhs, noname()) } } pub fn xor(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("xor"); unsafe { llvm::LLVMBuildXor(self.llbuilder, lhs, rhs, noname()) } } pub fn binop(&self, op: Opcode, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("binop"); unsafe { llvm::LLVMBuildBinOp(self.llbuilder, op, lhs, rhs, noname()) } } pub fn neg(&self, v: ValueRef) -> ValueRef { self.count_insn("neg"); unsafe { llvm::LLVMBuildNeg(self.llbuilder, v, noname()) } } pub fn nswneg(&self, v: ValueRef) -> ValueRef { self.count_insn("nswneg"); unsafe { llvm::LLVMBuildNSWNeg(self.llbuilder, v, noname()) } } pub fn nuwneg(&self, v: ValueRef) -> ValueRef { self.count_insn("nuwneg"); unsafe { llvm::LLVMBuildNUWNeg(self.llbuilder, v, noname()) } } pub fn fneg(&self, v: ValueRef) -> ValueRef { self.count_insn("fneg"); unsafe { llvm::LLVMBuildFNeg(self.llbuilder, v, noname()) } } pub fn not(&self, v: ValueRef) -> ValueRef { self.count_insn("not"); unsafe { llvm::LLVMBuildNot(self.llbuilder, v, noname()) } } pub fn alloca(&self, ty: Type, name: &str) -> ValueRef { let builder = Builder::with_ccx(self.ccx); builder.position_at_start(unsafe { llvm::LLVMGetFirstBasicBlock(self.llfn()) }); builder.dynamic_alloca(ty, name) } pub fn alloca_ty(&self, ty: Ty<'tcx>, name: &str) -> ValueRef { assert!(!ty.has_param_types()); self.alloca(type_of::type_of(self.ccx, ty), name) } pub fn dynamic_alloca(&self, ty: Type, name: &str) -> ValueRef { self.count_insn("alloca"); unsafe { if name.is_empty() { llvm::LLVMBuildAlloca(self.llbuilder, ty.to_ref(), noname()) } else { let name = CString::new(name).unwrap(); llvm::LLVMBuildAlloca(self.llbuilder, ty.to_ref(), name.as_ptr()) } } } pub fn free(&self, ptr: ValueRef) { self.count_insn("free"); unsafe { llvm::LLVMBuildFree(self.llbuilder, ptr); } } pub fn load(&self, ptr: ValueRef) -> ValueRef { self.count_insn("load"); unsafe { llvm::LLVMBuildLoad(self.llbuilder, ptr, noname()) } } pub fn volatile_load(&self, ptr: ValueRef) -> ValueRef { self.count_insn("load.volatile"); unsafe { let insn = llvm::LLVMBuildLoad(self.llbuilder, ptr, noname()); llvm::LLVMSetVolatile(insn, llvm::True); insn } } pub fn atomic_load(&self, ptr: ValueRef, order: AtomicOrdering) -> ValueRef { self.count_insn("load.atomic"); unsafe { let ty = Type::from_ref(llvm::LLVMTypeOf(ptr)); let align = llalign_of_pref(self.ccx, ty.element_type()); llvm::LLVMRustBuildAtomicLoad(self.llbuilder, ptr, noname(), order, align as c_uint) } } pub fn load_range_assert(&self, ptr: ValueRef, lo: u64, hi: u64, signed: llvm::Bool) -> ValueRef { let value = self.load(ptr); unsafe { let t = llvm::LLVMGetElementType(llvm::LLVMTypeOf(ptr)); let min = llvm::LLVMConstInt(t, lo, signed); let max = llvm::LLVMConstInt(t, hi, signed); let v = [min, max]; llvm::LLVMSetMetadata(value, llvm::MD_range as c_uint, llvm::LLVMMDNodeInContext(self.ccx.llcx(), v.as_ptr(), v.len() as c_uint)); } value } pub fn load_nonnull(&self, ptr: ValueRef) -> ValueRef { let value = self.load(ptr); unsafe { llvm::LLVMSetMetadata(value, llvm::MD_nonnull as c_uint, llvm::LLVMMDNodeInContext(self.ccx.llcx(), ptr::null(), 0)); } value } pub fn store(&self, val: ValueRef, ptr: ValueRef, align: Option<u32>) -> ValueRef { debug!("Store {:?} -> {:?}", Value(val), Value(ptr)); assert!(!self.llbuilder.is_null()); self.count_insn("store"); let ptr = self.check_store(val, ptr); unsafe { let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr); if let Some(align) = align { llvm::LLVMSetAlignment(store, align as c_uint); } store } } pub fn volatile_store(&self, val: ValueRef, ptr: ValueRef) -> ValueRef { debug!("Store {:?} -> {:?}", Value(val), Value(ptr)); assert!(!self.llbuilder.is_null()); self.count_insn("store.volatile"); let ptr = self.check_store(val, ptr); unsafe { let insn = llvm::LLVMBuildStore(self.llbuilder, val, ptr); llvm::LLVMSetVolatile(insn, llvm::True); insn } } pub fn atomic_store(&self, val: ValueRef, ptr: ValueRef, order: AtomicOrdering) { debug!("Store {:?} -> {:?}", Value(val), Value(ptr)); self.count_insn("store.atomic"); let ptr = self.check_store(val, ptr); unsafe { let ty = Type::from_ref(llvm::LLVMTypeOf(ptr)); let align = llalign_of_pref(self.ccx, ty.element_type()); llvm::LLVMRustBuildAtomicStore(self.llbuilder, val, ptr, order, align as c_uint); } } pub fn gep(&self, ptr: ValueRef, indices: &[ValueRef]) -> ValueRef { self.count_insn("gep"); unsafe { llvm::LLVMBuildGEP(self.llbuilder, ptr, indices.as_ptr(), indices.len() as c_uint, noname()) } } // Simple wrapper around GEP that takes an array of ints and wraps them // in C_i32() #[inline] pub fn gepi(&self, base: ValueRef, ixs: &[usize]) -> ValueRef { // Small vector optimization. This should catch 100% of the cases that // we care about. if ixs.len() < 16 { let mut small_vec = [ C_i32(self.ccx, 0); 16 ]; for (small_vec_e, &ix) in small_vec.iter_mut().zip(ixs) { *small_vec_e = C_i32(self.ccx, ix as i32); } self.inbounds_gep(base, &small_vec[..ixs.len()]) } else { let v = ixs.iter().map(|i| C_i32(self.ccx, *i as i32)).collect::<Vec<ValueRef>>(); self.count_insn("gepi"); self.inbounds_gep(base, &v[..]) } } pub fn inbounds_gep(&self, ptr: ValueRef, indices: &[ValueRef]) -> ValueRef { self.count_insn("inboundsgep"); unsafe { llvm::LLVMBuildInBoundsGEP( self.llbuilder, ptr, indices.as_ptr(), indices.len() as c_uint, noname()) } } pub fn struct_gep(&self, ptr: ValueRef, idx: usize) -> ValueRef { self.count_insn("structgep"); unsafe { llvm::LLVMBuildStructGEP(self.llbuilder, ptr, idx as c_uint, noname()) } } pub fn global_string(&self, _str: *const c_char) -> ValueRef { self.count_insn("globalstring"); unsafe { llvm::LLVMBuildGlobalString(self.llbuilder, _str, noname()) } } pub fn global_string_ptr(&self, _str: *const c_char) -> ValueRef { self.count_insn("globalstringptr"); unsafe { llvm::LLVMBuildGlobalStringPtr(self.llbuilder, _str, noname()) } } /* Casts */ pub fn trunc(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("trunc"); unsafe { llvm::LLVMBuildTrunc(self.llbuilder, val, dest_ty.to_ref(), noname()) } } pub fn zext(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("zext"); unsafe { llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty.to_ref(), noname()) } } pub fn sext(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("sext"); unsafe { llvm::LLVMBuildSExt(self.llbuilder, val, dest_ty.to_ref(), noname()) } } pub fn fptoui(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("fptoui"); unsafe { llvm::LLVMBuildFPToUI(self.llbuilder, val, dest_ty.to_ref(), noname()) } } pub fn fptosi(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("fptosi"); unsafe { llvm::LLVMBuildFPToSI(self.llbuilder, val, dest_ty.to_ref(),noname()) } } pub fn uitofp(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("uitofp"); unsafe { llvm::LLVMBuildUIToFP(self.llbuilder, val, dest_ty.to_ref(), noname()) } } pub fn sitofp(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("sitofp"); unsafe { llvm::LLVMBuildSIToFP(self.llbuilder, val, dest_ty.to_ref(), noname()) } } pub fn fptrunc(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("fptrunc"); unsafe { llvm::LLVMBuildFPTrunc(self.llbuilder, val, dest_ty.to_ref(), noname()) } } pub fn fpext(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("fpext"); unsafe { llvm::LLVMBuildFPExt(self.llbuilder, val, dest_ty.to_ref(), noname()) } } pub fn ptrtoint(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("ptrtoint"); unsafe { llvm::LLVMBuildPtrToInt(self.llbuilder, val, dest_ty.to_ref(), noname()) } } pub fn inttoptr(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("inttoptr"); unsafe { llvm::LLVMBuildIntToPtr(self.llbuilder, val, dest_ty.to_ref(), noname()) } } pub fn bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("bitcast"); unsafe { llvm::LLVMBuildBitCast(self.llbuilder, val, dest_ty.to_ref(), noname()) } } pub fn zext_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("zextorbitcast"); unsafe { llvm::LLVMBuildZExtOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname()) } } pub fn sext_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("sextorbitcast"); unsafe { llvm::LLVMBuildSExtOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname()) } } pub fn trunc_or_bitcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("truncorbitcast"); unsafe { llvm::LLVMBuildTruncOrBitCast(self.llbuilder, val, dest_ty.to_ref(), noname()) } } pub fn cast(&self, op: Opcode, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("cast"); unsafe { llvm::LLVMBuildCast(self.llbuilder, op, val, dest_ty.to_ref(), noname()) } } pub fn pointercast(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("pointercast"); unsafe { llvm::LLVMBuildPointerCast(self.llbuilder, val, dest_ty.to_ref(), noname()) } } pub fn intcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("intcast"); unsafe { llvm::LLVMBuildIntCast(self.llbuilder, val, dest_ty.to_ref(), noname()) } } pub fn fpcast(&self, val: ValueRef, dest_ty: Type) -> ValueRef { self.count_insn("fpcast"); unsafe { llvm::LLVMBuildFPCast(self.llbuilder, val, dest_ty.to_ref(), noname()) } } /* Comparisons */ pub fn icmp(&self, op: IntPredicate, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("icmp"); unsafe { llvm::LLVMBuildICmp(self.llbuilder, op as c_uint, lhs, rhs, noname()) } } pub fn fcmp(&self, op: RealPredicate, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("fcmp"); unsafe { llvm::LLVMBuildFCmp(self.llbuilder, op as c_uint, lhs, rhs, noname()) } } /* Miscellaneous instructions */ pub fn empty_phi(&self, ty: Type) -> ValueRef { self.count_insn("emptyphi"); unsafe { llvm::LLVMBuildPhi(self.llbuilder, ty.to_ref(), noname()) } } pub fn phi(&self, ty: Type, vals: &[ValueRef], bbs: &[BasicBlockRef]) -> ValueRef { assert_eq!(vals.len(), bbs.len()); let phi = self.empty_phi(ty); self.count_insn("addincoming"); unsafe { llvm::LLVMAddIncoming(phi, vals.as_ptr(), bbs.as_ptr(), vals.len() as c_uint); phi } } pub fn add_span_comment(&self, sp: Span, text: &str) { if self.ccx.sess().asm_comments() { let s = format!("{} ({})", text, self.ccx.sess().codemap().span_to_string(sp)); debug!("{}", &s[..]); self.add_comment(&s[..]); } } pub fn add_comment(&self, text: &str) { if self.ccx.sess().asm_comments() { let sanitized = text.replace("$", ""); let comment_text = format!("{} {}", "#", sanitized.replace("\n", "\n\t# ")); self.count_insn("inlineasm"); let comment_text = CString::new(comment_text).unwrap(); let asm = unsafe { llvm::LLVMConstInlineAsm(Type::func(&[], &Type::void(self.ccx)).to_ref(), comment_text.as_ptr(), noname(), False, False) }; self.call(asm, &[], None); } } pub fn inline_asm_call(&self, asm: *const c_char, cons: *const c_char, inputs: &[ValueRef], output: Type, volatile: bool, alignstack: bool, dia: AsmDialect) -> ValueRef { self.count_insn("inlineasm"); let volatile = if volatile { llvm::True } else { llvm::False }; let alignstack = if alignstack { llvm::True } else { llvm::False }; let argtys = inputs.iter().map(|v| { debug!("Asm Input Type: {:?}", Value(*v)); val_ty(*v) }).collect::<Vec<_>>(); debug!("Asm Output Type: {:?}", output); let fty = Type::func(&argtys[..], &output); unsafe { let v = llvm::LLVMRustInlineAsm( fty.to_ref(), asm, cons, volatile, alignstack, dia); self.call(v, inputs, None) } } pub fn call(&self, llfn: ValueRef, args: &[ValueRef], bundle: Option<&OperandBundleDef>) -> ValueRef { self.count_insn("call"); debug!("Call {:?} with args ({})", Value(llfn), args.iter() .map(|&v| format!("{:?}", Value(v))) .collect::<Vec<String>>() .join(", ")); let args = self.check_call("call", llfn, args); let bundle = bundle.as_ref().map(|b| b.raw()).unwrap_or(ptr::null_mut()); unsafe { llvm::LLVMRustBuildCall(self.llbuilder, llfn, args.as_ptr(), args.len() as c_uint, bundle, noname()) } } pub fn select(&self, cond: ValueRef, then_val: ValueRef, else_val: ValueRef) -> ValueRef { self.count_insn("select"); unsafe { llvm::LLVMBuildSelect(self.llbuilder, cond, then_val, else_val, noname()) } } pub fn va_arg(&self, list: ValueRef, ty: Type) -> ValueRef { self.count_insn("vaarg"); unsafe { llvm::LLVMBuildVAArg(self.llbuilder, list, ty.to_ref(), noname()) } } pub fn extract_element(&self, vec: ValueRef, idx: ValueRef) -> ValueRef { self.count_insn("extractelement"); unsafe { llvm::LLVMBuildExtractElement(self.llbuilder, vec, idx, noname()) } } pub fn insert_element(&self, vec: ValueRef, elt: ValueRef, idx: ValueRef) -> ValueRef { self.count_insn("insertelement"); unsafe { llvm::LLVMBuildInsertElement(self.llbuilder, vec, elt, idx, noname()) } } pub fn shuffle_vector(&self, v1: ValueRef, v2: ValueRef, mask: ValueRef) -> ValueRef { self.count_insn("shufflevector"); unsafe { llvm::LLVMBuildShuffleVector(self.llbuilder, v1, v2, mask, noname()) } } pub fn vector_splat(&self, num_elts: usize, elt: ValueRef) -> ValueRef { unsafe { let elt_ty = val_ty(elt); let undef = llvm::LLVMGetUndef(Type::vector(&elt_ty, num_elts as u64).to_ref()); let vec = self.insert_element(undef, elt, C_i32(self.ccx, 0)); let vec_i32_ty = Type::vector(&Type::i32(self.ccx), num_elts as u64); self.shuffle_vector(vec, undef, C_null(vec_i32_ty)) } } pub fn extract_value(&self, agg_val: ValueRef, idx: usize) -> ValueRef { self.count_insn("extractvalue"); unsafe { llvm::LLVMBuildExtractValue(self.llbuilder, agg_val, idx as c_uint, noname()) } } pub fn insert_value(&self, agg_val: ValueRef, elt: ValueRef, idx: usize) -> ValueRef { self.count_insn("insertvalue"); unsafe { llvm::LLVMBuildInsertValue(self.llbuilder, agg_val, elt, idx as c_uint, noname()) } } pub fn is_null(&self, val: ValueRef) -> ValueRef { self.count_insn("isnull"); unsafe { llvm::LLVMBuildIsNull(self.llbuilder, val, noname()) } } pub fn is_not_null(&self, val: ValueRef) -> ValueRef { self.count_insn("isnotnull"); unsafe { llvm::LLVMBuildIsNotNull(self.llbuilder, val, noname()) } } pub fn ptrdiff(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { self.count_insn("ptrdiff"); unsafe { llvm::LLVMBuildPtrDiff(self.llbuilder, lhs, rhs, noname()) } } pub fn trap(&self) { unsafe { let bb: BasicBlockRef = llvm::LLVMGetInsertBlock(self.llbuilder); let fn_: ValueRef = llvm::LLVMGetBasicBlockParent(bb); let m: ModuleRef = llvm::LLVMGetGlobalParent(fn_); let p = "llvm.trap\0".as_ptr(); let t: ValueRef = llvm::LLVMGetNamedFunction(m, p as *const _); assert!((t as isize != 0)); let args: &[ValueRef] = &[]; self.count_insn("trap"); llvm::LLVMRustBuildCall(self.llbuilder, t, args.as_ptr(), args.len() as c_uint, ptr::null_mut(), noname()); } } pub fn landing_pad(&self, ty: Type, pers_fn: ValueRef, num_clauses: usize, llfn: ValueRef) -> ValueRef { self.count_insn("landingpad"); unsafe { llvm::LLVMRustBuildLandingPad(self.llbuilder, ty.to_ref(), pers_fn, num_clauses as c_uint, noname(), llfn) } } pub fn add_clause(&self, landing_pad: ValueRef, clause: ValueRef) { unsafe { llvm::LLVMAddClause(landing_pad, clause); } } pub fn set_cleanup(&self, landing_pad: ValueRef) { self.count_insn("setcleanup"); unsafe { llvm::LLVMSetCleanup(landing_pad, llvm::True); } } pub fn resume(&self, exn: ValueRef) -> ValueRef { self.count_insn("resume"); unsafe { llvm::LLVMBuildResume(self.llbuilder, exn) } } pub fn cleanup_pad(&self, parent: Option<ValueRef>, args: &[ValueRef]) -> ValueRef { self.count_insn("cleanuppad"); let parent = parent.unwrap_or(ptr::null_mut()); let name = CString::new("cleanuppad").unwrap(); let ret = unsafe { llvm::LLVMRustBuildCleanupPad(self.llbuilder, parent, args.len() as c_uint, args.as_ptr(), name.as_ptr()) }; assert!(!ret.is_null(), "LLVM does not have support for cleanuppad"); return ret } pub fn cleanup_ret(&self, cleanup: ValueRef, unwind: Option<BasicBlockRef>) -> ValueRef { self.count_insn("cleanupret"); let unwind = unwind.unwrap_or(ptr::null_mut()); let ret = unsafe { llvm::LLVMRustBuildCleanupRet(self.llbuilder, cleanup, unwind) }; assert!(!ret.is_null(), "LLVM does not have support for cleanupret"); return ret } pub fn catch_pad(&self, parent: ValueRef, args: &[ValueRef]) -> ValueRef { self.count_insn("catchpad"); let name = CString::new("catchpad").unwrap(); let ret = unsafe { llvm::LLVMRustBuildCatchPad(self.llbuilder, parent, args.len() as c_uint, args.as_ptr(), name.as_ptr()) }; assert!(!ret.is_null(), "LLVM does not have support for catchpad"); return ret } pub fn catch_ret(&self, pad: ValueRef, unwind: BasicBlockRef) -> ValueRef { self.count_insn("catchret"); let ret = unsafe { llvm::LLVMRustBuildCatchRet(self.llbuilder, pad, unwind) }; assert!(!ret.is_null(), "LLVM does not have support for catchret"); return ret } pub fn catch_switch(&self, parent: Option<ValueRef>, unwind: Option<BasicBlockRef>, num_handlers: usize) -> ValueRef { self.count_insn("catchswitch"); let parent = parent.unwrap_or(ptr::null_mut()); let unwind = unwind.unwrap_or(ptr::null_mut()); let name = CString::new("catchswitch").unwrap(); let ret = unsafe { llvm::LLVMRustBuildCatchSwitch(self.llbuilder, parent, unwind, num_handlers as c_uint, name.as_ptr()) }; assert!(!ret.is_null(), "LLVM does not have support for catchswitch"); return ret } pub fn add_handler(&self, catch_switch: ValueRef, handler: BasicBlockRef) { unsafe { llvm::LLVMRustAddHandler(catch_switch, handler); } } pub fn set_personality_fn(&self, personality: ValueRef) { unsafe { llvm::LLVMSetPersonalityFn(self.llfn(), personality); } } // Atomic Operations pub fn atomic_cmpxchg(&self, dst: ValueRef, cmp: ValueRef, src: ValueRef, order: AtomicOrdering, failure_order: AtomicOrdering, weak: llvm::Bool) -> ValueRef { unsafe { llvm::LLVMRustBuildAtomicCmpXchg(self.llbuilder, dst, cmp, src, order, failure_order, weak) } } pub fn atomic_rmw(&self, op: AtomicRmwBinOp, dst: ValueRef, src: ValueRef, order: AtomicOrdering) -> ValueRef { unsafe { llvm::LLVMBuildAtomicRMW(self.llbuilder, op, dst, src, order, False) } } pub fn atomic_fence(&self, order: AtomicOrdering, scope: SynchronizationScope) { unsafe { llvm::LLVMRustBuildAtomicFence(self.llbuilder, order, scope); } } pub fn add_case(&self, s: ValueRef, on_val: ValueRef, dest: BasicBlockRef) { unsafe { if llvm::LLVMIsUndef(s) == llvm::True { return; } llvm::LLVMAddCase(s, on_val, dest) } } pub fn add_incoming_to_phi(&self, phi: ValueRef, val: ValueRef, bb: BasicBlockRef) { unsafe { if llvm::LLVMIsUndef(phi) == llvm::True { return; } llvm::LLVMAddIncoming(phi, &val, &bb, 1 as c_uint); } } /// Returns the ptr value that should be used for storing `val`. fn check_store<'b>(&self, val: ValueRef, ptr: ValueRef) -> ValueRef { let dest_ptr_ty = val_ty(ptr); let stored_ty = val_ty(val); let stored_ptr_ty = stored_ty.ptr_to(); assert_eq!(dest_ptr_ty.kind(), llvm::TypeKind::Pointer); if dest_ptr_ty == stored_ptr_ty { ptr } else { debug!("Type mismatch in store. \ Expected {:?}, got {:?}; inserting bitcast", dest_ptr_ty, stored_ptr_ty); self.bitcast(ptr, stored_ptr_ty) } } /// Returns the args that should be used for a call to `llfn`. fn check_call<'b>(&self, typ: &str, llfn: ValueRef, args: &'b [ValueRef]) -> Cow<'b, [ValueRef]> { let mut fn_ty = val_ty(llfn); // Strip off pointers while fn_ty.kind() == llvm::TypeKind::Pointer { fn_ty = fn_ty.element_type(); } assert!(fn_ty.kind() == llvm::TypeKind::Function, "builder::{} not passed a function", typ); let param_tys = fn_ty.func_params(); let all_args_match = param_tys.iter() .zip(args.iter().map(|&v| val_ty(v))) .all(|(expected_ty, actual_ty)| *expected_ty == actual_ty); if all_args_match { return Cow::Borrowed(args); } let casted_args: Vec<_> = param_tys.into_iter() .zip(args.iter()) .enumerate() .map(|(i, (expected_ty, &actual_val))| { let actual_ty = val_ty(actual_val); if expected_ty != actual_ty { debug!("Type mismatch in function call of {:?}. \ Expected {:?} for param {}, got {:?}; injecting bitcast", Value(llfn), expected_ty, i, actual_ty); self.bitcast(actual_val, expected_ty) } else { actual_val } }) .collect(); return Cow::Owned(casted_args); } }
32.79622
98
0.529877
d7c6e4d2ba836e06ecf9d67a580e92144848fdf0
1,606
use crate::state::*; use ethnum::U256; use i256::I256; #[inline(always)] pub(crate) fn lt(stack: &mut Stack) { let a = stack.pop(); let b = stack.get_mut(0); *b = if a.lt(b) { U256::ONE } else { U256::ZERO } } #[inline(always)] pub(crate) fn gt(stack: &mut Stack) { let a = stack.pop(); let b = stack.get_mut(0); *b = if a.gt(b) { U256::ONE } else { U256::ZERO } } #[inline(always)] pub(crate) fn slt(stack: &mut Stack) { let a: I256 = stack.pop().into(); let b: I256 = stack.pop().into(); stack.push(if a.lt(&b) { U256::ONE } else { U256::ZERO }) } #[inline(always)] pub(crate) fn sgt(stack: &mut Stack) { let a: I256 = stack.pop().into(); let b: I256 = stack.pop().into(); stack.push(if a.gt(&b) { U256::ONE } else { U256::ZERO }) } #[inline(always)] pub(crate) fn eq(stack: &mut Stack) { let a = stack.pop(); let b = stack.get_mut(0); *b = if a.eq(b) { U256::ONE } else { U256::ZERO } } #[inline(always)] pub(crate) fn iszero(stack: &mut Stack) { let a = stack.get_mut(0); *a = if *a == 0 { U256::ONE } else { U256::ZERO } } #[inline(always)] pub(crate) fn and(stack: &mut Stack) { let a = stack.pop(); let b = stack.get_mut(0); *b = a & *b; } #[inline(always)] pub(crate) fn or(stack: &mut Stack) { let a = stack.pop(); let b = stack.get_mut(0); *b = a | *b; } #[inline(always)] pub(crate) fn xor(stack: &mut Stack) { let a = stack.pop(); let b = stack.get_mut(0); *b = a ^ *b; } #[inline(always)] pub(crate) fn not(stack: &mut Stack) { let v = stack.get_mut(0); *v = !*v; }
20.857143
61
0.551059
fbe4f0e36c686283be58c2511e61d06b509c66dc
912
mod analyzed_token; mod cli_configuration; mod doctor; mod error_message; mod flags; mod formatters; mod project_configurations_loader; use cli_configuration::CliConfiguration; use colored::*; use doctor::Doctor; use flags::{Flags, Format}; use project_configuration::ProjectConfigurations; use structopt::StructOpt; use token_search::Token; pub fn run() { let mut flags = Flags::from_args(); if flags.json { flags.format = Format::Json; } if flags.no_color { control::set_override(false); } match flags.cmd { Some(flags::Command::Doctor) => Doctor::new().render(), Some(flags::Command::DefaultYaml) => println!("{}", ProjectConfigurations::default_yaml()), _ => match Token::all() { Ok((_, results)) => CliConfiguration::new(flags, results).render(), Err(e) => error_message::failed_token_parse(e), }, } }
24.648649
99
0.656798
71c2c1ede69962890cf7f529d4432ccc97df96cf
103
crate::version::Version { minor: 59, patch: 0, channel: crate::version::Channel::Stable, }
17.166667
45
0.621359
916adc83223ac4c24c2863a1b4c01542659a9723
711
// 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. // compile-pass // pretty-expanded FIXME #23616 trait Canvas { fn add_point(&self, point: &isize); fn add_points(&self, shapes: &[isize]) { for pt in shapes { self.add_point(pt) } } } pub fn main() {}
28.44
68
0.679325
5d37bf904724b31fe4338336e24ef53d20a64514
2,870
use std::ffi::{CString}; use std::os::raw::c_char; use serde::{Serialize,Deserialize}; use bdk::Wallet; use bdk::database::SqliteDatabase; use bdk::wallet::AddressIndex::Peek; use crate::e::{S5Error,ErrorKind}; use crate::config::{WalletConfig}; /// FFI Output #[derive(Serialize,Deserialize,Debug)] pub struct WalletAddress { pub address: String, } impl WalletAddress{ pub fn c_stringify(&self)->*mut c_char{ let stringified = match serde_json::to_string(self){ Ok(result)=>result, Err(_)=>return CString::new("Error:JSON Stringify Failed. BAD NEWS! Contact Support.").unwrap().into_raw() }; CString::new(stringified).unwrap().into_raw() } } pub fn generate( config: WalletConfig, index: u32, ) -> Result<WalletAddress, S5Error> { let wallet = match Wallet::new( &config.deposit_desc, Some(&config.change_desc), config.network, SqliteDatabase::new(config.db_path.unwrap()), ){ Ok(result) => result, Err(e) => return Err(S5Error::new(ErrorKind::Internal,&e.to_string())) }; match wallet.get_address(Peek(index)){ Ok(address) => Ok(WalletAddress{ address:address.to_string() }), Err(e) => Err(S5Error::new(ErrorKind::Internal,&e.to_string())) } } #[cfg(test)] mod tests { use crate::config::DEFAULT_TESTNET_NODE; use super::*; use std::process::Command; use secp256k1::rand::{distributions::Alphanumeric, thread_rng,Rng}; // 0.8 #[test] fn test_solo_address() { let xkey = "[db7d25b5/84'/1'/6']tpubDCCh4SuT3pSAQ1qAN86qKEzsLoBeiugoGGQeibmieRUKv8z6fCTTmEXsb9yeueBkUWjGVzJr91bCzeCNShorbBqjZV4WRGjz3CrJsCboXUe"; let descriptor = format!("wpkh({}/*)", xkey); let s: String =thread_rng() .sample_iter(&Alphanumeric) .take(7) .map(char::from) .collect(); let db_path = env!("CARGO_MANIFEST_DIR").to_owned() + "/artifacts/" + &s + ".db"; let config = WalletConfig::new(&descriptor,Some(db_path.clone()),Some(DEFAULT_TESTNET_NODE),None).unwrap(); let address0 = generate(config, 0).unwrap(); assert_eq!( "tb1q093gl5yxww0hlvlkajdmf8wh3a6rlvsdk9e6d3", address0.address ); let config = WalletConfig::new(&descriptor,Some(db_path.clone()),Some(DEFAULT_TESTNET_NODE),None).unwrap(); let address1 = generate(config, 1).unwrap(); assert_eq!( "tb1qzdwqxt8l2s47vl4fp4ft6w67fcxel4qf5j96ld".to_string(), address1.address ); let mut remove = Command::new("rm"); let _removed = remove.arg("-rf").arg(&db_path).output().unwrap(); } // fn test_raft_address(){ // let user = "[db7d25b5/84'/1'/6']tpubDCCh4SuT3pSAQ1qAN86qKEzsLoBeiugoGGQeibmieRUKv8z6fCTTmEXsb9yeueBkUWjGVzJr91bCzeCNShorbBqjZV4WRGjz3CrJsCboXUe"; // let custodian = "[66a0c105/84'/1'/5']tpubDCKvnVh6U56wTSUEJGamQzdb3ByAc6gTPbjxXQqts5Bf1dBMopknipUUSmAV3UuihKPTddruSZCiqhyiYyhFWhz62SAGuC3PYmtAafUuG6R"; // } }
32.247191
157
0.693728
14bb1614c8d2f2715c710c19857ce621b23e0823
1,978
#![allow(dead_code)] #![cfg_attr(test, feature(plugin))] #![cfg_attr(test, plugin(quickcheck_macros))] #[cfg(test)] extern crate quickcheck; extern crate rand; #[macro_use] extern crate rand_derive; #[macro_use] extern crate comp; #[macro_use] extern crate lazy_static; extern crate conv; pub mod utils; pub mod gen; pub mod u64s; pub mod random_utils; pub mod zygote; pub mod chromosome; pub mod individual; pub mod generation; pub mod fitness_calculator; pub mod breeding; pub mod incubator; pub mod global_constants; use breeding::*; use incubator::Incubator; use random_utils::*; use fitness_calculator::*; use conv::*; use utils::*; use std::time::{SystemTime, UNIX_EPOCH}; use global_constants::*; impl RandomParams for RandomParamsStruct { fn chromosome_genes_amount() -> usize { 20 * U64_BITS_AMOUNT } } impl FitnessCalculator for FitnessCalculatorStruct { fn calc_fitness(decoded_genotype: &[u64]) -> f64 { let u64s = decode_bits_to_u64s(decoded_genotype); u64s.iter().map(|l| f64::approx_from(*l)).fold( 0.0, |acc, d| { acc + d.unwrap() }, ) } } fn main() { let chromosomes_amount = 1000; let mut incubator: Incubator< RandomUtilsStruct<RandomParamsStruct>, PerfChoosingProbability, BreedingStruct<RandomUtilsStruct<RandomParamsStruct>>, FitnessCalculatorStruct, > = Incubator::new(chromosomes_amount); let duration = run_and_measure(|| for _ in 0..100_000 { incubator.make_next_generation(); }); println!("exec time = {:?} ms", duration); } fn run_and_measure<F>(f: F) -> u64 where F: FnOnce(), { let start = get_ms_now(); f(); get_ms_now() - start } fn get_ms_now() -> u64 { let start = SystemTime::now(); let since_the_epoch = start.duration_since(UNIX_EPOCH).unwrap(); since_the_epoch.as_secs() * 1000 + u64::from(since_the_epoch.subsec_nanos()) / 1_000_000 }
22.477273
92
0.669869
e43e9abea6968408961d7070dbb0de6675c96dc6
98
pub mod constants; pub mod instructions; pub mod utils; pub mod processor; #[cfg(test)] mod test;
14
21
0.744898
91df418e202fb35b96fb6f2e7c32379613589bc6
221,659
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Error type for the `AssociateDomain` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct AssociateDomainError { /// Kind of error that occurred. pub kind: AssociateDomainErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `AssociateDomain` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum AssociateDomainErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The resource already exists.</p> ResourceAlreadyExistsException(crate::error::ResourceAlreadyExistsException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for AssociateDomainError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { AssociateDomainErrorKind::InternalServerErrorException(_inner) => _inner.fmt(f), AssociateDomainErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), AssociateDomainErrorKind::ResourceAlreadyExistsException(_inner) => _inner.fmt(f), AssociateDomainErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), AssociateDomainErrorKind::TooManyRequestsException(_inner) => _inner.fmt(f), AssociateDomainErrorKind::UnauthorizedException(_inner) => _inner.fmt(f), AssociateDomainErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for AssociateDomainError { fn code(&self) -> Option<&str> { AssociateDomainError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl AssociateDomainError { /// Creates a new `AssociateDomainError`. pub fn new(kind: AssociateDomainErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `AssociateDomainError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: AssociateDomainErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `AssociateDomainError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: AssociateDomainErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `AssociateDomainErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, AssociateDomainErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `AssociateDomainErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, AssociateDomainErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `AssociateDomainErrorKind::ResourceAlreadyExistsException`. pub fn is_resource_already_exists_exception(&self) -> bool { matches!( &self.kind, AssociateDomainErrorKind::ResourceAlreadyExistsException(_) ) } /// Returns `true` if the error kind is `AssociateDomainErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, AssociateDomainErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `AssociateDomainErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, AssociateDomainErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `AssociateDomainErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!( &self.kind, AssociateDomainErrorKind::UnauthorizedException(_) ) } } impl std::error::Error for AssociateDomainError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { AssociateDomainErrorKind::InternalServerErrorException(_inner) => Some(_inner), AssociateDomainErrorKind::InvalidRequestException(_inner) => Some(_inner), AssociateDomainErrorKind::ResourceAlreadyExistsException(_inner) => Some(_inner), AssociateDomainErrorKind::ResourceNotFoundException(_inner) => Some(_inner), AssociateDomainErrorKind::TooManyRequestsException(_inner) => Some(_inner), AssociateDomainErrorKind::UnauthorizedException(_inner) => Some(_inner), AssociateDomainErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `AssociateWebsiteAuthorizationProvider` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct AssociateWebsiteAuthorizationProviderError { /// Kind of error that occurred. pub kind: AssociateWebsiteAuthorizationProviderErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `AssociateWebsiteAuthorizationProvider` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum AssociateWebsiteAuthorizationProviderErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The resource already exists.</p> ResourceAlreadyExistsException(crate::error::ResourceAlreadyExistsException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for AssociateWebsiteAuthorizationProviderError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { AssociateWebsiteAuthorizationProviderErrorKind::InternalServerErrorException( _inner, ) => _inner.fmt(f), AssociateWebsiteAuthorizationProviderErrorKind::InvalidRequestException(_inner) => { _inner.fmt(f) } AssociateWebsiteAuthorizationProviderErrorKind::ResourceAlreadyExistsException( _inner, ) => _inner.fmt(f), AssociateWebsiteAuthorizationProviderErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } AssociateWebsiteAuthorizationProviderErrorKind::TooManyRequestsException(_inner) => { _inner.fmt(f) } AssociateWebsiteAuthorizationProviderErrorKind::UnauthorizedException(_inner) => { _inner.fmt(f) } AssociateWebsiteAuthorizationProviderErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for AssociateWebsiteAuthorizationProviderError { fn code(&self) -> Option<&str> { AssociateWebsiteAuthorizationProviderError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl AssociateWebsiteAuthorizationProviderError { /// Creates a new `AssociateWebsiteAuthorizationProviderError`. pub fn new( kind: AssociateWebsiteAuthorizationProviderErrorKind, meta: aws_smithy_types::Error, ) -> Self { Self { kind, meta } } /// Creates the `AssociateWebsiteAuthorizationProviderError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: AssociateWebsiteAuthorizationProviderErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `AssociateWebsiteAuthorizationProviderError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: AssociateWebsiteAuthorizationProviderErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `AssociateWebsiteAuthorizationProviderErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, AssociateWebsiteAuthorizationProviderErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `AssociateWebsiteAuthorizationProviderErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, AssociateWebsiteAuthorizationProviderErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `AssociateWebsiteAuthorizationProviderErrorKind::ResourceAlreadyExistsException`. pub fn is_resource_already_exists_exception(&self) -> bool { matches!( &self.kind, AssociateWebsiteAuthorizationProviderErrorKind::ResourceAlreadyExistsException(_) ) } /// Returns `true` if the error kind is `AssociateWebsiteAuthorizationProviderErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, AssociateWebsiteAuthorizationProviderErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `AssociateWebsiteAuthorizationProviderErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, AssociateWebsiteAuthorizationProviderErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `AssociateWebsiteAuthorizationProviderErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!( &self.kind, AssociateWebsiteAuthorizationProviderErrorKind::UnauthorizedException(_) ) } } impl std::error::Error for AssociateWebsiteAuthorizationProviderError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { AssociateWebsiteAuthorizationProviderErrorKind::InternalServerErrorException( _inner, ) => Some(_inner), AssociateWebsiteAuthorizationProviderErrorKind::InvalidRequestException(_inner) => { Some(_inner) } AssociateWebsiteAuthorizationProviderErrorKind::ResourceAlreadyExistsException( _inner, ) => Some(_inner), AssociateWebsiteAuthorizationProviderErrorKind::ResourceNotFoundException(_inner) => { Some(_inner) } AssociateWebsiteAuthorizationProviderErrorKind::TooManyRequestsException(_inner) => { Some(_inner) } AssociateWebsiteAuthorizationProviderErrorKind::UnauthorizedException(_inner) => { Some(_inner) } AssociateWebsiteAuthorizationProviderErrorKind::Unhandled(_inner) => { Some(_inner.as_ref()) } } } } /// Error type for the `AssociateWebsiteCertificateAuthority` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct AssociateWebsiteCertificateAuthorityError { /// Kind of error that occurred. pub kind: AssociateWebsiteCertificateAuthorityErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `AssociateWebsiteCertificateAuthority` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum AssociateWebsiteCertificateAuthorityErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The resource already exists.</p> ResourceAlreadyExistsException(crate::error::ResourceAlreadyExistsException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for AssociateWebsiteCertificateAuthorityError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { AssociateWebsiteCertificateAuthorityErrorKind::InternalServerErrorException(_inner) => { _inner.fmt(f) } AssociateWebsiteCertificateAuthorityErrorKind::InvalidRequestException(_inner) => { _inner.fmt(f) } AssociateWebsiteCertificateAuthorityErrorKind::ResourceAlreadyExistsException( _inner, ) => _inner.fmt(f), AssociateWebsiteCertificateAuthorityErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } AssociateWebsiteCertificateAuthorityErrorKind::TooManyRequestsException(_inner) => { _inner.fmt(f) } AssociateWebsiteCertificateAuthorityErrorKind::UnauthorizedException(_inner) => { _inner.fmt(f) } AssociateWebsiteCertificateAuthorityErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for AssociateWebsiteCertificateAuthorityError { fn code(&self) -> Option<&str> { AssociateWebsiteCertificateAuthorityError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl AssociateWebsiteCertificateAuthorityError { /// Creates a new `AssociateWebsiteCertificateAuthorityError`. pub fn new( kind: AssociateWebsiteCertificateAuthorityErrorKind, meta: aws_smithy_types::Error, ) -> Self { Self { kind, meta } } /// Creates the `AssociateWebsiteCertificateAuthorityError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: AssociateWebsiteCertificateAuthorityErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `AssociateWebsiteCertificateAuthorityError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: AssociateWebsiteCertificateAuthorityErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `AssociateWebsiteCertificateAuthorityErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, AssociateWebsiteCertificateAuthorityErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `AssociateWebsiteCertificateAuthorityErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, AssociateWebsiteCertificateAuthorityErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `AssociateWebsiteCertificateAuthorityErrorKind::ResourceAlreadyExistsException`. pub fn is_resource_already_exists_exception(&self) -> bool { matches!( &self.kind, AssociateWebsiteCertificateAuthorityErrorKind::ResourceAlreadyExistsException(_) ) } /// Returns `true` if the error kind is `AssociateWebsiteCertificateAuthorityErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, AssociateWebsiteCertificateAuthorityErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `AssociateWebsiteCertificateAuthorityErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, AssociateWebsiteCertificateAuthorityErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `AssociateWebsiteCertificateAuthorityErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!( &self.kind, AssociateWebsiteCertificateAuthorityErrorKind::UnauthorizedException(_) ) } } impl std::error::Error for AssociateWebsiteCertificateAuthorityError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { AssociateWebsiteCertificateAuthorityErrorKind::InternalServerErrorException(_inner) => { Some(_inner) } AssociateWebsiteCertificateAuthorityErrorKind::InvalidRequestException(_inner) => { Some(_inner) } AssociateWebsiteCertificateAuthorityErrorKind::ResourceAlreadyExistsException( _inner, ) => Some(_inner), AssociateWebsiteCertificateAuthorityErrorKind::ResourceNotFoundException(_inner) => { Some(_inner) } AssociateWebsiteCertificateAuthorityErrorKind::TooManyRequestsException(_inner) => { Some(_inner) } AssociateWebsiteCertificateAuthorityErrorKind::UnauthorizedException(_inner) => { Some(_inner) } AssociateWebsiteCertificateAuthorityErrorKind::Unhandled(_inner) => { Some(_inner.as_ref()) } } } } /// Error type for the `CreateFleet` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct CreateFleetError { /// Kind of error that occurred. pub kind: CreateFleetErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `CreateFleet` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum CreateFleetErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The resource already exists.</p> ResourceAlreadyExistsException(crate::error::ResourceAlreadyExistsException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for CreateFleetError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { CreateFleetErrorKind::InternalServerErrorException(_inner) => _inner.fmt(f), CreateFleetErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), CreateFleetErrorKind::ResourceAlreadyExistsException(_inner) => _inner.fmt(f), CreateFleetErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), CreateFleetErrorKind::TooManyRequestsException(_inner) => _inner.fmt(f), CreateFleetErrorKind::UnauthorizedException(_inner) => _inner.fmt(f), CreateFleetErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for CreateFleetError { fn code(&self) -> Option<&str> { CreateFleetError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl CreateFleetError { /// Creates a new `CreateFleetError`. pub fn new(kind: CreateFleetErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `CreateFleetError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: CreateFleetErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `CreateFleetError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: CreateFleetErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `CreateFleetErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, CreateFleetErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `CreateFleetErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!(&self.kind, CreateFleetErrorKind::InvalidRequestException(_)) } /// Returns `true` if the error kind is `CreateFleetErrorKind::ResourceAlreadyExistsException`. pub fn is_resource_already_exists_exception(&self) -> bool { matches!( &self.kind, CreateFleetErrorKind::ResourceAlreadyExistsException(_) ) } /// Returns `true` if the error kind is `CreateFleetErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, CreateFleetErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `CreateFleetErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, CreateFleetErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `CreateFleetErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!(&self.kind, CreateFleetErrorKind::UnauthorizedException(_)) } } impl std::error::Error for CreateFleetError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { CreateFleetErrorKind::InternalServerErrorException(_inner) => Some(_inner), CreateFleetErrorKind::InvalidRequestException(_inner) => Some(_inner), CreateFleetErrorKind::ResourceAlreadyExistsException(_inner) => Some(_inner), CreateFleetErrorKind::ResourceNotFoundException(_inner) => Some(_inner), CreateFleetErrorKind::TooManyRequestsException(_inner) => Some(_inner), CreateFleetErrorKind::UnauthorizedException(_inner) => Some(_inner), CreateFleetErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DeleteFleet` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DeleteFleetError { /// Kind of error that occurred. pub kind: DeleteFleetErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DeleteFleet` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DeleteFleetErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DeleteFleetError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DeleteFleetErrorKind::InternalServerErrorException(_inner) => _inner.fmt(f), DeleteFleetErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DeleteFleetErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), DeleteFleetErrorKind::TooManyRequestsException(_inner) => _inner.fmt(f), DeleteFleetErrorKind::UnauthorizedException(_inner) => _inner.fmt(f), DeleteFleetErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DeleteFleetError { fn code(&self) -> Option<&str> { DeleteFleetError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DeleteFleetError { /// Creates a new `DeleteFleetError`. pub fn new(kind: DeleteFleetErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DeleteFleetError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DeleteFleetErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DeleteFleetError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DeleteFleetErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DeleteFleetErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, DeleteFleetErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `DeleteFleetErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!(&self.kind, DeleteFleetErrorKind::InvalidRequestException(_)) } /// Returns `true` if the error kind is `DeleteFleetErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DeleteFleetErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DeleteFleetErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, DeleteFleetErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `DeleteFleetErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!(&self.kind, DeleteFleetErrorKind::UnauthorizedException(_)) } } impl std::error::Error for DeleteFleetError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DeleteFleetErrorKind::InternalServerErrorException(_inner) => Some(_inner), DeleteFleetErrorKind::InvalidRequestException(_inner) => Some(_inner), DeleteFleetErrorKind::ResourceNotFoundException(_inner) => Some(_inner), DeleteFleetErrorKind::TooManyRequestsException(_inner) => Some(_inner), DeleteFleetErrorKind::UnauthorizedException(_inner) => Some(_inner), DeleteFleetErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DescribeAuditStreamConfiguration` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DescribeAuditStreamConfigurationError { /// Kind of error that occurred. pub kind: DescribeAuditStreamConfigurationErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DescribeAuditStreamConfiguration` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DescribeAuditStreamConfigurationErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DescribeAuditStreamConfigurationError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DescribeAuditStreamConfigurationErrorKind::InternalServerErrorException(_inner) => { _inner.fmt(f) } DescribeAuditStreamConfigurationErrorKind::InvalidRequestException(_inner) => { _inner.fmt(f) } DescribeAuditStreamConfigurationErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } DescribeAuditStreamConfigurationErrorKind::TooManyRequestsException(_inner) => { _inner.fmt(f) } DescribeAuditStreamConfigurationErrorKind::UnauthorizedException(_inner) => { _inner.fmt(f) } DescribeAuditStreamConfigurationErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DescribeAuditStreamConfigurationError { fn code(&self) -> Option<&str> { DescribeAuditStreamConfigurationError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DescribeAuditStreamConfigurationError { /// Creates a new `DescribeAuditStreamConfigurationError`. pub fn new( kind: DescribeAuditStreamConfigurationErrorKind, meta: aws_smithy_types::Error, ) -> Self { Self { kind, meta } } /// Creates the `DescribeAuditStreamConfigurationError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DescribeAuditStreamConfigurationErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DescribeAuditStreamConfigurationError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DescribeAuditStreamConfigurationErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DescribeAuditStreamConfigurationErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, DescribeAuditStreamConfigurationErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `DescribeAuditStreamConfigurationErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DescribeAuditStreamConfigurationErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DescribeAuditStreamConfigurationErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DescribeAuditStreamConfigurationErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DescribeAuditStreamConfigurationErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, DescribeAuditStreamConfigurationErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `DescribeAuditStreamConfigurationErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!( &self.kind, DescribeAuditStreamConfigurationErrorKind::UnauthorizedException(_) ) } } impl std::error::Error for DescribeAuditStreamConfigurationError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DescribeAuditStreamConfigurationErrorKind::InternalServerErrorException(_inner) => { Some(_inner) } DescribeAuditStreamConfigurationErrorKind::InvalidRequestException(_inner) => { Some(_inner) } DescribeAuditStreamConfigurationErrorKind::ResourceNotFoundException(_inner) => { Some(_inner) } DescribeAuditStreamConfigurationErrorKind::TooManyRequestsException(_inner) => { Some(_inner) } DescribeAuditStreamConfigurationErrorKind::UnauthorizedException(_inner) => { Some(_inner) } DescribeAuditStreamConfigurationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DescribeCompanyNetworkConfiguration` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DescribeCompanyNetworkConfigurationError { /// Kind of error that occurred. pub kind: DescribeCompanyNetworkConfigurationErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DescribeCompanyNetworkConfiguration` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DescribeCompanyNetworkConfigurationErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DescribeCompanyNetworkConfigurationError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DescribeCompanyNetworkConfigurationErrorKind::InternalServerErrorException(_inner) => { _inner.fmt(f) } DescribeCompanyNetworkConfigurationErrorKind::InvalidRequestException(_inner) => { _inner.fmt(f) } DescribeCompanyNetworkConfigurationErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } DescribeCompanyNetworkConfigurationErrorKind::TooManyRequestsException(_inner) => { _inner.fmt(f) } DescribeCompanyNetworkConfigurationErrorKind::UnauthorizedException(_inner) => { _inner.fmt(f) } DescribeCompanyNetworkConfigurationErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DescribeCompanyNetworkConfigurationError { fn code(&self) -> Option<&str> { DescribeCompanyNetworkConfigurationError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DescribeCompanyNetworkConfigurationError { /// Creates a new `DescribeCompanyNetworkConfigurationError`. pub fn new( kind: DescribeCompanyNetworkConfigurationErrorKind, meta: aws_smithy_types::Error, ) -> Self { Self { kind, meta } } /// Creates the `DescribeCompanyNetworkConfigurationError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DescribeCompanyNetworkConfigurationErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DescribeCompanyNetworkConfigurationError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DescribeCompanyNetworkConfigurationErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DescribeCompanyNetworkConfigurationErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, DescribeCompanyNetworkConfigurationErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `DescribeCompanyNetworkConfigurationErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DescribeCompanyNetworkConfigurationErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DescribeCompanyNetworkConfigurationErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DescribeCompanyNetworkConfigurationErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DescribeCompanyNetworkConfigurationErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, DescribeCompanyNetworkConfigurationErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `DescribeCompanyNetworkConfigurationErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!( &self.kind, DescribeCompanyNetworkConfigurationErrorKind::UnauthorizedException(_) ) } } impl std::error::Error for DescribeCompanyNetworkConfigurationError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DescribeCompanyNetworkConfigurationErrorKind::InternalServerErrorException(_inner) => { Some(_inner) } DescribeCompanyNetworkConfigurationErrorKind::InvalidRequestException(_inner) => { Some(_inner) } DescribeCompanyNetworkConfigurationErrorKind::ResourceNotFoundException(_inner) => { Some(_inner) } DescribeCompanyNetworkConfigurationErrorKind::TooManyRequestsException(_inner) => { Some(_inner) } DescribeCompanyNetworkConfigurationErrorKind::UnauthorizedException(_inner) => { Some(_inner) } DescribeCompanyNetworkConfigurationErrorKind::Unhandled(_inner) => { Some(_inner.as_ref()) } } } } /// Error type for the `DescribeDevice` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DescribeDeviceError { /// Kind of error that occurred. pub kind: DescribeDeviceErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DescribeDevice` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DescribeDeviceErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DescribeDeviceError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DescribeDeviceErrorKind::InternalServerErrorException(_inner) => _inner.fmt(f), DescribeDeviceErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DescribeDeviceErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), DescribeDeviceErrorKind::TooManyRequestsException(_inner) => _inner.fmt(f), DescribeDeviceErrorKind::UnauthorizedException(_inner) => _inner.fmt(f), DescribeDeviceErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DescribeDeviceError { fn code(&self) -> Option<&str> { DescribeDeviceError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DescribeDeviceError { /// Creates a new `DescribeDeviceError`. pub fn new(kind: DescribeDeviceErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DescribeDeviceError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DescribeDeviceErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DescribeDeviceError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DescribeDeviceErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DescribeDeviceErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, DescribeDeviceErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `DescribeDeviceErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DescribeDeviceErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DescribeDeviceErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DescribeDeviceErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DescribeDeviceErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, DescribeDeviceErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `DescribeDeviceErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!( &self.kind, DescribeDeviceErrorKind::UnauthorizedException(_) ) } } impl std::error::Error for DescribeDeviceError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DescribeDeviceErrorKind::InternalServerErrorException(_inner) => Some(_inner), DescribeDeviceErrorKind::InvalidRequestException(_inner) => Some(_inner), DescribeDeviceErrorKind::ResourceNotFoundException(_inner) => Some(_inner), DescribeDeviceErrorKind::TooManyRequestsException(_inner) => Some(_inner), DescribeDeviceErrorKind::UnauthorizedException(_inner) => Some(_inner), DescribeDeviceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DescribeDevicePolicyConfiguration` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DescribeDevicePolicyConfigurationError { /// Kind of error that occurred. pub kind: DescribeDevicePolicyConfigurationErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DescribeDevicePolicyConfiguration` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DescribeDevicePolicyConfigurationErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DescribeDevicePolicyConfigurationError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DescribeDevicePolicyConfigurationErrorKind::InternalServerErrorException(_inner) => { _inner.fmt(f) } DescribeDevicePolicyConfigurationErrorKind::InvalidRequestException(_inner) => { _inner.fmt(f) } DescribeDevicePolicyConfigurationErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } DescribeDevicePolicyConfigurationErrorKind::TooManyRequestsException(_inner) => { _inner.fmt(f) } DescribeDevicePolicyConfigurationErrorKind::UnauthorizedException(_inner) => { _inner.fmt(f) } DescribeDevicePolicyConfigurationErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DescribeDevicePolicyConfigurationError { fn code(&self) -> Option<&str> { DescribeDevicePolicyConfigurationError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DescribeDevicePolicyConfigurationError { /// Creates a new `DescribeDevicePolicyConfigurationError`. pub fn new( kind: DescribeDevicePolicyConfigurationErrorKind, meta: aws_smithy_types::Error, ) -> Self { Self { kind, meta } } /// Creates the `DescribeDevicePolicyConfigurationError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DescribeDevicePolicyConfigurationErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DescribeDevicePolicyConfigurationError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DescribeDevicePolicyConfigurationErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DescribeDevicePolicyConfigurationErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, DescribeDevicePolicyConfigurationErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `DescribeDevicePolicyConfigurationErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DescribeDevicePolicyConfigurationErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DescribeDevicePolicyConfigurationErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DescribeDevicePolicyConfigurationErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DescribeDevicePolicyConfigurationErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, DescribeDevicePolicyConfigurationErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `DescribeDevicePolicyConfigurationErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!( &self.kind, DescribeDevicePolicyConfigurationErrorKind::UnauthorizedException(_) ) } } impl std::error::Error for DescribeDevicePolicyConfigurationError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DescribeDevicePolicyConfigurationErrorKind::InternalServerErrorException(_inner) => { Some(_inner) } DescribeDevicePolicyConfigurationErrorKind::InvalidRequestException(_inner) => { Some(_inner) } DescribeDevicePolicyConfigurationErrorKind::ResourceNotFoundException(_inner) => { Some(_inner) } DescribeDevicePolicyConfigurationErrorKind::TooManyRequestsException(_inner) => { Some(_inner) } DescribeDevicePolicyConfigurationErrorKind::UnauthorizedException(_inner) => { Some(_inner) } DescribeDevicePolicyConfigurationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DescribeDomain` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DescribeDomainError { /// Kind of error that occurred. pub kind: DescribeDomainErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DescribeDomain` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DescribeDomainErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DescribeDomainError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DescribeDomainErrorKind::InternalServerErrorException(_inner) => _inner.fmt(f), DescribeDomainErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DescribeDomainErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), DescribeDomainErrorKind::TooManyRequestsException(_inner) => _inner.fmt(f), DescribeDomainErrorKind::UnauthorizedException(_inner) => _inner.fmt(f), DescribeDomainErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DescribeDomainError { fn code(&self) -> Option<&str> { DescribeDomainError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DescribeDomainError { /// Creates a new `DescribeDomainError`. pub fn new(kind: DescribeDomainErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DescribeDomainError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DescribeDomainErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DescribeDomainError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DescribeDomainErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DescribeDomainErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, DescribeDomainErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `DescribeDomainErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DescribeDomainErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DescribeDomainErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DescribeDomainErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DescribeDomainErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, DescribeDomainErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `DescribeDomainErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!( &self.kind, DescribeDomainErrorKind::UnauthorizedException(_) ) } } impl std::error::Error for DescribeDomainError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DescribeDomainErrorKind::InternalServerErrorException(_inner) => Some(_inner), DescribeDomainErrorKind::InvalidRequestException(_inner) => Some(_inner), DescribeDomainErrorKind::ResourceNotFoundException(_inner) => Some(_inner), DescribeDomainErrorKind::TooManyRequestsException(_inner) => Some(_inner), DescribeDomainErrorKind::UnauthorizedException(_inner) => Some(_inner), DescribeDomainErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DescribeFleetMetadata` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DescribeFleetMetadataError { /// Kind of error that occurred. pub kind: DescribeFleetMetadataErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DescribeFleetMetadata` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DescribeFleetMetadataErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DescribeFleetMetadataError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DescribeFleetMetadataErrorKind::InternalServerErrorException(_inner) => _inner.fmt(f), DescribeFleetMetadataErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DescribeFleetMetadataErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), DescribeFleetMetadataErrorKind::TooManyRequestsException(_inner) => _inner.fmt(f), DescribeFleetMetadataErrorKind::UnauthorizedException(_inner) => _inner.fmt(f), DescribeFleetMetadataErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DescribeFleetMetadataError { fn code(&self) -> Option<&str> { DescribeFleetMetadataError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DescribeFleetMetadataError { /// Creates a new `DescribeFleetMetadataError`. pub fn new(kind: DescribeFleetMetadataErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DescribeFleetMetadataError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DescribeFleetMetadataErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DescribeFleetMetadataError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DescribeFleetMetadataErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DescribeFleetMetadataErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, DescribeFleetMetadataErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `DescribeFleetMetadataErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DescribeFleetMetadataErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DescribeFleetMetadataErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DescribeFleetMetadataErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DescribeFleetMetadataErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, DescribeFleetMetadataErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `DescribeFleetMetadataErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!( &self.kind, DescribeFleetMetadataErrorKind::UnauthorizedException(_) ) } } impl std::error::Error for DescribeFleetMetadataError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DescribeFleetMetadataErrorKind::InternalServerErrorException(_inner) => Some(_inner), DescribeFleetMetadataErrorKind::InvalidRequestException(_inner) => Some(_inner), DescribeFleetMetadataErrorKind::ResourceNotFoundException(_inner) => Some(_inner), DescribeFleetMetadataErrorKind::TooManyRequestsException(_inner) => Some(_inner), DescribeFleetMetadataErrorKind::UnauthorizedException(_inner) => Some(_inner), DescribeFleetMetadataErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DescribeIdentityProviderConfiguration` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DescribeIdentityProviderConfigurationError { /// Kind of error that occurred. pub kind: DescribeIdentityProviderConfigurationErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DescribeIdentityProviderConfiguration` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DescribeIdentityProviderConfigurationErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DescribeIdentityProviderConfigurationError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DescribeIdentityProviderConfigurationErrorKind::InternalServerErrorException( _inner, ) => _inner.fmt(f), DescribeIdentityProviderConfigurationErrorKind::InvalidRequestException(_inner) => { _inner.fmt(f) } DescribeIdentityProviderConfigurationErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } DescribeIdentityProviderConfigurationErrorKind::TooManyRequestsException(_inner) => { _inner.fmt(f) } DescribeIdentityProviderConfigurationErrorKind::UnauthorizedException(_inner) => { _inner.fmt(f) } DescribeIdentityProviderConfigurationErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DescribeIdentityProviderConfigurationError { fn code(&self) -> Option<&str> { DescribeIdentityProviderConfigurationError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DescribeIdentityProviderConfigurationError { /// Creates a new `DescribeIdentityProviderConfigurationError`. pub fn new( kind: DescribeIdentityProviderConfigurationErrorKind, meta: aws_smithy_types::Error, ) -> Self { Self { kind, meta } } /// Creates the `DescribeIdentityProviderConfigurationError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DescribeIdentityProviderConfigurationErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DescribeIdentityProviderConfigurationError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DescribeIdentityProviderConfigurationErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DescribeIdentityProviderConfigurationErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, DescribeIdentityProviderConfigurationErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `DescribeIdentityProviderConfigurationErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DescribeIdentityProviderConfigurationErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DescribeIdentityProviderConfigurationErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DescribeIdentityProviderConfigurationErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DescribeIdentityProviderConfigurationErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, DescribeIdentityProviderConfigurationErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `DescribeIdentityProviderConfigurationErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!( &self.kind, DescribeIdentityProviderConfigurationErrorKind::UnauthorizedException(_) ) } } impl std::error::Error for DescribeIdentityProviderConfigurationError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DescribeIdentityProviderConfigurationErrorKind::InternalServerErrorException( _inner, ) => Some(_inner), DescribeIdentityProviderConfigurationErrorKind::InvalidRequestException(_inner) => { Some(_inner) } DescribeIdentityProviderConfigurationErrorKind::ResourceNotFoundException(_inner) => { Some(_inner) } DescribeIdentityProviderConfigurationErrorKind::TooManyRequestsException(_inner) => { Some(_inner) } DescribeIdentityProviderConfigurationErrorKind::UnauthorizedException(_inner) => { Some(_inner) } DescribeIdentityProviderConfigurationErrorKind::Unhandled(_inner) => { Some(_inner.as_ref()) } } } } /// Error type for the `DescribeWebsiteCertificateAuthority` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DescribeWebsiteCertificateAuthorityError { /// Kind of error that occurred. pub kind: DescribeWebsiteCertificateAuthorityErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DescribeWebsiteCertificateAuthority` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DescribeWebsiteCertificateAuthorityErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DescribeWebsiteCertificateAuthorityError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DescribeWebsiteCertificateAuthorityErrorKind::InternalServerErrorException(_inner) => { _inner.fmt(f) } DescribeWebsiteCertificateAuthorityErrorKind::InvalidRequestException(_inner) => { _inner.fmt(f) } DescribeWebsiteCertificateAuthorityErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } DescribeWebsiteCertificateAuthorityErrorKind::TooManyRequestsException(_inner) => { _inner.fmt(f) } DescribeWebsiteCertificateAuthorityErrorKind::UnauthorizedException(_inner) => { _inner.fmt(f) } DescribeWebsiteCertificateAuthorityErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DescribeWebsiteCertificateAuthorityError { fn code(&self) -> Option<&str> { DescribeWebsiteCertificateAuthorityError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DescribeWebsiteCertificateAuthorityError { /// Creates a new `DescribeWebsiteCertificateAuthorityError`. pub fn new( kind: DescribeWebsiteCertificateAuthorityErrorKind, meta: aws_smithy_types::Error, ) -> Self { Self { kind, meta } } /// Creates the `DescribeWebsiteCertificateAuthorityError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DescribeWebsiteCertificateAuthorityErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DescribeWebsiteCertificateAuthorityError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DescribeWebsiteCertificateAuthorityErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DescribeWebsiteCertificateAuthorityErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, DescribeWebsiteCertificateAuthorityErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `DescribeWebsiteCertificateAuthorityErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DescribeWebsiteCertificateAuthorityErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DescribeWebsiteCertificateAuthorityErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DescribeWebsiteCertificateAuthorityErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DescribeWebsiteCertificateAuthorityErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, DescribeWebsiteCertificateAuthorityErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `DescribeWebsiteCertificateAuthorityErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!( &self.kind, DescribeWebsiteCertificateAuthorityErrorKind::UnauthorizedException(_) ) } } impl std::error::Error for DescribeWebsiteCertificateAuthorityError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DescribeWebsiteCertificateAuthorityErrorKind::InternalServerErrorException(_inner) => { Some(_inner) } DescribeWebsiteCertificateAuthorityErrorKind::InvalidRequestException(_inner) => { Some(_inner) } DescribeWebsiteCertificateAuthorityErrorKind::ResourceNotFoundException(_inner) => { Some(_inner) } DescribeWebsiteCertificateAuthorityErrorKind::TooManyRequestsException(_inner) => { Some(_inner) } DescribeWebsiteCertificateAuthorityErrorKind::UnauthorizedException(_inner) => { Some(_inner) } DescribeWebsiteCertificateAuthorityErrorKind::Unhandled(_inner) => { Some(_inner.as_ref()) } } } } /// Error type for the `DisassociateDomain` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DisassociateDomainError { /// Kind of error that occurred. pub kind: DisassociateDomainErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DisassociateDomain` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DisassociateDomainErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DisassociateDomainError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DisassociateDomainErrorKind::InternalServerErrorException(_inner) => _inner.fmt(f), DisassociateDomainErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DisassociateDomainErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), DisassociateDomainErrorKind::TooManyRequestsException(_inner) => _inner.fmt(f), DisassociateDomainErrorKind::UnauthorizedException(_inner) => _inner.fmt(f), DisassociateDomainErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DisassociateDomainError { fn code(&self) -> Option<&str> { DisassociateDomainError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DisassociateDomainError { /// Creates a new `DisassociateDomainError`. pub fn new(kind: DisassociateDomainErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DisassociateDomainError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DisassociateDomainErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DisassociateDomainError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DisassociateDomainErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DisassociateDomainErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, DisassociateDomainErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `DisassociateDomainErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DisassociateDomainErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DisassociateDomainErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DisassociateDomainErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DisassociateDomainErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, DisassociateDomainErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `DisassociateDomainErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!( &self.kind, DisassociateDomainErrorKind::UnauthorizedException(_) ) } } impl std::error::Error for DisassociateDomainError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DisassociateDomainErrorKind::InternalServerErrorException(_inner) => Some(_inner), DisassociateDomainErrorKind::InvalidRequestException(_inner) => Some(_inner), DisassociateDomainErrorKind::ResourceNotFoundException(_inner) => Some(_inner), DisassociateDomainErrorKind::TooManyRequestsException(_inner) => Some(_inner), DisassociateDomainErrorKind::UnauthorizedException(_inner) => Some(_inner), DisassociateDomainErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DisassociateWebsiteAuthorizationProvider` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DisassociateWebsiteAuthorizationProviderError { /// Kind of error that occurred. pub kind: DisassociateWebsiteAuthorizationProviderErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DisassociateWebsiteAuthorizationProvider` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DisassociateWebsiteAuthorizationProviderErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The resource already exists.</p> ResourceAlreadyExistsException(crate::error::ResourceAlreadyExistsException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DisassociateWebsiteAuthorizationProviderError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DisassociateWebsiteAuthorizationProviderErrorKind::InternalServerErrorException( _inner, ) => _inner.fmt(f), DisassociateWebsiteAuthorizationProviderErrorKind::InvalidRequestException(_inner) => { _inner.fmt(f) } DisassociateWebsiteAuthorizationProviderErrorKind::ResourceAlreadyExistsException( _inner, ) => _inner.fmt(f), DisassociateWebsiteAuthorizationProviderErrorKind::ResourceNotFoundException( _inner, ) => _inner.fmt(f), DisassociateWebsiteAuthorizationProviderErrorKind::TooManyRequestsException(_inner) => { _inner.fmt(f) } DisassociateWebsiteAuthorizationProviderErrorKind::UnauthorizedException(_inner) => { _inner.fmt(f) } DisassociateWebsiteAuthorizationProviderErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DisassociateWebsiteAuthorizationProviderError { fn code(&self) -> Option<&str> { DisassociateWebsiteAuthorizationProviderError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DisassociateWebsiteAuthorizationProviderError { /// Creates a new `DisassociateWebsiteAuthorizationProviderError`. pub fn new( kind: DisassociateWebsiteAuthorizationProviderErrorKind, meta: aws_smithy_types::Error, ) -> Self { Self { kind, meta } } /// Creates the `DisassociateWebsiteAuthorizationProviderError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DisassociateWebsiteAuthorizationProviderErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DisassociateWebsiteAuthorizationProviderError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DisassociateWebsiteAuthorizationProviderErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DisassociateWebsiteAuthorizationProviderErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, DisassociateWebsiteAuthorizationProviderErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `DisassociateWebsiteAuthorizationProviderErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DisassociateWebsiteAuthorizationProviderErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DisassociateWebsiteAuthorizationProviderErrorKind::ResourceAlreadyExistsException`. pub fn is_resource_already_exists_exception(&self) -> bool { matches!( &self.kind, DisassociateWebsiteAuthorizationProviderErrorKind::ResourceAlreadyExistsException(_) ) } /// Returns `true` if the error kind is `DisassociateWebsiteAuthorizationProviderErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DisassociateWebsiteAuthorizationProviderErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DisassociateWebsiteAuthorizationProviderErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, DisassociateWebsiteAuthorizationProviderErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `DisassociateWebsiteAuthorizationProviderErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!( &self.kind, DisassociateWebsiteAuthorizationProviderErrorKind::UnauthorizedException(_) ) } } impl std::error::Error for DisassociateWebsiteAuthorizationProviderError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DisassociateWebsiteAuthorizationProviderErrorKind::InternalServerErrorException( _inner, ) => Some(_inner), DisassociateWebsiteAuthorizationProviderErrorKind::InvalidRequestException(_inner) => { Some(_inner) } DisassociateWebsiteAuthorizationProviderErrorKind::ResourceAlreadyExistsException( _inner, ) => Some(_inner), DisassociateWebsiteAuthorizationProviderErrorKind::ResourceNotFoundException( _inner, ) => Some(_inner), DisassociateWebsiteAuthorizationProviderErrorKind::TooManyRequestsException(_inner) => { Some(_inner) } DisassociateWebsiteAuthorizationProviderErrorKind::UnauthorizedException(_inner) => { Some(_inner) } DisassociateWebsiteAuthorizationProviderErrorKind::Unhandled(_inner) => { Some(_inner.as_ref()) } } } } /// Error type for the `DisassociateWebsiteCertificateAuthority` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DisassociateWebsiteCertificateAuthorityError { /// Kind of error that occurred. pub kind: DisassociateWebsiteCertificateAuthorityErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DisassociateWebsiteCertificateAuthority` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DisassociateWebsiteCertificateAuthorityErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DisassociateWebsiteCertificateAuthorityError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DisassociateWebsiteCertificateAuthorityErrorKind::InternalServerErrorException( _inner, ) => _inner.fmt(f), DisassociateWebsiteCertificateAuthorityErrorKind::InvalidRequestException(_inner) => { _inner.fmt(f) } DisassociateWebsiteCertificateAuthorityErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } DisassociateWebsiteCertificateAuthorityErrorKind::TooManyRequestsException(_inner) => { _inner.fmt(f) } DisassociateWebsiteCertificateAuthorityErrorKind::UnauthorizedException(_inner) => { _inner.fmt(f) } DisassociateWebsiteCertificateAuthorityErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DisassociateWebsiteCertificateAuthorityError { fn code(&self) -> Option<&str> { DisassociateWebsiteCertificateAuthorityError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DisassociateWebsiteCertificateAuthorityError { /// Creates a new `DisassociateWebsiteCertificateAuthorityError`. pub fn new( kind: DisassociateWebsiteCertificateAuthorityErrorKind, meta: aws_smithy_types::Error, ) -> Self { Self { kind, meta } } /// Creates the `DisassociateWebsiteCertificateAuthorityError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DisassociateWebsiteCertificateAuthorityErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DisassociateWebsiteCertificateAuthorityError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DisassociateWebsiteCertificateAuthorityErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DisassociateWebsiteCertificateAuthorityErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, DisassociateWebsiteCertificateAuthorityErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `DisassociateWebsiteCertificateAuthorityErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DisassociateWebsiteCertificateAuthorityErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DisassociateWebsiteCertificateAuthorityErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DisassociateWebsiteCertificateAuthorityErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DisassociateWebsiteCertificateAuthorityErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, DisassociateWebsiteCertificateAuthorityErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `DisassociateWebsiteCertificateAuthorityErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!( &self.kind, DisassociateWebsiteCertificateAuthorityErrorKind::UnauthorizedException(_) ) } } impl std::error::Error for DisassociateWebsiteCertificateAuthorityError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DisassociateWebsiteCertificateAuthorityErrorKind::InternalServerErrorException( _inner, ) => Some(_inner), DisassociateWebsiteCertificateAuthorityErrorKind::InvalidRequestException(_inner) => { Some(_inner) } DisassociateWebsiteCertificateAuthorityErrorKind::ResourceNotFoundException(_inner) => { Some(_inner) } DisassociateWebsiteCertificateAuthorityErrorKind::TooManyRequestsException(_inner) => { Some(_inner) } DisassociateWebsiteCertificateAuthorityErrorKind::UnauthorizedException(_inner) => { Some(_inner) } DisassociateWebsiteCertificateAuthorityErrorKind::Unhandled(_inner) => { Some(_inner.as_ref()) } } } } /// Error type for the `ListDevices` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListDevicesError { /// Kind of error that occurred. pub kind: ListDevicesErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListDevices` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListDevicesErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListDevicesError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListDevicesErrorKind::InternalServerErrorException(_inner) => _inner.fmt(f), ListDevicesErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListDevicesErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), ListDevicesErrorKind::TooManyRequestsException(_inner) => _inner.fmt(f), ListDevicesErrorKind::UnauthorizedException(_inner) => _inner.fmt(f), ListDevicesErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListDevicesError { fn code(&self) -> Option<&str> { ListDevicesError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListDevicesError { /// Creates a new `ListDevicesError`. pub fn new(kind: ListDevicesErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListDevicesError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListDevicesErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListDevicesError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListDevicesErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListDevicesErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, ListDevicesErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `ListDevicesErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!(&self.kind, ListDevicesErrorKind::InvalidRequestException(_)) } /// Returns `true` if the error kind is `ListDevicesErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, ListDevicesErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `ListDevicesErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, ListDevicesErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `ListDevicesErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!(&self.kind, ListDevicesErrorKind::UnauthorizedException(_)) } } impl std::error::Error for ListDevicesError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListDevicesErrorKind::InternalServerErrorException(_inner) => Some(_inner), ListDevicesErrorKind::InvalidRequestException(_inner) => Some(_inner), ListDevicesErrorKind::ResourceNotFoundException(_inner) => Some(_inner), ListDevicesErrorKind::TooManyRequestsException(_inner) => Some(_inner), ListDevicesErrorKind::UnauthorizedException(_inner) => Some(_inner), ListDevicesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListDomains` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListDomainsError { /// Kind of error that occurred. pub kind: ListDomainsErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListDomains` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListDomainsErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListDomainsError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListDomainsErrorKind::InternalServerErrorException(_inner) => _inner.fmt(f), ListDomainsErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListDomainsErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), ListDomainsErrorKind::TooManyRequestsException(_inner) => _inner.fmt(f), ListDomainsErrorKind::UnauthorizedException(_inner) => _inner.fmt(f), ListDomainsErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListDomainsError { fn code(&self) -> Option<&str> { ListDomainsError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListDomainsError { /// Creates a new `ListDomainsError`. pub fn new(kind: ListDomainsErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListDomainsError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListDomainsErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListDomainsError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListDomainsErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListDomainsErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, ListDomainsErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `ListDomainsErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!(&self.kind, ListDomainsErrorKind::InvalidRequestException(_)) } /// Returns `true` if the error kind is `ListDomainsErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, ListDomainsErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `ListDomainsErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, ListDomainsErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `ListDomainsErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!(&self.kind, ListDomainsErrorKind::UnauthorizedException(_)) } } impl std::error::Error for ListDomainsError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListDomainsErrorKind::InternalServerErrorException(_inner) => Some(_inner), ListDomainsErrorKind::InvalidRequestException(_inner) => Some(_inner), ListDomainsErrorKind::ResourceNotFoundException(_inner) => Some(_inner), ListDomainsErrorKind::TooManyRequestsException(_inner) => Some(_inner), ListDomainsErrorKind::UnauthorizedException(_inner) => Some(_inner), ListDomainsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListFleets` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListFleetsError { /// Kind of error that occurred. pub kind: ListFleetsErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListFleets` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListFleetsErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListFleetsError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListFleetsErrorKind::InternalServerErrorException(_inner) => _inner.fmt(f), ListFleetsErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListFleetsErrorKind::TooManyRequestsException(_inner) => _inner.fmt(f), ListFleetsErrorKind::UnauthorizedException(_inner) => _inner.fmt(f), ListFleetsErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListFleetsError { fn code(&self) -> Option<&str> { ListFleetsError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListFleetsError { /// Creates a new `ListFleetsError`. pub fn new(kind: ListFleetsErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListFleetsError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListFleetsErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListFleetsError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListFleetsErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListFleetsErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, ListFleetsErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `ListFleetsErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!(&self.kind, ListFleetsErrorKind::InvalidRequestException(_)) } /// Returns `true` if the error kind is `ListFleetsErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!(&self.kind, ListFleetsErrorKind::TooManyRequestsException(_)) } /// Returns `true` if the error kind is `ListFleetsErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!(&self.kind, ListFleetsErrorKind::UnauthorizedException(_)) } } impl std::error::Error for ListFleetsError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListFleetsErrorKind::InternalServerErrorException(_inner) => Some(_inner), ListFleetsErrorKind::InvalidRequestException(_inner) => Some(_inner), ListFleetsErrorKind::TooManyRequestsException(_inner) => Some(_inner), ListFleetsErrorKind::UnauthorizedException(_inner) => Some(_inner), ListFleetsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListTagsForResource` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListTagsForResourceError { /// Kind of error that occurred. pub kind: ListTagsForResourceErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListTagsForResource` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListTagsForResourceErrorKind { /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListTagsForResourceError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListTagsForResourceErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListTagsForResourceErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListTagsForResourceError { fn code(&self) -> Option<&str> { ListTagsForResourceError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListTagsForResourceError { /// Creates a new `ListTagsForResourceError`. pub fn new(kind: ListTagsForResourceErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListTagsForResourceError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListTagsForResourceErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListTagsForResourceError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListTagsForResourceErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListTagsForResourceErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, ListTagsForResourceErrorKind::InvalidRequestException(_) ) } } impl std::error::Error for ListTagsForResourceError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListTagsForResourceErrorKind::InvalidRequestException(_inner) => Some(_inner), ListTagsForResourceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListWebsiteAuthorizationProviders` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListWebsiteAuthorizationProvidersError { /// Kind of error that occurred. pub kind: ListWebsiteAuthorizationProvidersErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListWebsiteAuthorizationProviders` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListWebsiteAuthorizationProvidersErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListWebsiteAuthorizationProvidersError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListWebsiteAuthorizationProvidersErrorKind::InternalServerErrorException(_inner) => { _inner.fmt(f) } ListWebsiteAuthorizationProvidersErrorKind::InvalidRequestException(_inner) => { _inner.fmt(f) } ListWebsiteAuthorizationProvidersErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } ListWebsiteAuthorizationProvidersErrorKind::TooManyRequestsException(_inner) => { _inner.fmt(f) } ListWebsiteAuthorizationProvidersErrorKind::UnauthorizedException(_inner) => { _inner.fmt(f) } ListWebsiteAuthorizationProvidersErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListWebsiteAuthorizationProvidersError { fn code(&self) -> Option<&str> { ListWebsiteAuthorizationProvidersError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListWebsiteAuthorizationProvidersError { /// Creates a new `ListWebsiteAuthorizationProvidersError`. pub fn new( kind: ListWebsiteAuthorizationProvidersErrorKind, meta: aws_smithy_types::Error, ) -> Self { Self { kind, meta } } /// Creates the `ListWebsiteAuthorizationProvidersError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListWebsiteAuthorizationProvidersErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListWebsiteAuthorizationProvidersError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListWebsiteAuthorizationProvidersErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListWebsiteAuthorizationProvidersErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, ListWebsiteAuthorizationProvidersErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `ListWebsiteAuthorizationProvidersErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, ListWebsiteAuthorizationProvidersErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `ListWebsiteAuthorizationProvidersErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, ListWebsiteAuthorizationProvidersErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `ListWebsiteAuthorizationProvidersErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, ListWebsiteAuthorizationProvidersErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `ListWebsiteAuthorizationProvidersErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!( &self.kind, ListWebsiteAuthorizationProvidersErrorKind::UnauthorizedException(_) ) } } impl std::error::Error for ListWebsiteAuthorizationProvidersError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListWebsiteAuthorizationProvidersErrorKind::InternalServerErrorException(_inner) => { Some(_inner) } ListWebsiteAuthorizationProvidersErrorKind::InvalidRequestException(_inner) => { Some(_inner) } ListWebsiteAuthorizationProvidersErrorKind::ResourceNotFoundException(_inner) => { Some(_inner) } ListWebsiteAuthorizationProvidersErrorKind::TooManyRequestsException(_inner) => { Some(_inner) } ListWebsiteAuthorizationProvidersErrorKind::UnauthorizedException(_inner) => { Some(_inner) } ListWebsiteAuthorizationProvidersErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListWebsiteCertificateAuthorities` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListWebsiteCertificateAuthoritiesError { /// Kind of error that occurred. pub kind: ListWebsiteCertificateAuthoritiesErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListWebsiteCertificateAuthorities` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListWebsiteCertificateAuthoritiesErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListWebsiteCertificateAuthoritiesError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListWebsiteCertificateAuthoritiesErrorKind::InternalServerErrorException(_inner) => { _inner.fmt(f) } ListWebsiteCertificateAuthoritiesErrorKind::InvalidRequestException(_inner) => { _inner.fmt(f) } ListWebsiteCertificateAuthoritiesErrorKind::TooManyRequestsException(_inner) => { _inner.fmt(f) } ListWebsiteCertificateAuthoritiesErrorKind::UnauthorizedException(_inner) => { _inner.fmt(f) } ListWebsiteCertificateAuthoritiesErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListWebsiteCertificateAuthoritiesError { fn code(&self) -> Option<&str> { ListWebsiteCertificateAuthoritiesError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListWebsiteCertificateAuthoritiesError { /// Creates a new `ListWebsiteCertificateAuthoritiesError`. pub fn new( kind: ListWebsiteCertificateAuthoritiesErrorKind, meta: aws_smithy_types::Error, ) -> Self { Self { kind, meta } } /// Creates the `ListWebsiteCertificateAuthoritiesError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListWebsiteCertificateAuthoritiesErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListWebsiteCertificateAuthoritiesError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListWebsiteCertificateAuthoritiesErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListWebsiteCertificateAuthoritiesErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, ListWebsiteCertificateAuthoritiesErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `ListWebsiteCertificateAuthoritiesErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, ListWebsiteCertificateAuthoritiesErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `ListWebsiteCertificateAuthoritiesErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, ListWebsiteCertificateAuthoritiesErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `ListWebsiteCertificateAuthoritiesErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!( &self.kind, ListWebsiteCertificateAuthoritiesErrorKind::UnauthorizedException(_) ) } } impl std::error::Error for ListWebsiteCertificateAuthoritiesError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListWebsiteCertificateAuthoritiesErrorKind::InternalServerErrorException(_inner) => { Some(_inner) } ListWebsiteCertificateAuthoritiesErrorKind::InvalidRequestException(_inner) => { Some(_inner) } ListWebsiteCertificateAuthoritiesErrorKind::TooManyRequestsException(_inner) => { Some(_inner) } ListWebsiteCertificateAuthoritiesErrorKind::UnauthorizedException(_inner) => { Some(_inner) } ListWebsiteCertificateAuthoritiesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `RestoreDomainAccess` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct RestoreDomainAccessError { /// Kind of error that occurred. pub kind: RestoreDomainAccessErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `RestoreDomainAccess` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum RestoreDomainAccessErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for RestoreDomainAccessError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { RestoreDomainAccessErrorKind::InternalServerErrorException(_inner) => _inner.fmt(f), RestoreDomainAccessErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), RestoreDomainAccessErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), RestoreDomainAccessErrorKind::TooManyRequestsException(_inner) => _inner.fmt(f), RestoreDomainAccessErrorKind::UnauthorizedException(_inner) => _inner.fmt(f), RestoreDomainAccessErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for RestoreDomainAccessError { fn code(&self) -> Option<&str> { RestoreDomainAccessError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl RestoreDomainAccessError { /// Creates a new `RestoreDomainAccessError`. pub fn new(kind: RestoreDomainAccessErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `RestoreDomainAccessError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: RestoreDomainAccessErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `RestoreDomainAccessError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: RestoreDomainAccessErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `RestoreDomainAccessErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, RestoreDomainAccessErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `RestoreDomainAccessErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, RestoreDomainAccessErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `RestoreDomainAccessErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, RestoreDomainAccessErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `RestoreDomainAccessErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, RestoreDomainAccessErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `RestoreDomainAccessErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!( &self.kind, RestoreDomainAccessErrorKind::UnauthorizedException(_) ) } } impl std::error::Error for RestoreDomainAccessError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { RestoreDomainAccessErrorKind::InternalServerErrorException(_inner) => Some(_inner), RestoreDomainAccessErrorKind::InvalidRequestException(_inner) => Some(_inner), RestoreDomainAccessErrorKind::ResourceNotFoundException(_inner) => Some(_inner), RestoreDomainAccessErrorKind::TooManyRequestsException(_inner) => Some(_inner), RestoreDomainAccessErrorKind::UnauthorizedException(_inner) => Some(_inner), RestoreDomainAccessErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `RevokeDomainAccess` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct RevokeDomainAccessError { /// Kind of error that occurred. pub kind: RevokeDomainAccessErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `RevokeDomainAccess` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum RevokeDomainAccessErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for RevokeDomainAccessError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { RevokeDomainAccessErrorKind::InternalServerErrorException(_inner) => _inner.fmt(f), RevokeDomainAccessErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), RevokeDomainAccessErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), RevokeDomainAccessErrorKind::TooManyRequestsException(_inner) => _inner.fmt(f), RevokeDomainAccessErrorKind::UnauthorizedException(_inner) => _inner.fmt(f), RevokeDomainAccessErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for RevokeDomainAccessError { fn code(&self) -> Option<&str> { RevokeDomainAccessError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl RevokeDomainAccessError { /// Creates a new `RevokeDomainAccessError`. pub fn new(kind: RevokeDomainAccessErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `RevokeDomainAccessError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: RevokeDomainAccessErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `RevokeDomainAccessError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: RevokeDomainAccessErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `RevokeDomainAccessErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, RevokeDomainAccessErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `RevokeDomainAccessErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, RevokeDomainAccessErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `RevokeDomainAccessErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, RevokeDomainAccessErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `RevokeDomainAccessErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, RevokeDomainAccessErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `RevokeDomainAccessErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!( &self.kind, RevokeDomainAccessErrorKind::UnauthorizedException(_) ) } } impl std::error::Error for RevokeDomainAccessError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { RevokeDomainAccessErrorKind::InternalServerErrorException(_inner) => Some(_inner), RevokeDomainAccessErrorKind::InvalidRequestException(_inner) => Some(_inner), RevokeDomainAccessErrorKind::ResourceNotFoundException(_inner) => Some(_inner), RevokeDomainAccessErrorKind::TooManyRequestsException(_inner) => Some(_inner), RevokeDomainAccessErrorKind::UnauthorizedException(_inner) => Some(_inner), RevokeDomainAccessErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `SignOutUser` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct SignOutUserError { /// Kind of error that occurred. pub kind: SignOutUserErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `SignOutUser` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum SignOutUserErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for SignOutUserError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { SignOutUserErrorKind::InternalServerErrorException(_inner) => _inner.fmt(f), SignOutUserErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), SignOutUserErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), SignOutUserErrorKind::TooManyRequestsException(_inner) => _inner.fmt(f), SignOutUserErrorKind::UnauthorizedException(_inner) => _inner.fmt(f), SignOutUserErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for SignOutUserError { fn code(&self) -> Option<&str> { SignOutUserError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl SignOutUserError { /// Creates a new `SignOutUserError`. pub fn new(kind: SignOutUserErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `SignOutUserError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: SignOutUserErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `SignOutUserError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: SignOutUserErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `SignOutUserErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, SignOutUserErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `SignOutUserErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!(&self.kind, SignOutUserErrorKind::InvalidRequestException(_)) } /// Returns `true` if the error kind is `SignOutUserErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, SignOutUserErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `SignOutUserErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, SignOutUserErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `SignOutUserErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!(&self.kind, SignOutUserErrorKind::UnauthorizedException(_)) } } impl std::error::Error for SignOutUserError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { SignOutUserErrorKind::InternalServerErrorException(_inner) => Some(_inner), SignOutUserErrorKind::InvalidRequestException(_inner) => Some(_inner), SignOutUserErrorKind::ResourceNotFoundException(_inner) => Some(_inner), SignOutUserErrorKind::TooManyRequestsException(_inner) => Some(_inner), SignOutUserErrorKind::UnauthorizedException(_inner) => Some(_inner), SignOutUserErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `TagResource` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct TagResourceError { /// Kind of error that occurred. pub kind: TagResourceErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `TagResource` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum TagResourceErrorKind { /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for TagResourceError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { TagResourceErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), TagResourceErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for TagResourceError { fn code(&self) -> Option<&str> { TagResourceError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl TagResourceError { /// Creates a new `TagResourceError`. pub fn new(kind: TagResourceErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `TagResourceError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: TagResourceErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `TagResourceError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: TagResourceErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `TagResourceErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!(&self.kind, TagResourceErrorKind::InvalidRequestException(_)) } } impl std::error::Error for TagResourceError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { TagResourceErrorKind::InvalidRequestException(_inner) => Some(_inner), TagResourceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UntagResource` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UntagResourceError { /// Kind of error that occurred. pub kind: UntagResourceErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UntagResource` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UntagResourceErrorKind { /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UntagResourceError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UntagResourceErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), UntagResourceErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UntagResourceError { fn code(&self) -> Option<&str> { UntagResourceError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UntagResourceError { /// Creates a new `UntagResourceError`. pub fn new(kind: UntagResourceErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UntagResourceError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UntagResourceErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UntagResourceError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UntagResourceErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UntagResourceErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UntagResourceErrorKind::InvalidRequestException(_) ) } } impl std::error::Error for UntagResourceError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UntagResourceErrorKind::InvalidRequestException(_inner) => Some(_inner), UntagResourceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateAuditStreamConfiguration` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateAuditStreamConfigurationError { /// Kind of error that occurred. pub kind: UpdateAuditStreamConfigurationErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateAuditStreamConfiguration` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateAuditStreamConfigurationErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateAuditStreamConfigurationError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateAuditStreamConfigurationErrorKind::InternalServerErrorException(_inner) => { _inner.fmt(f) } UpdateAuditStreamConfigurationErrorKind::InvalidRequestException(_inner) => { _inner.fmt(f) } UpdateAuditStreamConfigurationErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } UpdateAuditStreamConfigurationErrorKind::TooManyRequestsException(_inner) => { _inner.fmt(f) } UpdateAuditStreamConfigurationErrorKind::UnauthorizedException(_inner) => _inner.fmt(f), UpdateAuditStreamConfigurationErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateAuditStreamConfigurationError { fn code(&self) -> Option<&str> { UpdateAuditStreamConfigurationError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateAuditStreamConfigurationError { /// Creates a new `UpdateAuditStreamConfigurationError`. pub fn new( kind: UpdateAuditStreamConfigurationErrorKind, meta: aws_smithy_types::Error, ) -> Self { Self { kind, meta } } /// Creates the `UpdateAuditStreamConfigurationError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateAuditStreamConfigurationErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateAuditStreamConfigurationError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateAuditStreamConfigurationErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateAuditStreamConfigurationErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, UpdateAuditStreamConfigurationErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `UpdateAuditStreamConfigurationErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateAuditStreamConfigurationErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateAuditStreamConfigurationErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateAuditStreamConfigurationErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateAuditStreamConfigurationErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, UpdateAuditStreamConfigurationErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `UpdateAuditStreamConfigurationErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!( &self.kind, UpdateAuditStreamConfigurationErrorKind::UnauthorizedException(_) ) } } impl std::error::Error for UpdateAuditStreamConfigurationError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateAuditStreamConfigurationErrorKind::InternalServerErrorException(_inner) => { Some(_inner) } UpdateAuditStreamConfigurationErrorKind::InvalidRequestException(_inner) => { Some(_inner) } UpdateAuditStreamConfigurationErrorKind::ResourceNotFoundException(_inner) => { Some(_inner) } UpdateAuditStreamConfigurationErrorKind::TooManyRequestsException(_inner) => { Some(_inner) } UpdateAuditStreamConfigurationErrorKind::UnauthorizedException(_inner) => Some(_inner), UpdateAuditStreamConfigurationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateCompanyNetworkConfiguration` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateCompanyNetworkConfigurationError { /// Kind of error that occurred. pub kind: UpdateCompanyNetworkConfigurationErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateCompanyNetworkConfiguration` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateCompanyNetworkConfigurationErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateCompanyNetworkConfigurationError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateCompanyNetworkConfigurationErrorKind::InternalServerErrorException(_inner) => { _inner.fmt(f) } UpdateCompanyNetworkConfigurationErrorKind::InvalidRequestException(_inner) => { _inner.fmt(f) } UpdateCompanyNetworkConfigurationErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } UpdateCompanyNetworkConfigurationErrorKind::TooManyRequestsException(_inner) => { _inner.fmt(f) } UpdateCompanyNetworkConfigurationErrorKind::UnauthorizedException(_inner) => { _inner.fmt(f) } UpdateCompanyNetworkConfigurationErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateCompanyNetworkConfigurationError { fn code(&self) -> Option<&str> { UpdateCompanyNetworkConfigurationError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateCompanyNetworkConfigurationError { /// Creates a new `UpdateCompanyNetworkConfigurationError`. pub fn new( kind: UpdateCompanyNetworkConfigurationErrorKind, meta: aws_smithy_types::Error, ) -> Self { Self { kind, meta } } /// Creates the `UpdateCompanyNetworkConfigurationError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateCompanyNetworkConfigurationErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateCompanyNetworkConfigurationError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateCompanyNetworkConfigurationErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateCompanyNetworkConfigurationErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, UpdateCompanyNetworkConfigurationErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `UpdateCompanyNetworkConfigurationErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateCompanyNetworkConfigurationErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateCompanyNetworkConfigurationErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateCompanyNetworkConfigurationErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateCompanyNetworkConfigurationErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, UpdateCompanyNetworkConfigurationErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `UpdateCompanyNetworkConfigurationErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!( &self.kind, UpdateCompanyNetworkConfigurationErrorKind::UnauthorizedException(_) ) } } impl std::error::Error for UpdateCompanyNetworkConfigurationError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateCompanyNetworkConfigurationErrorKind::InternalServerErrorException(_inner) => { Some(_inner) } UpdateCompanyNetworkConfigurationErrorKind::InvalidRequestException(_inner) => { Some(_inner) } UpdateCompanyNetworkConfigurationErrorKind::ResourceNotFoundException(_inner) => { Some(_inner) } UpdateCompanyNetworkConfigurationErrorKind::TooManyRequestsException(_inner) => { Some(_inner) } UpdateCompanyNetworkConfigurationErrorKind::UnauthorizedException(_inner) => { Some(_inner) } UpdateCompanyNetworkConfigurationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateDevicePolicyConfiguration` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateDevicePolicyConfigurationError { /// Kind of error that occurred. pub kind: UpdateDevicePolicyConfigurationErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateDevicePolicyConfiguration` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateDevicePolicyConfigurationErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateDevicePolicyConfigurationError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateDevicePolicyConfigurationErrorKind::InternalServerErrorException(_inner) => { _inner.fmt(f) } UpdateDevicePolicyConfigurationErrorKind::InvalidRequestException(_inner) => { _inner.fmt(f) } UpdateDevicePolicyConfigurationErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } UpdateDevicePolicyConfigurationErrorKind::TooManyRequestsException(_inner) => { _inner.fmt(f) } UpdateDevicePolicyConfigurationErrorKind::UnauthorizedException(_inner) => { _inner.fmt(f) } UpdateDevicePolicyConfigurationErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateDevicePolicyConfigurationError { fn code(&self) -> Option<&str> { UpdateDevicePolicyConfigurationError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateDevicePolicyConfigurationError { /// Creates a new `UpdateDevicePolicyConfigurationError`. pub fn new( kind: UpdateDevicePolicyConfigurationErrorKind, meta: aws_smithy_types::Error, ) -> Self { Self { kind, meta } } /// Creates the `UpdateDevicePolicyConfigurationError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateDevicePolicyConfigurationErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateDevicePolicyConfigurationError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateDevicePolicyConfigurationErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateDevicePolicyConfigurationErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, UpdateDevicePolicyConfigurationErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `UpdateDevicePolicyConfigurationErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateDevicePolicyConfigurationErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateDevicePolicyConfigurationErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateDevicePolicyConfigurationErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateDevicePolicyConfigurationErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, UpdateDevicePolicyConfigurationErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `UpdateDevicePolicyConfigurationErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!( &self.kind, UpdateDevicePolicyConfigurationErrorKind::UnauthorizedException(_) ) } } impl std::error::Error for UpdateDevicePolicyConfigurationError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateDevicePolicyConfigurationErrorKind::InternalServerErrorException(_inner) => { Some(_inner) } UpdateDevicePolicyConfigurationErrorKind::InvalidRequestException(_inner) => { Some(_inner) } UpdateDevicePolicyConfigurationErrorKind::ResourceNotFoundException(_inner) => { Some(_inner) } UpdateDevicePolicyConfigurationErrorKind::TooManyRequestsException(_inner) => { Some(_inner) } UpdateDevicePolicyConfigurationErrorKind::UnauthorizedException(_inner) => Some(_inner), UpdateDevicePolicyConfigurationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateDomainMetadata` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateDomainMetadataError { /// Kind of error that occurred. pub kind: UpdateDomainMetadataErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateDomainMetadata` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateDomainMetadataErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateDomainMetadataError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateDomainMetadataErrorKind::InternalServerErrorException(_inner) => _inner.fmt(f), UpdateDomainMetadataErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), UpdateDomainMetadataErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), UpdateDomainMetadataErrorKind::TooManyRequestsException(_inner) => _inner.fmt(f), UpdateDomainMetadataErrorKind::UnauthorizedException(_inner) => _inner.fmt(f), UpdateDomainMetadataErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateDomainMetadataError { fn code(&self) -> Option<&str> { UpdateDomainMetadataError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateDomainMetadataError { /// Creates a new `UpdateDomainMetadataError`. pub fn new(kind: UpdateDomainMetadataErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UpdateDomainMetadataError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateDomainMetadataErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateDomainMetadataError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateDomainMetadataErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateDomainMetadataErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, UpdateDomainMetadataErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `UpdateDomainMetadataErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateDomainMetadataErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateDomainMetadataErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateDomainMetadataErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateDomainMetadataErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, UpdateDomainMetadataErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `UpdateDomainMetadataErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!( &self.kind, UpdateDomainMetadataErrorKind::UnauthorizedException(_) ) } } impl std::error::Error for UpdateDomainMetadataError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateDomainMetadataErrorKind::InternalServerErrorException(_inner) => Some(_inner), UpdateDomainMetadataErrorKind::InvalidRequestException(_inner) => Some(_inner), UpdateDomainMetadataErrorKind::ResourceNotFoundException(_inner) => Some(_inner), UpdateDomainMetadataErrorKind::TooManyRequestsException(_inner) => Some(_inner), UpdateDomainMetadataErrorKind::UnauthorizedException(_inner) => Some(_inner), UpdateDomainMetadataErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateFleetMetadata` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateFleetMetadataError { /// Kind of error that occurred. pub kind: UpdateFleetMetadataErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateFleetMetadata` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateFleetMetadataErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateFleetMetadataError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateFleetMetadataErrorKind::InternalServerErrorException(_inner) => _inner.fmt(f), UpdateFleetMetadataErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), UpdateFleetMetadataErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), UpdateFleetMetadataErrorKind::TooManyRequestsException(_inner) => _inner.fmt(f), UpdateFleetMetadataErrorKind::UnauthorizedException(_inner) => _inner.fmt(f), UpdateFleetMetadataErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateFleetMetadataError { fn code(&self) -> Option<&str> { UpdateFleetMetadataError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateFleetMetadataError { /// Creates a new `UpdateFleetMetadataError`. pub fn new(kind: UpdateFleetMetadataErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UpdateFleetMetadataError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateFleetMetadataErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateFleetMetadataError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateFleetMetadataErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateFleetMetadataErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, UpdateFleetMetadataErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `UpdateFleetMetadataErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateFleetMetadataErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateFleetMetadataErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateFleetMetadataErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateFleetMetadataErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, UpdateFleetMetadataErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `UpdateFleetMetadataErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!( &self.kind, UpdateFleetMetadataErrorKind::UnauthorizedException(_) ) } } impl std::error::Error for UpdateFleetMetadataError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateFleetMetadataErrorKind::InternalServerErrorException(_inner) => Some(_inner), UpdateFleetMetadataErrorKind::InvalidRequestException(_inner) => Some(_inner), UpdateFleetMetadataErrorKind::ResourceNotFoundException(_inner) => Some(_inner), UpdateFleetMetadataErrorKind::TooManyRequestsException(_inner) => Some(_inner), UpdateFleetMetadataErrorKind::UnauthorizedException(_inner) => Some(_inner), UpdateFleetMetadataErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateIdentityProviderConfiguration` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateIdentityProviderConfigurationError { /// Kind of error that occurred. pub kind: UpdateIdentityProviderConfigurationErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateIdentityProviderConfiguration` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateIdentityProviderConfigurationErrorKind { /// <p>The service is temporarily unavailable.</p> InternalServerErrorException(crate::error::InternalServerErrorException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The requested resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The number of requests exceeds the limit.</p> TooManyRequestsException(crate::error::TooManyRequestsException), /// <p>You are not authorized to perform this action.</p> UnauthorizedException(crate::error::UnauthorizedException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateIdentityProviderConfigurationError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateIdentityProviderConfigurationErrorKind::InternalServerErrorException(_inner) => { _inner.fmt(f) } UpdateIdentityProviderConfigurationErrorKind::InvalidRequestException(_inner) => { _inner.fmt(f) } UpdateIdentityProviderConfigurationErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } UpdateIdentityProviderConfigurationErrorKind::TooManyRequestsException(_inner) => { _inner.fmt(f) } UpdateIdentityProviderConfigurationErrorKind::UnauthorizedException(_inner) => { _inner.fmt(f) } UpdateIdentityProviderConfigurationErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateIdentityProviderConfigurationError { fn code(&self) -> Option<&str> { UpdateIdentityProviderConfigurationError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateIdentityProviderConfigurationError { /// Creates a new `UpdateIdentityProviderConfigurationError`. pub fn new( kind: UpdateIdentityProviderConfigurationErrorKind, meta: aws_smithy_types::Error, ) -> Self { Self { kind, meta } } /// Creates the `UpdateIdentityProviderConfigurationError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateIdentityProviderConfigurationErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateIdentityProviderConfigurationError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateIdentityProviderConfigurationErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateIdentityProviderConfigurationErrorKind::InternalServerErrorException`. pub fn is_internal_server_error_exception(&self) -> bool { matches!( &self.kind, UpdateIdentityProviderConfigurationErrorKind::InternalServerErrorException(_) ) } /// Returns `true` if the error kind is `UpdateIdentityProviderConfigurationErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateIdentityProviderConfigurationErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateIdentityProviderConfigurationErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateIdentityProviderConfigurationErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateIdentityProviderConfigurationErrorKind::TooManyRequestsException`. pub fn is_too_many_requests_exception(&self) -> bool { matches!( &self.kind, UpdateIdentityProviderConfigurationErrorKind::TooManyRequestsException(_) ) } /// Returns `true` if the error kind is `UpdateIdentityProviderConfigurationErrorKind::UnauthorizedException`. pub fn is_unauthorized_exception(&self) -> bool { matches!( &self.kind, UpdateIdentityProviderConfigurationErrorKind::UnauthorizedException(_) ) } } impl std::error::Error for UpdateIdentityProviderConfigurationError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateIdentityProviderConfigurationErrorKind::InternalServerErrorException(_inner) => { Some(_inner) } UpdateIdentityProviderConfigurationErrorKind::InvalidRequestException(_inner) => { Some(_inner) } UpdateIdentityProviderConfigurationErrorKind::ResourceNotFoundException(_inner) => { Some(_inner) } UpdateIdentityProviderConfigurationErrorKind::TooManyRequestsException(_inner) => { Some(_inner) } UpdateIdentityProviderConfigurationErrorKind::UnauthorizedException(_inner) => { Some(_inner) } UpdateIdentityProviderConfigurationErrorKind::Unhandled(_inner) => { Some(_inner.as_ref()) } } } } /// <p>You are not authorized to perform this action.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct UnauthorizedException { #[allow(missing_docs)] // documentation missing in model pub message: std::option::Option<std::string::String>, } impl std::fmt::Debug for UnauthorizedException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("UnauthorizedException"); formatter.field("message", &self.message); formatter.finish() } } impl UnauthorizedException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for UnauthorizedException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "UnauthorizedException")?; if let Some(inner_1) = &self.message { write!(f, ": {}", inner_1)?; } Ok(()) } } impl std::error::Error for UnauthorizedException {} /// See [`UnauthorizedException`](crate::error::UnauthorizedException) pub mod unauthorized_exception { /// A builder for [`UnauthorizedException`](crate::error::UnauthorizedException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, } impl Builder { #[allow(missing_docs)] // documentation missing in model pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } #[allow(missing_docs)] // documentation missing in model pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`UnauthorizedException`](crate::error::UnauthorizedException) pub fn build(self) -> crate::error::UnauthorizedException { crate::error::UnauthorizedException { message: self.message, } } } } impl UnauthorizedException { /// Creates a new builder-style object to manufacture [`UnauthorizedException`](crate::error::UnauthorizedException) pub fn builder() -> crate::error::unauthorized_exception::Builder { crate::error::unauthorized_exception::Builder::default() } } /// <p>The number of requests exceeds the limit.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct TooManyRequestsException { #[allow(missing_docs)] // documentation missing in model pub message: std::option::Option<std::string::String>, } impl std::fmt::Debug for TooManyRequestsException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("TooManyRequestsException"); formatter.field("message", &self.message); formatter.finish() } } impl TooManyRequestsException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for TooManyRequestsException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "TooManyRequestsException")?; if let Some(inner_2) = &self.message { write!(f, ": {}", inner_2)?; } Ok(()) } } impl std::error::Error for TooManyRequestsException {} /// See [`TooManyRequestsException`](crate::error::TooManyRequestsException) pub mod too_many_requests_exception { /// A builder for [`TooManyRequestsException`](crate::error::TooManyRequestsException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, } impl Builder { #[allow(missing_docs)] // documentation missing in model pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } #[allow(missing_docs)] // documentation missing in model pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`TooManyRequestsException`](crate::error::TooManyRequestsException) pub fn build(self) -> crate::error::TooManyRequestsException { crate::error::TooManyRequestsException { message: self.message, } } } } impl TooManyRequestsException { /// Creates a new builder-style object to manufacture [`TooManyRequestsException`](crate::error::TooManyRequestsException) pub fn builder() -> crate::error::too_many_requests_exception::Builder { crate::error::too_many_requests_exception::Builder::default() } } /// <p>The requested resource was not found.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ResourceNotFoundException { #[allow(missing_docs)] // documentation missing in model pub message: std::option::Option<std::string::String>, } impl std::fmt::Debug for ResourceNotFoundException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ResourceNotFoundException"); formatter.field("message", &self.message); formatter.finish() } } impl ResourceNotFoundException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for ResourceNotFoundException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "ResourceNotFoundException")?; if let Some(inner_3) = &self.message { write!(f, ": {}", inner_3)?; } Ok(()) } } impl std::error::Error for ResourceNotFoundException {} /// See [`ResourceNotFoundException`](crate::error::ResourceNotFoundException) pub mod resource_not_found_exception { /// A builder for [`ResourceNotFoundException`](crate::error::ResourceNotFoundException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, } impl Builder { #[allow(missing_docs)] // documentation missing in model pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } #[allow(missing_docs)] // documentation missing in model pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`ResourceNotFoundException`](crate::error::ResourceNotFoundException) pub fn build(self) -> crate::error::ResourceNotFoundException { crate::error::ResourceNotFoundException { message: self.message, } } } } impl ResourceNotFoundException { /// Creates a new builder-style object to manufacture [`ResourceNotFoundException`](crate::error::ResourceNotFoundException) pub fn builder() -> crate::error::resource_not_found_exception::Builder { crate::error::resource_not_found_exception::Builder::default() } } /// <p>The request is not valid.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct InvalidRequestException { #[allow(missing_docs)] // documentation missing in model pub message: std::option::Option<std::string::String>, } impl std::fmt::Debug for InvalidRequestException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("InvalidRequestException"); formatter.field("message", &self.message); formatter.finish() } } impl InvalidRequestException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for InvalidRequestException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "InvalidRequestException")?; if let Some(inner_4) = &self.message { write!(f, ": {}", inner_4)?; } Ok(()) } } impl std::error::Error for InvalidRequestException {} /// See [`InvalidRequestException`](crate::error::InvalidRequestException) pub mod invalid_request_exception { /// A builder for [`InvalidRequestException`](crate::error::InvalidRequestException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, } impl Builder { #[allow(missing_docs)] // documentation missing in model pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } #[allow(missing_docs)] // documentation missing in model pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`InvalidRequestException`](crate::error::InvalidRequestException) pub fn build(self) -> crate::error::InvalidRequestException { crate::error::InvalidRequestException { message: self.message, } } } } impl InvalidRequestException { /// Creates a new builder-style object to manufacture [`InvalidRequestException`](crate::error::InvalidRequestException) pub fn builder() -> crate::error::invalid_request_exception::Builder { crate::error::invalid_request_exception::Builder::default() } } /// <p>The service is temporarily unavailable.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct InternalServerErrorException { #[allow(missing_docs)] // documentation missing in model pub message: std::option::Option<std::string::String>, } impl std::fmt::Debug for InternalServerErrorException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("InternalServerErrorException"); formatter.field("message", &self.message); formatter.finish() } } impl InternalServerErrorException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for InternalServerErrorException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "InternalServerErrorException")?; if let Some(inner_5) = &self.message { write!(f, ": {}", inner_5)?; } Ok(()) } } impl std::error::Error for InternalServerErrorException {} /// See [`InternalServerErrorException`](crate::error::InternalServerErrorException) pub mod internal_server_error_exception { /// A builder for [`InternalServerErrorException`](crate::error::InternalServerErrorException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, } impl Builder { #[allow(missing_docs)] // documentation missing in model pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } #[allow(missing_docs)] // documentation missing in model pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`InternalServerErrorException`](crate::error::InternalServerErrorException) pub fn build(self) -> crate::error::InternalServerErrorException { crate::error::InternalServerErrorException { message: self.message, } } } } impl InternalServerErrorException { /// Creates a new builder-style object to manufacture [`InternalServerErrorException`](crate::error::InternalServerErrorException) pub fn builder() -> crate::error::internal_server_error_exception::Builder { crate::error::internal_server_error_exception::Builder::default() } } /// <p>The resource already exists.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ResourceAlreadyExistsException { #[allow(missing_docs)] // documentation missing in model pub message: std::option::Option<std::string::String>, } impl std::fmt::Debug for ResourceAlreadyExistsException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ResourceAlreadyExistsException"); formatter.field("message", &self.message); formatter.finish() } } impl ResourceAlreadyExistsException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for ResourceAlreadyExistsException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "ResourceAlreadyExistsException")?; if let Some(inner_6) = &self.message { write!(f, ": {}", inner_6)?; } Ok(()) } } impl std::error::Error for ResourceAlreadyExistsException {} /// See [`ResourceAlreadyExistsException`](crate::error::ResourceAlreadyExistsException) pub mod resource_already_exists_exception { /// A builder for [`ResourceAlreadyExistsException`](crate::error::ResourceAlreadyExistsException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, } impl Builder { #[allow(missing_docs)] // documentation missing in model pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } #[allow(missing_docs)] // documentation missing in model pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`ResourceAlreadyExistsException`](crate::error::ResourceAlreadyExistsException) pub fn build(self) -> crate::error::ResourceAlreadyExistsException { crate::error::ResourceAlreadyExistsException { message: self.message, } } } } impl ResourceAlreadyExistsException { /// Creates a new builder-style object to manufacture [`ResourceAlreadyExistsException`](crate::error::ResourceAlreadyExistsException) pub fn builder() -> crate::error::resource_already_exists_exception::Builder { crate::error::resource_already_exists_exception::Builder::default() } }
42.675972
138
0.667877
2671ac6dfdaf09a403eff766f46f115859b102b5
1,320
/* 给一非空的单词列表,返回前k个出现次数最多的单词。 返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率,按字母顺序排序。 示例 1: 输入: ["i", "love", "leetcode", "i", "love", "coding"], k = 2 输出: ["i", "love"] 解析: "i" 和 "love" 为出现次数最多的两个单词,均为2次。 注意,按字母顺序 "i" 在 "love" 之前。 示例 2: 输入: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4 输出: ["the", "is", "sunny", "day"] 解析: "the", "is", "sunny" 和 "day" 是出现次数最多的四个单词, 出现次数依次为 4, 3, 2 和 1 次。 注意: 假定 k 总为有效值, 1 ≤ k ≤ 集合元素数。 输入的单词均由小写字母组成。 扩展练习: 尝试以O(n log k) 时间复杂度和O(n) 空间复杂度解决。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/top-k-frequent-words 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ impl Solution { pub fn top_k_frequent(words: Vec<String>, k: i32) -> Vec<String> { use std::collections::HashMap; let mut fq = HashMap::new(); for word in words { *fq.entry(word).or_insert(0) += 1; } let mut v:Vec<(String, i32)> = fq.into_iter().map(|(k, v)| (k, v)).collect(); v.sort_unstable_by(|a, b| { if b.1 == a.1 { a.0.cmp(&b.0) } else { b.1.cmp(&a.1) } }); let mut answer = Vec::new(); for i in 0..v.len() { answer.push(v[i].0.clone()); if i as i32 == k - 1 { break; } } answer } }
22.758621
85
0.509091
ffc1a6efd1e51fdaedd9fda5cfb8d82b7a7c35f5
860
pub struct Note { pub freq: u32, pub duration: u64, } impl Note { pub fn new(b: u8) -> Self { let map: [u32; 12] = [262, 278, 294, 311, 330, 349, 370, 392, 415, 440, 466, 494]; let freq = map[(b % 12) as usize]; let duration = (b % 4 + 1) as u64 * 1000; Self { freq, duration } } } #[cfg(test)] mod tests { use super::Note; #[test] fn it_works() { let text = "hello"; let bytes = text.as_bytes(); let target_freq: [u32; 5] = [415, 349, 262, 262, 311]; let target_duration: [u64; 5] = [1000, 2000, 1000, 1000, 4000]; let mut index = 0; for b in bytes { let note = Note::new(*b); assert_eq!(note.freq, target_freq[index]); assert_eq!(note.duration, target_duration[index]); index += 1; } } }
26.060606
90
0.502326
8938dd600dc7feee4cd81f4c16cdd2c0183f12dd
8,895
use super::{Bounds, GameInfo, Light, Position, Rotation, Velocity}; use crate::ecs; use crate::ecs::Entity; use crate::entity::player_like::{compute_player_model_components, PlayerLikeModelPart}; use crate::entity::{CustomEntityRenderer, EntityType}; use crate::render; use crate::render::model; use crate::render::Renderer; use crate::world; use cgmath::{self, Decomposed, Matrix4, Point3, Quaternion, Rad, Rotation3, Vector3}; use collision::Aabb3; pub struct ZombieModel { model: Option<model::ModelKey>, name: Option<String>, dir: i32, time: f64, still_time: f64, idle_time: f64, } impl ZombieModel { pub fn new(name: Option<String>) -> ZombieModel { ZombieModel { model: None, name, dir: 0, time: 0.0, still_time: 0.0, idle_time: 0.0, } } } pub fn create_zombie(m: &mut ecs::Manager) -> ecs::Entity { let entity = m.create_entity(); m.add_component_direct(entity, Position::new(1478.5, 47.0, -474.5)); m.add_component_direct(entity, Rotation::new(0.0, 0.0)); m.add_component_direct(entity, Velocity::new(0.0, 0.0, 0.0)); m.add_component_direct( entity, Bounds::new(Aabb3::new( Point3::new(-0.3, 0.0, -0.3), Point3::new(0.3, 1.8, 0.3), )), ); m.add_component_direct(entity, Light::new()); m.add_component_direct(entity, EntityType::Zombie); m.add_component_direct(entity, ZombieModel::new(Some(String::from("test")))); entity } pub struct ZombieRenderer { zombie_model: ecs::Key<ZombieModel>, position: ecs::Key<Position>, rotation: ecs::Key<Rotation>, // TODO: Fix this, it is bugged somehow! game_info: ecs::Key<GameInfo>, light: ecs::Key<Light>, } impl ZombieRenderer { pub fn new(m: &mut ecs::Manager) -> Self { let zombie_model = m.get_key(); let position = m.get_key(); let rotation = m.get_key(); let light = m.get_key(); ZombieRenderer { zombie_model, position, rotation, game_info: m.get_key(), light, } } } // TODO: Setup culling impl CustomEntityRenderer for ZombieRenderer { fn update( &self, m: &mut ecs::Manager, _world: &world::World, renderer: &mut render::Renderer, _: bool, _: bool, e: Entity, ) { use std::f32::consts::PI; use std::f64::consts::PI as PI64; let world_entity = m.get_world(); let delta = m .get_component_mut(world_entity, self.game_info) .unwrap() .delta; let player_model = m.get_component_mut(e, self.zombie_model).unwrap(); let position = m.get_component_mut(e, self.position).unwrap(); let rotation = m.get_component_mut(e, self.rotation).unwrap(); let light = m.get_component(e, self.light).unwrap(); if let Some(pmodel) = player_model.model { let mdl = renderer.model.get_model(pmodel).unwrap(); mdl.block_light = light.block_light; mdl.sky_light = light.sky_light; let offset = Vector3::new( position.position.x as f32, -position.position.y as f32, position.position.z as f32, ); let offset_matrix = Matrix4::from(Decomposed { scale: 1.0, rot: Quaternion::from_angle_y(Rad(PI + rotation.yaw as f32)), disp: offset, }); // TODO This sucks /* if player_model.has_name_tag { let ang = (position.position.x - renderer.camera.pos.x) .atan2(position.position.z - renderer.camera.pos.z) as f32; mdl.matrix[ZombieModelPart::NameTag as usize] = Matrix4::from(Decomposed { scale: 1.0, rot: Quaternion::from_angle_y(Rad(ang)), disp: offset + Vector3::new(0.0, (-24.0 / 16.0) - 0.6, 0.0), }); }*/ mdl.matrix[PlayerLikeModelPart::Head as usize] = offset_matrix * Matrix4::from(Decomposed { scale: 1.0, rot: Quaternion::from_angle_x(Rad(-rotation.pitch as f32)), disp: Vector3::new(0.0, -12.0 / 16.0 - 12.0 / 16.0, 0.0), }); mdl.matrix[PlayerLikeModelPart::Body as usize] = offset_matrix * Matrix4::from(Decomposed { scale: 1.0, rot: Quaternion::from_angle_x(Rad(0.0)), disp: Vector3::new(0.0, -12.0 / 16.0 - 6.0 / 16.0, 0.0), }); let mut time = player_model.time; let mut dir = player_model.dir; if dir == 0 { dir = 1; time = 15.0; } let ang = ((time / 15.0) - 1.0) * (PI64 / 4.0); mdl.matrix[PlayerLikeModelPart::LegRight as usize] = offset_matrix * Matrix4::from(Decomposed { scale: 1.0, rot: Quaternion::from_angle_x(Rad(ang as f32)), disp: Vector3::new(2.0 / 16.0, -12.0 / 16.0, 0.0), }); mdl.matrix[PlayerLikeModelPart::LegLeft as usize] = offset_matrix * Matrix4::from(Decomposed { scale: 1.0, rot: Quaternion::from_angle_x(Rad(-ang as f32)), disp: Vector3::new(-2.0 / 16.0, -12.0 / 16.0, 0.0), }); let mut i_time = player_model.idle_time; i_time += delta * 0.02; if i_time > PI64 * 2.0 { i_time -= PI64 * 2.0; } player_model.idle_time = i_time; mdl.matrix[PlayerLikeModelPart::ArmRight as usize] = offset_matrix * Matrix4::from_translation(Vector3::new( 6.0 / 16.0, -12.0 / 16.0 - 12.0 / 16.0, 0.0, )) * Matrix4::from(Quaternion::from_angle_x(Rad(-(ang * 0.75) as f32))) * Matrix4::from(Quaternion::from_angle_z(Rad( (i_time.cos() * 0.06 - 0.06) as f32 ))) * Matrix4::from(Quaternion::from_angle_x(Rad((i_time.sin() * 0.06 - ((7.5 - (0.5_f64 - 7.5).abs()) / 7.5)) as f32))); mdl.matrix[PlayerLikeModelPart::ArmLeft as usize] = offset_matrix * Matrix4::from_translation(Vector3::new( -6.0 / 16.0, -12.0 / 16.0 - 12.0 / 16.0, 0.0, )) * Matrix4::from(Quaternion::from_angle_x(Rad((ang * 0.75) as f32))) * Matrix4::from(Quaternion::from_angle_z(Rad( -(i_time.cos() * 0.06 - 0.06) as f32 ))) * Matrix4::from(Quaternion::from_angle_x(Rad(-(i_time.sin() * 0.06) as f32))); let mut update = true; if position.moved { player_model.still_time = 0.0; } else if player_model.still_time > 2.0 { if (time - 15.0).abs() <= 1.5 * delta { time = 15.0; update = false; } dir = (15.0 - time).signum() as i32; } else { player_model.still_time += delta; } if update { time += delta * 1.5 * (dir as f64); if time > 30.0 { time = 30.0; dir = -1; } else if time < 0.0 { time = 0.0; dir = 1; } } player_model.time = time; player_model.dir = dir; } } fn entity_added( &self, m: &mut ecs::Manager, e: ecs::Entity, _: &world::World, renderer: &mut render::Renderer, ) { let zombie_model = m.get_component_mut(e, self.zombie_model).unwrap(); let tex = Renderer::get_texture( renderer.get_textures_ref(), "minecraft:entity/zombie/zombie", ); let components = compute_player_model_components(&tex, &zombie_model.name, renderer); zombie_model.model = Some(renderer.model.create_model(model::DEFAULT, components)); } fn entity_removed( &self, m: &mut ecs::Manager, e: ecs::Entity, _: &world::World, renderer: &mut render::Renderer, ) { let zombie_model = m.get_component_mut(e, self.zombie_model).unwrap(); if let Some(model) = zombie_model.model.take() { renderer.model.remove_model(model); } } }
34.882353
94
0.505003
6a624e39e326775c93c0bf3d9a2522a3ad8984d4
3,460
// Copyright 2013-2014 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. // ignore-android: FIXME(#10381) // min-lldb-version: 310 // compile-flags:-g // === GDB TESTS =================================================================================== // gdb-command:run // gdb-command:print arg // gdb-check:$1 = {b = -1, b1 = 0} // gdb-command:continue // gdb-command:print inferred // gdb-check:$2 = 1 // gdb-command:print explicitly // gdb-check:$3 = 1 // gdb-command:continue // gdb-command:print arg // gdb-check:$4 = 2 // gdb-command:continue // gdb-command:print arg // gdb-check:$5 = {4, 5} // gdb-command:continue // gdb-command:print a // gdb-check:$6 = 6 // gdb-command:print b // gdb-check:$7 = 7 // gdb-command:continue // gdb-command:print a // gdb-check:$8 = 8 // gdb-command:print b // gdb-check:$9 = 9 // gdb-command:continue // === LLDB TESTS ================================================================================== // lldb-command:run // lldb-command:print arg // lldb-check:[...]$0 = Struct<i32> { b: -1, b1: 0 } // lldb-command:continue // lldb-command:print inferred // lldb-check:[...]$1 = 1 // lldb-command:print explicitly // lldb-check:[...]$2 = 1 // lldb-command:continue // lldb-command:print arg // lldb-check:[...]$3 = 2 // lldb-command:continue // lldb-command:print arg // lldb-check:[...]$4 = (4, 5) // lldb-command:continue // lldb-command:print a // lldb-check:[...]$5 = 6 // lldb-command:print b // lldb-check:[...]$6 = 7 // lldb-command:continue // lldb-command:print a // lldb-check:[...]$7 = 8 // lldb-command:print b // lldb-check:[...]$8 = 9 // lldb-command:continue #![allow(unused_variables)] #![allow(dead_code)] #![omit_gdb_pretty_printer_section] trait TraitWithAssocType { type Type; fn get_value(&self) -> Self::Type; } impl TraitWithAssocType for i32 { type Type = i64; fn get_value(&self) -> i64 { *self as i64 } } struct Struct<T: TraitWithAssocType> { b: T, b1: T::Type, } enum Enum<T: TraitWithAssocType> { Variant1(T, T::Type), Variant2(T::Type, T) } fn assoc_struct<T: TraitWithAssocType>(arg: Struct<T>) { zzz(); // #break } fn assoc_local<T: TraitWithAssocType>(x: T) { let inferred = x.get_value(); let explicitly: T::Type = x.get_value(); zzz(); // #break } fn assoc_arg<T: TraitWithAssocType>(arg: T::Type) { zzz(); // #break } fn assoc_return_value<T: TraitWithAssocType>(arg: T) -> T::Type { return arg.get_value(); } fn assoc_tuple<T: TraitWithAssocType>(arg: (T, T::Type)) { zzz(); // #break } fn assoc_enum<T: TraitWithAssocType>(arg: Enum<T>) { match arg { Enum::Variant1(a, b) => { zzz(); // #break } Enum::Variant2(a, b) => { zzz(); // #break } } } fn main() { assoc_struct(Struct { b: -1i32, b1: 0i64 }); assoc_local(1i32); assoc_arg::<i32>(2i64); assoc_return_value(3i32); assoc_tuple((4i32, 5i64)); assoc_enum(Enum::Variant1(6i32, 7i64)); assoc_enum(Enum::Variant2(8i64, 9i32)); } fn zzz() { () }
22.763158
100
0.597399
bfe6e6e2dafdefaff0ff2eaef4352aad2584103b
3,560
// Copyright (c) SimpleStaking and Tezedge Contributors // SPDX-License-Identifier: MIT use std::sync::Arc; use rocksdb::{Cache, ColumnFamilyDescriptor}; use serde::{Deserialize, Serialize}; use crypto::hash::BlockHash; use crate::block_meta_storage::Meta; use crate::persistent::database::{ default_table_options, IteratorMode, IteratorWithSchema, RocksDbKeyValueSchema, }; use crate::persistent::{BincodeEncoded, KeyValueSchema, KeyValueStoreWithSchema}; use crate::{PersistentStorage, StorageError}; pub type PredecessorsIndexStorageKV = dyn KeyValueStoreWithSchema<PredecessorStorage> + Sync + Send; #[derive(Serialize, Deserialize)] pub struct PredecessorKey { block_hash: BlockHash, exponent_slot: u32, } impl PredecessorKey { pub fn new(block_hash: BlockHash, exponent_slot: u32) -> Self { Self { block_hash, exponent_slot, } } } #[derive(Clone)] pub struct PredecessorStorage { kv: Arc<PredecessorsIndexStorageKV>, } impl PredecessorStorage { pub fn new(persistent_storage: &PersistentStorage) -> Self { Self { kv: persistent_storage.db(), } } pub fn store_predecessors( &self, block_hash: &BlockHash, block_meta: &Meta, stored_predecessors_size: u32, ) -> Result<(), StorageError> { if let Some(direct_predecessor) = block_meta.predecessor() { // genesis if direct_predecessor == block_hash { return Ok(()); } else { // put the direct predecessor to slot 0 self.put( &PredecessorKey::new(block_hash.clone(), 0), direct_predecessor, )?; // fill other slots let mut predecessor = direct_predecessor.clone(); for predecessor_exponent_slot in 1..stored_predecessors_size { let predecessor_key = PredecessorKey::new(predecessor, predecessor_exponent_slot - 1); if let Some(p) = self.get(&predecessor_key)? { let key = PredecessorKey::new(block_hash.clone(), predecessor_exponent_slot); self.put(&key, &p)?; predecessor = p; } else { return Ok(()); } } } } Ok(()) } #[inline] pub fn put( &self, key: &PredecessorKey, predeccessor_hash: &BlockHash, ) -> Result<(), StorageError> { self.kv .put(key, predeccessor_hash) .map_err(StorageError::from) } #[inline] pub fn get(&self, key: &PredecessorKey) -> Result<Option<BlockHash>, StorageError> { self.kv.get(key).map_err(StorageError::from) } #[inline] pub fn iter(&self, mode: IteratorMode<Self>) -> Result<IteratorWithSchema<Self>, StorageError> { self.kv.iterator(mode).map_err(StorageError::from) } } impl BincodeEncoded for PredecessorKey {} impl KeyValueSchema for PredecessorStorage { type Key = PredecessorKey; type Value = BlockHash; } impl RocksDbKeyValueSchema for PredecessorStorage { fn descriptor(cache: &Cache) -> ColumnFamilyDescriptor { let cf_opts = default_table_options(cache); ColumnFamilyDescriptor::new(Self::name(), cf_opts) } #[inline] fn name() -> &'static str { "predecessor_storage" } }
28.709677
100
0.591011
e2d23ea59760a565beef78fabd630d0345ea4100
14,533
//! This module contains functions that often are more convenient to use than the raw OpenSlide //! wrappers //! use std::cmp::PartialOrd; use std::collections::HashMap; use std::fmt::{Debug, Display}; use std::path::Path; use failure::{format_err, Error}; use image::RgbaImage; use num::zero; use num::{Integer, Num, ToPrimitive, Unsigned}; use crate::{bindings, properties, utils}; /// A convenient OpenSlide object with the ordinary OpenSlide functions as methods /// /// This wraps the bindings found in the bindings module, but has a more (in my opinion) convenient /// API for rust. It also contains some other convenience methods. #[derive(Clone)] pub struct OpenSlide { osr: *const bindings::OpenSlideT, pub properties: properties::Properties, } impl Drop for OpenSlide { /// This method is called when the object in dropped, and tries to close the slide. fn drop(&mut self) { unsafe { bindings::close(self.osr) }; } } impl OpenSlide { /// This method tries to open the slide at the given filename location. /// /// This function can be expensive; avoid calling it unnecessarily. For example, a tile server /// should not create a new object on every tile request. Instead, it should maintain a cache /// of OpenSlide objects and reuse them when possible. pub fn new(filename: &Path) -> Result<OpenSlide, Error> { if !filename.exists() { return Err(format_err!( "Error: Nonexisting path: {}", filename.display() )); } let osr = bindings::open( filename .to_str() .ok_or(format_err!("Error: Path to &str"))?, )?; let mut property_map = HashMap::<String, String>::new(); for name in unsafe { bindings::get_property_names(osr)? } { property_map.insert(name.clone(), unsafe { bindings::get_property_value(osr, &name)? }); } let properties = properties::Properties::new(&property_map); Ok(OpenSlide { osr, properties }) } /// Get the number of levels in the whole slide image. pub fn get_level_count(&self) -> Result<u32, Error> { let num_levels = unsafe { bindings::get_level_count(self.osr)? }; if num_levels < -1 { Err(format_err!( "Error: Number of levels is {}, this is an unknown error from OpenSlide. \ OpenSlide returns -1 if an error occured. \ See OpenSlide C API documentation.", num_levels )) } else if num_levels == -1 { Err(format_err!( "Error: Number of levels is -1, this is a known error from OpenSlide. \ OpenSlide returns -1 if an error occured. \ See OpenSlide C API documentation.", )) } else { Ok(num_levels as u32) } } /// Get the dimensions of level 0 (the largest level). /// /// This method returns the (width, height) number of pixels of the level 0 whole slide image. /// /// This is the same as calling get_level_dimensions(level) with level=0. pub fn get_level0_dimensions(&self) -> Result<(u64, u64), Error> { let (width, height) = unsafe { bindings::get_level0_dimensions(self.osr)? }; if width < -1 { return Err(format_err!( "Error: Width is {}, this is an unknown error from OpenSlide. \ OpenSlide returns -1 if an error occured. \ See OpenSlide C API documentation.", width )); } else if width == -1 { return Err(format_err!( "Error: Width is -1, this is a known error from OpenSlide. \ OpenSlide returns -1 if an error occured. \ See OpenSlide C API documentation.", )); } if height < -1 { return Err(format_err!( "Error: Height is {}, this is an unknown error from OpenSlide. \ OpenSlide returns -1 if an error occured. \ See OpenSlide C API documentation.", width )); } else if height == -1 { return Err(format_err!( "Error: Height is -1, this is a known error from OpenSlide. \ OpenSlide returns -1 if an error occured. \ See OpenSlide C API documentation.", )); } Ok((width as u64, height as u64)) } /// Get the dimensions of level 0 (the largest level). /// /// This method returns the (width, height) number of pixels of the whole slide image at the /// specified level. Returns an error if the level is invalid pub fn get_level_dimensions<T: Integer + ToPrimitive + Debug + Display + Clone + Copy>( &self, level: T, ) -> Result<(u64, u64), Error> { self.assert_level_validity(level)?; let level = level .to_i32() .ok_or(format_err!("Conversion to primitive error"))?; let (width, height) = unsafe { bindings::get_level_dimensions(self.osr, level)? }; if width < -1 { return Err(format_err!( "Error: Width is {}, this is an unknown error from OpenSlide. \ OpenSlide returns -1 if an error occured. \ See OpenSlide C API documentation.", width )); } else if width == -1 { return Err(format_err!( "Error: Width is -1, this is a known error from openslide. \ OpenSlide returns -1 if an error occured. \ See OpenSlide C API documentation.", )); } if height < -1 { return Err(format_err!( "Error: Height is {}, this is an unknown error from OpenSlide. \ OpenSlide returns -1 if an error occured. \ See OpenSlide C API documentation.", width )); } else if height == -1 { return Err(format_err!( "Error: Height is -1, this is a known error from openslide. \ OpenSlide returns -1 if an error occured. \ See OpenSlide C API documentation.", )); } Ok((width as u64, height as u64)) } /// Get the downsampling factor of a given level. pub fn get_level_downsample<T: Integer + ToPrimitive + Debug + Display + Clone + Copy>( &self, level: T, ) -> Result<f64, Error> { self.assert_level_validity(level)?; let level = level .to_i32() .ok_or(format_err!("Conversion to primitive error"))?; let downsample_factor = unsafe { bindings::get_level_downsample(self.osr, level)? }; if downsample_factor < 0.0 { return Err(format_err!( "Error: When trying to get a downsample factor for level {},\ OpenSlide returned a downsample factor {}, this is an error from \ OpenSlide. OpenSlide returns -1.0 if an error occured. \ See OpenSlide C API documentation.", level, downsample_factor )); } Ok(downsample_factor) } /// Get the best level to use for displaying the given downsample factor. pub fn get_best_level_for_downsample< T: Num + ToPrimitive + PartialOrd + Debug + Display + Clone + Copy, >( &self, downsample_factor: T, ) -> Result<u32, Error> { if downsample_factor < zero() { return Err(format_err!( "Error: Only non-negative downsample factor is allowed. \ You specified {}. ", downsample_factor )); } let level = unsafe { bindings::get_best_level_for_downsample( self.osr, downsample_factor .to_f64() .ok_or(format_err!("Conversion to primitive error"))?, )? }; if level < -1 { Err(format_err!( "Error: Returned level is {}, this is an unknown error from OpenSlide. \ OpenSlide returns -1 if an error occured. \ See OpenSlide C API documentation.", level )) } else if level == -1 { Err(format_err!( "Error: Returned level is -1, this is a known error from openslide. \ OpenSlide returns -1 if an error occured. \ See OpenSlide C API documentation.", )) } else { Ok(level as u32) } } /// Return (new_height, new_width) where /// /// new_height = min(height, max_height) /// new_width = min(width, max_width) /// /// and max_{height, width} are computed based on the top left corner coordinates and the /// dimensions of the image. fn get_feasible_dimensions< T: Integer + Unsigned + ToPrimitive + Debug + Display + Clone + Copy, >( &self, top_left_lvl0_row: T, top_left_lvl0_col: T, level: T, height: T, width: T, ) -> Result<(u64, u64), Error> { let (max_width, max_height) = self.get_level_dimensions(level)?; let downsample_factor = self.get_level_downsample(level)?; let tl_row_this_lvl = top_left_lvl0_row .to_f64() .ok_or(format_err!("Conversion to primitive error"))? / downsample_factor; let tl_col_this_lvl = top_left_lvl0_col .to_f64() .ok_or(format_err!("Conversion to primitive error"))? / downsample_factor; let new_height = height .to_u64() .ok_or(format_err!("Conversion to primitive error"))? .min(max_height - tl_row_this_lvl.round() as u64); let new_width = width .to_u64() .ok_or(format_err!("Conversion to primitive error"))? .min(max_width - tl_col_this_lvl.round() as u64); if new_height < height .to_u64() .ok_or(format_err!("Conversion to primitive error"))? { println!( "WARNING: Requested region height is changed from {} to {} in order to fit", height, new_height ); } if new_width < width .to_u64() .ok_or(format_err!("conversion to primitive error"))? { println!( "WARNING: Requested region width is changed from {} to {} in order to fit", width, new_width ); } if new_height > max_height { return Err(format_err!( "Requested height {} exceeds maximum {}", height, max_height )); } if new_width > max_width { return Err(format_err!( "Requested width {} exceeds maximum {}", width, max_width )); } Ok((new_height, new_width)) } /// Copy pre-multiplied ARGB data from a whole slide image. /// /// This function reads and decompresses a region of a whole slide image into an RGBA image /// /// Args: /// top_left_lvl0_row: Row coordinate (increasing downwards) of top left pixel position /// top_left_lvl0_col: Column coordinate (increasing to the right) of top left pixel /// position /// level: At which level to grab the region from /// height: Height in pixels of the outputted region /// width: Width in pixels of the outputted region pub fn read_region<T: Integer + Unsigned + ToPrimitive + Debug + Display + Clone + Copy>( &self, top_left_lvl0_row: T, top_left_lvl0_col: T, level: T, height: T, width: T, ) -> Result<RgbaImage, Error> { let (height, width) = self.get_feasible_dimensions( top_left_lvl0_row, top_left_lvl0_col, level, height, width, )?; let buffer = unsafe { bindings::read_region( self.osr, top_left_lvl0_col .to_i64() .ok_or(format_err!("Conversion to primitive error"))?, top_left_lvl0_row .to_i64() .ok_or(format_err!("Conversion to primitive error"))?, level .to_i32() .ok_or(format_err!("Conversion to primitive error"))?, width .to_i64() .ok_or(format_err!("Conversion to primitive error"))?, height .to_i64() .ok_or(format_err!("Conversion to primitive error"))?, )? }; let word_repr = utils::WordRepresentation::BigEndian; utils::decode_buffer(&buffer, height, width, word_repr) } /// Get a dictionary of properties associated with the current slide /// /// There are some standard properties to every slide, but also a lot of vendor-specific /// properties. This method returns a HashMap with all key-value pairs of the properties /// associated with the slide. pub fn get_properties(&self) -> Result<HashMap<String, String>, Error> { let mut properties = HashMap::<String, String>::new(); for name in unsafe { bindings::get_property_names(self.osr)? } { properties.insert(name.clone(), unsafe { bindings::get_property_value(self.osr, &name)? }); } Ok(properties) } /// Check if the given level is valid fn assert_level_validity<T: Integer + ToPrimitive>(&self, level: T) -> Result<(), Error> { let max_num_levels = self.get_level_count()?; let level = level .to_u32() .ok_or(format_err!("Conversion to primitive error"))?; if level >= max_num_levels { return Err(format_err!( "Error: Specified level {} is larger than the max slide level {}", level, max_num_levels - 1, )); } Ok(()) } }
36.062035
99
0.54304
ed8f6cc9a6c12ec8bcac1fa51658be6f27eee08c
2,333
use std::env; mod open_file; mod process; mod ps_utils; fn main() { let args: Vec<String> = env::args().collect(); if args.len() != 2 { println!("Usage: {} <name or pid of target>", args[0]); std::process::exit(1); } let target = &args[1]; let process = ps_utils::get_target(target).expect("some error about ps"); match process { Some(p) => { p.print(); let child_process = ps_utils::get_child_processes(p.pid).expect("error on get child process"); for c in child_process.iter() { c.print(); } } None => { println!( "Target \"{}\" did not match any running PIDs or executables", target ); std::process::exit(1); } } } #[cfg(test)] mod test { use std::process::{Child, Command}; fn start_c_program(program: &str) -> Child { Command::new(program) .spawn() .expect(&format!("Could not find {}. Have you run make?", program)) } #[test] fn test_exit_status_valid_target() { let mut subprocess = start_c_program("./multi_pipe_test"); assert_eq!( Command::new("./target/debug/inspect-fds") .args(&[&subprocess.id().to_string()]) .status() .expect("Could not find target/debug/inspect-fds. Is the binary compiled?") .code() .expect("Program was unexpectedly terminated by a signal"), 0, "We expected the program to exit normally, but it didn't." ); let _ = subprocess.kill(); } #[test] fn test_exit_status_invalid_target() { assert_eq!( Command::new("./target/debug/inspect-fds") .args(&["./nonexistent"]) .status() .expect("Could not find target/debug/inspect-fds. Is the binary compiled?") .code() .expect("Program was unexpectedly terminated by a signal"), 1, "Program exited with unexpected return code. Make sure you handle the case where \ ps_utils::get_target returns None and print an error message and return status \ 1." ); } }
30.298701
94
0.519931
149b5142839789c27e0dbe7ab8004dc0a6ceba60
29,668
#[doc = "Reader of register LFAPRESC0"] pub type R = crate::R<u32, super::LFAPRESC0>; #[doc = "Writer for register LFAPRESC0"] pub type W = crate::W<u32, super::LFAPRESC0>; #[doc = "Register LFAPRESC0 `reset()`'s with value 0"] impl crate::ResetValue for super::LFAPRESC0 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Low Energy Timer 0 Prescaler\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum LETIMER0_A { #[doc = "0: LFACLKLETIMER0 = LFACLK"] DIV1 = 0, #[doc = "1: LFACLKLETIMER0 = LFACLK/2"] DIV2 = 1, #[doc = "2: LFACLKLETIMER0 = LFACLK/4"] DIV4 = 2, #[doc = "3: LFACLKLETIMER0 = LFACLK/8"] DIV8 = 3, #[doc = "4: LFACLKLETIMER0 = LFACLK/16"] DIV16 = 4, #[doc = "5: LFACLKLETIMER0 = LFACLK/32"] DIV32 = 5, #[doc = "6: LFACLKLETIMER0 = LFACLK/64"] DIV64 = 6, #[doc = "7: LFACLKLETIMER0 = LFACLK/128"] DIV128 = 7, #[doc = "8: LFACLKLETIMER0 = LFACLK/256"] DIV256 = 8, #[doc = "9: LFACLKLETIMER0 = LFACLK/512"] DIV512 = 9, #[doc = "10: LFACLKLETIMER0 = LFACLK/1024"] DIV1024 = 10, #[doc = "11: LFACLKLETIMER0 = LFACLK/2048"] DIV2048 = 11, #[doc = "12: LFACLKLETIMER0 = LFACLK/4096"] DIV4096 = 12, #[doc = "13: LFACLKLETIMER0 = LFACLK/8192"] DIV8192 = 13, #[doc = "14: LFACLKLETIMER0 = LFACLK/16384"] DIV16384 = 14, #[doc = "15: LFACLKLETIMER0 = LFACLK/32768"] DIV32768 = 15, } impl From<LETIMER0_A> for u8 { #[inline(always)] fn from(variant: LETIMER0_A) -> Self { variant as _ } } #[doc = "Reader of field `LETIMER0`"] pub type LETIMER0_R = crate::R<u8, LETIMER0_A>; impl LETIMER0_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> LETIMER0_A { match self.bits { 0 => LETIMER0_A::DIV1, 1 => LETIMER0_A::DIV2, 2 => LETIMER0_A::DIV4, 3 => LETIMER0_A::DIV8, 4 => LETIMER0_A::DIV16, 5 => LETIMER0_A::DIV32, 6 => LETIMER0_A::DIV64, 7 => LETIMER0_A::DIV128, 8 => LETIMER0_A::DIV256, 9 => LETIMER0_A::DIV512, 10 => LETIMER0_A::DIV1024, 11 => LETIMER0_A::DIV2048, 12 => LETIMER0_A::DIV4096, 13 => LETIMER0_A::DIV8192, 14 => LETIMER0_A::DIV16384, 15 => LETIMER0_A::DIV32768, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `DIV1`"] #[inline(always)] pub fn is_div1(&self) -> bool { *self == LETIMER0_A::DIV1 } #[doc = "Checks if the value of the field is `DIV2`"] #[inline(always)] pub fn is_div2(&self) -> bool { *self == LETIMER0_A::DIV2 } #[doc = "Checks if the value of the field is `DIV4`"] #[inline(always)] pub fn is_div4(&self) -> bool { *self == LETIMER0_A::DIV4 } #[doc = "Checks if the value of the field is `DIV8`"] #[inline(always)] pub fn is_div8(&self) -> bool { *self == LETIMER0_A::DIV8 } #[doc = "Checks if the value of the field is `DIV16`"] #[inline(always)] pub fn is_div16(&self) -> bool { *self == LETIMER0_A::DIV16 } #[doc = "Checks if the value of the field is `DIV32`"] #[inline(always)] pub fn is_div32(&self) -> bool { *self == LETIMER0_A::DIV32 } #[doc = "Checks if the value of the field is `DIV64`"] #[inline(always)] pub fn is_div64(&self) -> bool { *self == LETIMER0_A::DIV64 } #[doc = "Checks if the value of the field is `DIV128`"] #[inline(always)] pub fn is_div128(&self) -> bool { *self == LETIMER0_A::DIV128 } #[doc = "Checks if the value of the field is `DIV256`"] #[inline(always)] pub fn is_div256(&self) -> bool { *self == LETIMER0_A::DIV256 } #[doc = "Checks if the value of the field is `DIV512`"] #[inline(always)] pub fn is_div512(&self) -> bool { *self == LETIMER0_A::DIV512 } #[doc = "Checks if the value of the field is `DIV1024`"] #[inline(always)] pub fn is_div1024(&self) -> bool { *self == LETIMER0_A::DIV1024 } #[doc = "Checks if the value of the field is `DIV2048`"] #[inline(always)] pub fn is_div2048(&self) -> bool { *self == LETIMER0_A::DIV2048 } #[doc = "Checks if the value of the field is `DIV4096`"] #[inline(always)] pub fn is_div4096(&self) -> bool { *self == LETIMER0_A::DIV4096 } #[doc = "Checks if the value of the field is `DIV8192`"] #[inline(always)] pub fn is_div8192(&self) -> bool { *self == LETIMER0_A::DIV8192 } #[doc = "Checks if the value of the field is `DIV16384`"] #[inline(always)] pub fn is_div16384(&self) -> bool { *self == LETIMER0_A::DIV16384 } #[doc = "Checks if the value of the field is `DIV32768`"] #[inline(always)] pub fn is_div32768(&self) -> bool { *self == LETIMER0_A::DIV32768 } } #[doc = "Write proxy for field `LETIMER0`"] pub struct LETIMER0_W<'a> { w: &'a mut W, } impl<'a> LETIMER0_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LETIMER0_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "LFACLKLETIMER0 = LFACLK"] #[inline(always)] pub fn div1(self) -> &'a mut W { self.variant(LETIMER0_A::DIV1) } #[doc = "LFACLKLETIMER0 = LFACLK/2"] #[inline(always)] pub fn div2(self) -> &'a mut W { self.variant(LETIMER0_A::DIV2) } #[doc = "LFACLKLETIMER0 = LFACLK/4"] #[inline(always)] pub fn div4(self) -> &'a mut W { self.variant(LETIMER0_A::DIV4) } #[doc = "LFACLKLETIMER0 = LFACLK/8"] #[inline(always)] pub fn div8(self) -> &'a mut W { self.variant(LETIMER0_A::DIV8) } #[doc = "LFACLKLETIMER0 = LFACLK/16"] #[inline(always)] pub fn div16(self) -> &'a mut W { self.variant(LETIMER0_A::DIV16) } #[doc = "LFACLKLETIMER0 = LFACLK/32"] #[inline(always)] pub fn div32(self) -> &'a mut W { self.variant(LETIMER0_A::DIV32) } #[doc = "LFACLKLETIMER0 = LFACLK/64"] #[inline(always)] pub fn div64(self) -> &'a mut W { self.variant(LETIMER0_A::DIV64) } #[doc = "LFACLKLETIMER0 = LFACLK/128"] #[inline(always)] pub fn div128(self) -> &'a mut W { self.variant(LETIMER0_A::DIV128) } #[doc = "LFACLKLETIMER0 = LFACLK/256"] #[inline(always)] pub fn div256(self) -> &'a mut W { self.variant(LETIMER0_A::DIV256) } #[doc = "LFACLKLETIMER0 = LFACLK/512"] #[inline(always)] pub fn div512(self) -> &'a mut W { self.variant(LETIMER0_A::DIV512) } #[doc = "LFACLKLETIMER0 = LFACLK/1024"] #[inline(always)] pub fn div1024(self) -> &'a mut W { self.variant(LETIMER0_A::DIV1024) } #[doc = "LFACLKLETIMER0 = LFACLK/2048"] #[inline(always)] pub fn div2048(self) -> &'a mut W { self.variant(LETIMER0_A::DIV2048) } #[doc = "LFACLKLETIMER0 = LFACLK/4096"] #[inline(always)] pub fn div4096(self) -> &'a mut W { self.variant(LETIMER0_A::DIV4096) } #[doc = "LFACLKLETIMER0 = LFACLK/8192"] #[inline(always)] pub fn div8192(self) -> &'a mut W { self.variant(LETIMER0_A::DIV8192) } #[doc = "LFACLKLETIMER0 = LFACLK/16384"] #[inline(always)] pub fn div16384(self) -> &'a mut W { self.variant(LETIMER0_A::DIV16384) } #[doc = "LFACLKLETIMER0 = LFACLK/32768"] #[inline(always)] pub fn div32768(self) -> &'a mut W { self.variant(LETIMER0_A::DIV32768) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f); self.w } } #[doc = "Low Energy Timer 1 Prescaler\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum LETIMER1_A { #[doc = "0: LFACLKLETIMER1 = LFACLK"] DIV1 = 0, #[doc = "1: LFACLKLETIMER1 = LFACLK/2"] DIV2 = 1, #[doc = "2: LFACLKLETIMER1 = LFACLK/4"] DIV4 = 2, #[doc = "3: LFACLKLETIMER1 = LFACLK/8"] DIV8 = 3, #[doc = "4: LFACLKLETIMER1 = LFACLK/16"] DIV16 = 4, #[doc = "5: LFACLKLETIMER1 = LFACLK/32"] DIV32 = 5, #[doc = "6: LFACLKLETIMER1 = LFACLK/64"] DIV64 = 6, #[doc = "7: LFACLKLETIMER1 = LFACLK/128"] DIV128 = 7, #[doc = "8: LFACLKLETIMER1 = LFACLK/256"] DIV256 = 8, #[doc = "9: LFACLKLETIMER1 = LFACLK/512"] DIV512 = 9, #[doc = "10: LFACLKLETIMER1 = LFACLK/1024"] DIV1024 = 10, #[doc = "11: LFACLKLETIMER1 = LFACLK/2048"] DIV2048 = 11, #[doc = "12: LFACLKLETIMER1 = LFACLK/4096"] DIV4096 = 12, #[doc = "13: LFACLKLETIMER1 = LFACLK/8192"] DIV8192 = 13, #[doc = "14: LFACLKLETIMER1 = LFACLK/16384"] DIV16384 = 14, #[doc = "15: LFACLKLETIMER1 = LFACLK/32768"] DIV32768 = 15, } impl From<LETIMER1_A> for u8 { #[inline(always)] fn from(variant: LETIMER1_A) -> Self { variant as _ } } #[doc = "Reader of field `LETIMER1`"] pub type LETIMER1_R = crate::R<u8, LETIMER1_A>; impl LETIMER1_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> LETIMER1_A { match self.bits { 0 => LETIMER1_A::DIV1, 1 => LETIMER1_A::DIV2, 2 => LETIMER1_A::DIV4, 3 => LETIMER1_A::DIV8, 4 => LETIMER1_A::DIV16, 5 => LETIMER1_A::DIV32, 6 => LETIMER1_A::DIV64, 7 => LETIMER1_A::DIV128, 8 => LETIMER1_A::DIV256, 9 => LETIMER1_A::DIV512, 10 => LETIMER1_A::DIV1024, 11 => LETIMER1_A::DIV2048, 12 => LETIMER1_A::DIV4096, 13 => LETIMER1_A::DIV8192, 14 => LETIMER1_A::DIV16384, 15 => LETIMER1_A::DIV32768, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `DIV1`"] #[inline(always)] pub fn is_div1(&self) -> bool { *self == LETIMER1_A::DIV1 } #[doc = "Checks if the value of the field is `DIV2`"] #[inline(always)] pub fn is_div2(&self) -> bool { *self == LETIMER1_A::DIV2 } #[doc = "Checks if the value of the field is `DIV4`"] #[inline(always)] pub fn is_div4(&self) -> bool { *self == LETIMER1_A::DIV4 } #[doc = "Checks if the value of the field is `DIV8`"] #[inline(always)] pub fn is_div8(&self) -> bool { *self == LETIMER1_A::DIV8 } #[doc = "Checks if the value of the field is `DIV16`"] #[inline(always)] pub fn is_div16(&self) -> bool { *self == LETIMER1_A::DIV16 } #[doc = "Checks if the value of the field is `DIV32`"] #[inline(always)] pub fn is_div32(&self) -> bool { *self == LETIMER1_A::DIV32 } #[doc = "Checks if the value of the field is `DIV64`"] #[inline(always)] pub fn is_div64(&self) -> bool { *self == LETIMER1_A::DIV64 } #[doc = "Checks if the value of the field is `DIV128`"] #[inline(always)] pub fn is_div128(&self) -> bool { *self == LETIMER1_A::DIV128 } #[doc = "Checks if the value of the field is `DIV256`"] #[inline(always)] pub fn is_div256(&self) -> bool { *self == LETIMER1_A::DIV256 } #[doc = "Checks if the value of the field is `DIV512`"] #[inline(always)] pub fn is_div512(&self) -> bool { *self == LETIMER1_A::DIV512 } #[doc = "Checks if the value of the field is `DIV1024`"] #[inline(always)] pub fn is_div1024(&self) -> bool { *self == LETIMER1_A::DIV1024 } #[doc = "Checks if the value of the field is `DIV2048`"] #[inline(always)] pub fn is_div2048(&self) -> bool { *self == LETIMER1_A::DIV2048 } #[doc = "Checks if the value of the field is `DIV4096`"] #[inline(always)] pub fn is_div4096(&self) -> bool { *self == LETIMER1_A::DIV4096 } #[doc = "Checks if the value of the field is `DIV8192`"] #[inline(always)] pub fn is_div8192(&self) -> bool { *self == LETIMER1_A::DIV8192 } #[doc = "Checks if the value of the field is `DIV16384`"] #[inline(always)] pub fn is_div16384(&self) -> bool { *self == LETIMER1_A::DIV16384 } #[doc = "Checks if the value of the field is `DIV32768`"] #[inline(always)] pub fn is_div32768(&self) -> bool { *self == LETIMER1_A::DIV32768 } } #[doc = "Write proxy for field `LETIMER1`"] pub struct LETIMER1_W<'a> { w: &'a mut W, } impl<'a> LETIMER1_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LETIMER1_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "LFACLKLETIMER1 = LFACLK"] #[inline(always)] pub fn div1(self) -> &'a mut W { self.variant(LETIMER1_A::DIV1) } #[doc = "LFACLKLETIMER1 = LFACLK/2"] #[inline(always)] pub fn div2(self) -> &'a mut W { self.variant(LETIMER1_A::DIV2) } #[doc = "LFACLKLETIMER1 = LFACLK/4"] #[inline(always)] pub fn div4(self) -> &'a mut W { self.variant(LETIMER1_A::DIV4) } #[doc = "LFACLKLETIMER1 = LFACLK/8"] #[inline(always)] pub fn div8(self) -> &'a mut W { self.variant(LETIMER1_A::DIV8) } #[doc = "LFACLKLETIMER1 = LFACLK/16"] #[inline(always)] pub fn div16(self) -> &'a mut W { self.variant(LETIMER1_A::DIV16) } #[doc = "LFACLKLETIMER1 = LFACLK/32"] #[inline(always)] pub fn div32(self) -> &'a mut W { self.variant(LETIMER1_A::DIV32) } #[doc = "LFACLKLETIMER1 = LFACLK/64"] #[inline(always)] pub fn div64(self) -> &'a mut W { self.variant(LETIMER1_A::DIV64) } #[doc = "LFACLKLETIMER1 = LFACLK/128"] #[inline(always)] pub fn div128(self) -> &'a mut W { self.variant(LETIMER1_A::DIV128) } #[doc = "LFACLKLETIMER1 = LFACLK/256"] #[inline(always)] pub fn div256(self) -> &'a mut W { self.variant(LETIMER1_A::DIV256) } #[doc = "LFACLKLETIMER1 = LFACLK/512"] #[inline(always)] pub fn div512(self) -> &'a mut W { self.variant(LETIMER1_A::DIV512) } #[doc = "LFACLKLETIMER1 = LFACLK/1024"] #[inline(always)] pub fn div1024(self) -> &'a mut W { self.variant(LETIMER1_A::DIV1024) } #[doc = "LFACLKLETIMER1 = LFACLK/2048"] #[inline(always)] pub fn div2048(self) -> &'a mut W { self.variant(LETIMER1_A::DIV2048) } #[doc = "LFACLKLETIMER1 = LFACLK/4096"] #[inline(always)] pub fn div4096(self) -> &'a mut W { self.variant(LETIMER1_A::DIV4096) } #[doc = "LFACLKLETIMER1 = LFACLK/8192"] #[inline(always)] pub fn div8192(self) -> &'a mut W { self.variant(LETIMER1_A::DIV8192) } #[doc = "LFACLKLETIMER1 = LFACLK/16384"] #[inline(always)] pub fn div16384(self) -> &'a mut W { self.variant(LETIMER1_A::DIV16384) } #[doc = "LFACLKLETIMER1 = LFACLK/32768"] #[inline(always)] pub fn div32768(self) -> &'a mut W { self.variant(LETIMER1_A::DIV32768) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 4)) | (((value as u32) & 0x0f) << 4); self.w } } #[doc = "Low Energy Sensor Interface Prescaler\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum LESENSE_A { #[doc = "0: LFACLKLESENSE = LFACLK"] DIV1 = 0, #[doc = "1: LFACLKLESENSE = LFACLK/2"] DIV2 = 1, #[doc = "2: LFACLKLESENSE = LFACLK/4"] DIV4 = 2, #[doc = "3: LFACLKLESENSE = LFACLK/8"] DIV8 = 3, } impl From<LESENSE_A> for u8 { #[inline(always)] fn from(variant: LESENSE_A) -> Self { variant as _ } } #[doc = "Reader of field `LESENSE`"] pub type LESENSE_R = crate::R<u8, LESENSE_A>; impl LESENSE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> LESENSE_A { match self.bits { 0 => LESENSE_A::DIV1, 1 => LESENSE_A::DIV2, 2 => LESENSE_A::DIV4, 3 => LESENSE_A::DIV8, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `DIV1`"] #[inline(always)] pub fn is_div1(&self) -> bool { *self == LESENSE_A::DIV1 } #[doc = "Checks if the value of the field is `DIV2`"] #[inline(always)] pub fn is_div2(&self) -> bool { *self == LESENSE_A::DIV2 } #[doc = "Checks if the value of the field is `DIV4`"] #[inline(always)] pub fn is_div4(&self) -> bool { *self == LESENSE_A::DIV4 } #[doc = "Checks if the value of the field is `DIV8`"] #[inline(always)] pub fn is_div8(&self) -> bool { *self == LESENSE_A::DIV8 } } #[doc = "Write proxy for field `LESENSE`"] pub struct LESENSE_W<'a> { w: &'a mut W, } impl<'a> LESENSE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LESENSE_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "LFACLKLESENSE = LFACLK"] #[inline(always)] pub fn div1(self) -> &'a mut W { self.variant(LESENSE_A::DIV1) } #[doc = "LFACLKLESENSE = LFACLK/2"] #[inline(always)] pub fn div2(self) -> &'a mut W { self.variant(LESENSE_A::DIV2) } #[doc = "LFACLKLESENSE = LFACLK/4"] #[inline(always)] pub fn div4(self) -> &'a mut W { self.variant(LESENSE_A::DIV4) } #[doc = "LFACLKLESENSE = LFACLK/8"] #[inline(always)] pub fn div8(self) -> &'a mut W { self.variant(LESENSE_A::DIV8) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 8)) | (((value as u32) & 0x03) << 8); self.w } } #[doc = "Liquid Crystal Display Controller Prescaler\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum LCD_A { #[doc = "0: LFACLKLCD = LFACLK"] DIV1 = 0, #[doc = "1: LFACLKLCD = LFACLK/2"] DIV2 = 1, #[doc = "2: LFACLKLCD = LFACLK/4"] DIV4 = 2, #[doc = "3: LFACLKLCD = LFACLK/8"] DIV8 = 3, #[doc = "4: LFACLKLCD = LFACLK/16"] DIV16 = 4, #[doc = "5: LFACLKLCD = LFACLK/32"] DIV32 = 5, #[doc = "6: LFACLKLCD = LFACLK/64"] DIV64 = 6, #[doc = "7: LFACLKLCD = LFACLK/128"] DIV128 = 7, } impl From<LCD_A> for u8 { #[inline(always)] fn from(variant: LCD_A) -> Self { variant as _ } } #[doc = "Reader of field `LCD`"] pub type LCD_R = crate::R<u8, LCD_A>; impl LCD_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> LCD_A { match self.bits { 0 => LCD_A::DIV1, 1 => LCD_A::DIV2, 2 => LCD_A::DIV4, 3 => LCD_A::DIV8, 4 => LCD_A::DIV16, 5 => LCD_A::DIV32, 6 => LCD_A::DIV64, 7 => LCD_A::DIV128, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `DIV1`"] #[inline(always)] pub fn is_div1(&self) -> bool { *self == LCD_A::DIV1 } #[doc = "Checks if the value of the field is `DIV2`"] #[inline(always)] pub fn is_div2(&self) -> bool { *self == LCD_A::DIV2 } #[doc = "Checks if the value of the field is `DIV4`"] #[inline(always)] pub fn is_div4(&self) -> bool { *self == LCD_A::DIV4 } #[doc = "Checks if the value of the field is `DIV8`"] #[inline(always)] pub fn is_div8(&self) -> bool { *self == LCD_A::DIV8 } #[doc = "Checks if the value of the field is `DIV16`"] #[inline(always)] pub fn is_div16(&self) -> bool { *self == LCD_A::DIV16 } #[doc = "Checks if the value of the field is `DIV32`"] #[inline(always)] pub fn is_div32(&self) -> bool { *self == LCD_A::DIV32 } #[doc = "Checks if the value of the field is `DIV64`"] #[inline(always)] pub fn is_div64(&self) -> bool { *self == LCD_A::DIV64 } #[doc = "Checks if the value of the field is `DIV128`"] #[inline(always)] pub fn is_div128(&self) -> bool { *self == LCD_A::DIV128 } } #[doc = "Write proxy for field `LCD`"] pub struct LCD_W<'a> { w: &'a mut W, } impl<'a> LCD_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LCD_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "LFACLKLCD = LFACLK"] #[inline(always)] pub fn div1(self) -> &'a mut W { self.variant(LCD_A::DIV1) } #[doc = "LFACLKLCD = LFACLK/2"] #[inline(always)] pub fn div2(self) -> &'a mut W { self.variant(LCD_A::DIV2) } #[doc = "LFACLKLCD = LFACLK/4"] #[inline(always)] pub fn div4(self) -> &'a mut W { self.variant(LCD_A::DIV4) } #[doc = "LFACLKLCD = LFACLK/8"] #[inline(always)] pub fn div8(self) -> &'a mut W { self.variant(LCD_A::DIV8) } #[doc = "LFACLKLCD = LFACLK/16"] #[inline(always)] pub fn div16(self) -> &'a mut W { self.variant(LCD_A::DIV16) } #[doc = "LFACLKLCD = LFACLK/32"] #[inline(always)] pub fn div32(self) -> &'a mut W { self.variant(LCD_A::DIV32) } #[doc = "LFACLKLCD = LFACLK/64"] #[inline(always)] pub fn div64(self) -> &'a mut W { self.variant(LCD_A::DIV64) } #[doc = "LFACLKLCD = LFACLK/128"] #[inline(always)] pub fn div128(self) -> &'a mut W { self.variant(LCD_A::DIV128) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x07 << 12)) | (((value as u32) & 0x07) << 12); self.w } } #[doc = "Real-Time Counter Prescaler\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum RTC_A { #[doc = "0: LFACLKRTC = LFACLK"] DIV1 = 0, #[doc = "1: LFACLKRTC = LFACLK/2"] DIV2 = 1, #[doc = "2: LFACLKRTC = LFACLK/4"] DIV4 = 2, #[doc = "3: LFACLKRTC = LFACLK/8"] DIV8 = 3, #[doc = "4: LFACLKRTC = LFACLK/16"] DIV16 = 4, #[doc = "5: LFACLKRTC = LFACLK/32"] DIV32 = 5, #[doc = "6: LFACLKRTC = LFACLK/64"] DIV64 = 6, #[doc = "7: LFACLKRTC = LFACLK/128"] DIV128 = 7, #[doc = "8: LFACLKRTC = LFACLK/256"] DIV256 = 8, #[doc = "9: LFACLKRTC = LFACLK/512"] DIV512 = 9, #[doc = "10: LFACLKRTC = LFACLK/1024"] DIV1024 = 10, #[doc = "11: LFACLKRTC = LFACLK/2048"] DIV2048 = 11, #[doc = "12: LFACLKRTC = LFACLK/4096"] DIV4096 = 12, #[doc = "13: LFACLKRTC = LFACLK/8192"] DIV8192 = 13, #[doc = "14: LFACLKRTC = LFACLK/16384"] DIV16384 = 14, #[doc = "15: LFACLKRTC = LFACLK/32768"] DIV32768 = 15, } impl From<RTC_A> for u8 { #[inline(always)] fn from(variant: RTC_A) -> Self { variant as _ } } #[doc = "Reader of field `RTC`"] pub type RTC_R = crate::R<u8, RTC_A>; impl RTC_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> RTC_A { match self.bits { 0 => RTC_A::DIV1, 1 => RTC_A::DIV2, 2 => RTC_A::DIV4, 3 => RTC_A::DIV8, 4 => RTC_A::DIV16, 5 => RTC_A::DIV32, 6 => RTC_A::DIV64, 7 => RTC_A::DIV128, 8 => RTC_A::DIV256, 9 => RTC_A::DIV512, 10 => RTC_A::DIV1024, 11 => RTC_A::DIV2048, 12 => RTC_A::DIV4096, 13 => RTC_A::DIV8192, 14 => RTC_A::DIV16384, 15 => RTC_A::DIV32768, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `DIV1`"] #[inline(always)] pub fn is_div1(&self) -> bool { *self == RTC_A::DIV1 } #[doc = "Checks if the value of the field is `DIV2`"] #[inline(always)] pub fn is_div2(&self) -> bool { *self == RTC_A::DIV2 } #[doc = "Checks if the value of the field is `DIV4`"] #[inline(always)] pub fn is_div4(&self) -> bool { *self == RTC_A::DIV4 } #[doc = "Checks if the value of the field is `DIV8`"] #[inline(always)] pub fn is_div8(&self) -> bool { *self == RTC_A::DIV8 } #[doc = "Checks if the value of the field is `DIV16`"] #[inline(always)] pub fn is_div16(&self) -> bool { *self == RTC_A::DIV16 } #[doc = "Checks if the value of the field is `DIV32`"] #[inline(always)] pub fn is_div32(&self) -> bool { *self == RTC_A::DIV32 } #[doc = "Checks if the value of the field is `DIV64`"] #[inline(always)] pub fn is_div64(&self) -> bool { *self == RTC_A::DIV64 } #[doc = "Checks if the value of the field is `DIV128`"] #[inline(always)] pub fn is_div128(&self) -> bool { *self == RTC_A::DIV128 } #[doc = "Checks if the value of the field is `DIV256`"] #[inline(always)] pub fn is_div256(&self) -> bool { *self == RTC_A::DIV256 } #[doc = "Checks if the value of the field is `DIV512`"] #[inline(always)] pub fn is_div512(&self) -> bool { *self == RTC_A::DIV512 } #[doc = "Checks if the value of the field is `DIV1024`"] #[inline(always)] pub fn is_div1024(&self) -> bool { *self == RTC_A::DIV1024 } #[doc = "Checks if the value of the field is `DIV2048`"] #[inline(always)] pub fn is_div2048(&self) -> bool { *self == RTC_A::DIV2048 } #[doc = "Checks if the value of the field is `DIV4096`"] #[inline(always)] pub fn is_div4096(&self) -> bool { *self == RTC_A::DIV4096 } #[doc = "Checks if the value of the field is `DIV8192`"] #[inline(always)] pub fn is_div8192(&self) -> bool { *self == RTC_A::DIV8192 } #[doc = "Checks if the value of the field is `DIV16384`"] #[inline(always)] pub fn is_div16384(&self) -> bool { *self == RTC_A::DIV16384 } #[doc = "Checks if the value of the field is `DIV32768`"] #[inline(always)] pub fn is_div32768(&self) -> bool { *self == RTC_A::DIV32768 } } #[doc = "Write proxy for field `RTC`"] pub struct RTC_W<'a> { w: &'a mut W, } impl<'a> RTC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: RTC_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "LFACLKRTC = LFACLK"] #[inline(always)] pub fn div1(self) -> &'a mut W { self.variant(RTC_A::DIV1) } #[doc = "LFACLKRTC = LFACLK/2"] #[inline(always)] pub fn div2(self) -> &'a mut W { self.variant(RTC_A::DIV2) } #[doc = "LFACLKRTC = LFACLK/4"] #[inline(always)] pub fn div4(self) -> &'a mut W { self.variant(RTC_A::DIV4) } #[doc = "LFACLKRTC = LFACLK/8"] #[inline(always)] pub fn div8(self) -> &'a mut W { self.variant(RTC_A::DIV8) } #[doc = "LFACLKRTC = LFACLK/16"] #[inline(always)] pub fn div16(self) -> &'a mut W { self.variant(RTC_A::DIV16) } #[doc = "LFACLKRTC = LFACLK/32"] #[inline(always)] pub fn div32(self) -> &'a mut W { self.variant(RTC_A::DIV32) } #[doc = "LFACLKRTC = LFACLK/64"] #[inline(always)] pub fn div64(self) -> &'a mut W { self.variant(RTC_A::DIV64) } #[doc = "LFACLKRTC = LFACLK/128"] #[inline(always)] pub fn div128(self) -> &'a mut W { self.variant(RTC_A::DIV128) } #[doc = "LFACLKRTC = LFACLK/256"] #[inline(always)] pub fn div256(self) -> &'a mut W { self.variant(RTC_A::DIV256) } #[doc = "LFACLKRTC = LFACLK/512"] #[inline(always)] pub fn div512(self) -> &'a mut W { self.variant(RTC_A::DIV512) } #[doc = "LFACLKRTC = LFACLK/1024"] #[inline(always)] pub fn div1024(self) -> &'a mut W { self.variant(RTC_A::DIV1024) } #[doc = "LFACLKRTC = LFACLK/2048"] #[inline(always)] pub fn div2048(self) -> &'a mut W { self.variant(RTC_A::DIV2048) } #[doc = "LFACLKRTC = LFACLK/4096"] #[inline(always)] pub fn div4096(self) -> &'a mut W { self.variant(RTC_A::DIV4096) } #[doc = "LFACLKRTC = LFACLK/8192"] #[inline(always)] pub fn div8192(self) -> &'a mut W { self.variant(RTC_A::DIV8192) } #[doc = "LFACLKRTC = LFACLK/16384"] #[inline(always)] pub fn div16384(self) -> &'a mut W { self.variant(RTC_A::DIV16384) } #[doc = "LFACLKRTC = LFACLK/32768"] #[inline(always)] pub fn div32768(self) -> &'a mut W { self.variant(RTC_A::DIV32768) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 16)) | (((value as u32) & 0x0f) << 16); self.w } } impl R { #[doc = "Bits 0:3 - Low Energy Timer 0 Prescaler"] #[inline(always)] pub fn letimer0(&self) -> LETIMER0_R { LETIMER0_R::new((self.bits & 0x0f) as u8) } #[doc = "Bits 4:7 - Low Energy Timer 1 Prescaler"] #[inline(always)] pub fn letimer1(&self) -> LETIMER1_R { LETIMER1_R::new(((self.bits >> 4) & 0x0f) as u8) } #[doc = "Bits 8:9 - Low Energy Sensor Interface Prescaler"] #[inline(always)] pub fn lesense(&self) -> LESENSE_R { LESENSE_R::new(((self.bits >> 8) & 0x03) as u8) } #[doc = "Bits 12:14 - Liquid Crystal Display Controller Prescaler"] #[inline(always)] pub fn lcd(&self) -> LCD_R { LCD_R::new(((self.bits >> 12) & 0x07) as u8) } #[doc = "Bits 16:19 - Real-Time Counter Prescaler"] #[inline(always)] pub fn rtc(&self) -> RTC_R { RTC_R::new(((self.bits >> 16) & 0x0f) as u8) } } impl W { #[doc = "Bits 0:3 - Low Energy Timer 0 Prescaler"] #[inline(always)] pub fn letimer0(&mut self) -> LETIMER0_W { LETIMER0_W { w: self } } #[doc = "Bits 4:7 - Low Energy Timer 1 Prescaler"] #[inline(always)] pub fn letimer1(&mut self) -> LETIMER1_W { LETIMER1_W { w: self } } #[doc = "Bits 8:9 - Low Energy Sensor Interface Prescaler"] #[inline(always)] pub fn lesense(&mut self) -> LESENSE_W { LESENSE_W { w: self } } #[doc = "Bits 12:14 - Liquid Crystal Display Controller Prescaler"] #[inline(always)] pub fn lcd(&mut self) -> LCD_W { LCD_W { w: self } } #[doc = "Bits 16:19 - Real-Time Counter Prescaler"] #[inline(always)] pub fn rtc(&mut self) -> RTC_W { RTC_W { w: self } } }
38.035897
93
0.570076
e2784c26dbbaea4e526e936766034aa018dbeaf7
520
// Copyright 2013 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. #[derive(Clone)] struct S((), ()); pub fn main() {}
34.666667
68
0.721154
abdc566dcccda0b2194124b81474c86850d82af0
51,409
pub type rlim_t = ::uintptr_t; pub type sa_family_t = u8; pub type pthread_key_t = ::c_int; pub type nfds_t = ::c_ulong; pub type tcflag_t = ::c_uint; pub type speed_t = ::c_uchar; pub type c_char = i8; pub type clock_t = i32; pub type clockid_t = i32; pub type suseconds_t = i32; pub type wchar_t = i32; pub type off_t = i64; pub type ino_t = i64; pub type blkcnt_t = i64; pub type blksize_t = i32; pub type dev_t = i32; pub type mode_t = u32; pub type nlink_t = i32; pub type useconds_t = u32; pub type socklen_t = u32; pub type pthread_t = ::uintptr_t; pub type pthread_condattr_t = ::uintptr_t; pub type pthread_mutexattr_t = ::uintptr_t; pub type pthread_rwlockattr_t = ::uintptr_t; pub type sigset_t = u64; pub type fsblkcnt_t = i64; pub type fsfilcnt_t = i64; pub type pthread_attr_t = *mut ::c_void; pub type nl_item = ::c_int; pub type id_t = i32; pub type idtype_t = ::c_uint; pub type fd_mask = u32; #[cfg_attr(feature = "extra_traits", derive(Debug))] pub enum timezone {} impl ::Copy for timezone {} impl ::Clone for timezone { fn clone(&self) -> timezone { *self } } impl siginfo_t { pub unsafe fn si_addr(&self) -> *mut ::c_void { self.si_addr } pub unsafe fn si_pid(&self) -> ::pid_t { self.si_pid } pub unsafe fn si_uid(&self) -> ::uid_t { self.si_uid } pub unsafe fn si_status(&self) -> ::c_int { self.si_status } } s! { pub struct in_addr { pub s_addr: ::in_addr_t, } pub struct ip_mreq { pub imr_multiaddr: in_addr, pub imr_interface: in_addr, } pub struct sockaddr { pub sa_len: u8, pub sa_family: sa_family_t, pub sa_data: [u8; 30], } pub struct sockaddr_in { pub sin_len: u8, pub sin_family: sa_family_t, pub sin_port: ::in_port_t, pub sin_addr: ::in_addr, pub sin_zero: [i8; 24], } pub struct sockaddr_in6 { pub sin6_len: u8, pub sin6_family: u8, pub sin6_port: u16, pub sin6_flowinfo: u32, pub sin6_addr: ::in6_addr, pub sin6_scope_id: u32, } pub struct addrinfo { pub ai_flags: ::c_int, pub ai_family: ::c_int, pub ai_socktype: ::c_int, pub ai_protocol: ::c_int, pub ai_addrlen: socklen_t, pub ai_canonname: *mut c_char, pub ai_addr: *mut ::sockaddr, pub ai_next: *mut addrinfo, } pub struct fd_set { // size for 1024 bits, and a fd_mask with size u32 fds_bits: [fd_mask; 32], } pub struct tm { pub tm_sec: ::c_int, pub tm_min: ::c_int, pub tm_hour: ::c_int, pub tm_mday: ::c_int, pub tm_mon: ::c_int, pub tm_year: ::c_int, pub tm_wday: ::c_int, pub tm_yday: ::c_int, pub tm_isdst: ::c_int, pub tm_gmtoff: ::c_int, pub tm_zone: *mut ::c_char, } pub struct utsname { pub sysname: [::c_char; 32], pub nodename: [::c_char; 32], pub release: [::c_char; 32], pub version: [::c_char; 32], pub machine: [::c_char; 32], } pub struct lconv { pub decimal_point: *mut ::c_char, pub thousands_sep: *mut ::c_char, pub grouping: *mut ::c_char, pub int_curr_symbol: *mut ::c_char, pub currency_symbol: *mut ::c_char, pub mon_decimal_point: *mut ::c_char, pub mon_thousands_sep: *mut ::c_char, pub mon_grouping: *mut ::c_char, pub positive_sign: *mut ::c_char, pub negative_sign: *mut ::c_char, pub int_frac_digits: ::c_char, pub frac_digits: ::c_char, pub p_cs_precedes: ::c_char, pub p_sep_by_space: ::c_char, pub n_cs_precedes: ::c_char, pub n_sep_by_space: ::c_char, pub p_sign_posn: ::c_char, pub n_sign_posn: ::c_char, pub int_p_cs_precedes: ::c_char, pub int_p_sep_by_space: ::c_char, pub int_n_cs_precedes: ::c_char, pub int_n_sep_by_space: ::c_char, pub int_p_sign_posn: ::c_char, pub int_n_sign_posn: ::c_char, } pub struct msghdr { pub msg_name: *mut ::c_void, pub msg_namelen: socklen_t, pub msg_iov: *mut ::iovec, pub msg_iovlen: ::c_int, pub msg_control: *mut ::c_void, pub msg_controllen: socklen_t, pub msg_flags: ::c_int, } pub struct cmsghdr { pub cmsg_len: ::socklen_t, pub cmsg_level: ::c_int, pub cmsg_type: ::c_int, } pub struct Dl_info { pub dli_fname: *const ::c_char, pub dli_fbase: *mut ::c_void, pub dli_sname: *const ::c_char, pub dli_saddr: *mut ::c_void, } pub struct termios { pub c_iflag: ::tcflag_t, pub c_oflag: ::tcflag_t, pub c_cflag: ::tcflag_t, pub c_lflag: ::tcflag_t, pub c_line: ::c_char, pub c_ispeed: ::speed_t, pub c_ospeed: ::speed_t, pub c_cc: [::cc_t; ::NCCS], } pub struct flock { pub l_type: ::c_short, pub l_whence: ::c_short, pub l_start: ::off_t, pub l_len: ::off_t, pub l_pid: ::pid_t, } pub struct stat { pub st_dev: dev_t, pub st_ino: ino_t, pub st_mode: mode_t, pub st_nlink: nlink_t, pub st_uid: ::uid_t, pub st_gid: ::gid_t, pub st_size: off_t, pub st_rdev: dev_t, pub st_blksize: blksize_t, pub st_atime: time_t, pub st_atime_nsec: c_long, pub st_mtime: time_t, pub st_mtime_nsec: c_long, pub st_ctime: time_t, pub st_ctime_nsec: c_long, pub st_crtime: time_t, pub st_crtime_nsec: c_long, pub st_type: u32, pub st_blocks: blkcnt_t, } pub struct glob_t { pub gl_pathc: ::size_t, __unused1: ::size_t, pub gl_offs: ::size_t, __unused2: ::size_t, pub gl_pathv: *mut *mut c_char, __unused3: *mut ::c_void, __unused4: *mut ::c_void, __unused5: *mut ::c_void, __unused6: *mut ::c_void, __unused7: *mut ::c_void, __unused8: *mut ::c_void, } pub struct pthread_mutex_t { flags: u32, lock: i32, unused: i32, owner: i32, owner_count: i32, } pub struct pthread_cond_t { flags: u32, unused: i32, mutex: *mut ::c_void, waiter_count: i32, lock: i32, } pub struct pthread_rwlock_t { flags: u32, owner: i32, lock_sem: i32, // this is actually a union lock_count: i32, reader_count: i32, writer_count: i32, waiters: [*mut ::c_void; 2], } pub struct passwd { pub pw_name: *mut ::c_char, pub pw_passwd: *mut ::c_char, pub pw_uid: ::uid_t, pub pw_gid: ::gid_t, pub pw_dir: *mut ::c_char, pub pw_shell: *mut ::c_char, pub pw_gecos: *mut ::c_char, } pub struct statvfs { pub f_bsize: ::c_ulong, pub f_frsize: ::c_ulong, pub f_blocks: ::fsblkcnt_t, pub f_bfree: ::fsblkcnt_t, pub f_bavail: ::fsblkcnt_t, pub f_files: ::fsfilcnt_t, pub f_ffree: ::fsfilcnt_t, pub f_favail: ::fsfilcnt_t, pub f_fsid: ::c_ulong, pub f_flag: ::c_ulong, pub f_namemax: ::c_ulong, } pub struct stack_t { pub ss_sp: *mut ::c_void, pub ss_size: ::size_t, pub ss_flags: ::c_int, } pub struct siginfo_t { pub si_signo: ::c_int, pub si_code: ::c_int, pub si_errno: ::c_int, pub si_pid: ::pid_t, pub si_uid: ::uid_t, pub si_addr: *mut ::c_void, pub si_status: ::c_int, pub si_band: c_long, pub sigval: *mut ::c_void, } pub struct sigaction { pub sa_sigaction: ::sighandler_t, //actually a union with sa_handler pub sa_mask: ::sigset_t, pub sa_flags: ::c_int, sa_userdata: *mut ::c_void, } pub struct sem_t { pub type_: i32, pub named_sem_id: i32, // actually a union with unnamed_sem (i32) pub padding: [i32; 2], } pub struct ucred { pub pid: ::pid_t, pub uid: ::uid_t, pub gid: ::gid_t, } } s_no_extra_traits! { pub struct sockaddr_un { pub sun_len: u8, pub sun_family: sa_family_t, pub sun_path: [::c_char; 126] } pub struct sockaddr_storage { pub ss_len: u8, pub ss_family: sa_family_t, __ss_pad1: [u8; 6], __ss_pad2: u64, __ss_pad3: [u8; 112], } pub struct dirent { pub d_dev: dev_t, pub d_pdev: dev_t, pub d_ino: ino_t, pub d_pino: i64, pub d_reclen: ::c_ushort, pub d_name: [::c_char; 1024], // Max length is _POSIX_PATH_MAX } pub struct sigevent { pub sigev_notify: ::c_int, pub sigev_signo: ::c_int, pub sigev_value: ::sigval, __unused1: *mut ::c_void, // actually a function pointer pub sigev_notify_attributes: *mut ::pthread_attr_t, } } cfg_if! { if #[cfg(feature = "extra_traits")] { impl PartialEq for sockaddr_un { fn eq(&self, other: &sockaddr_un) -> bool { self.sun_len == other.sun_len && self.sun_family == other.sun_family && self .sun_path .iter() .zip(other.sun_path.iter()) .all(|(a,b)| a == b) } } impl Eq for sockaddr_un {} impl ::fmt::Debug for sockaddr_un { fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result { f.debug_struct("sockaddr_un") .field("sun_len", &self.sun_len) .field("sun_family", &self.sun_family) // FIXME: .field("sun_path", &self.sun_path) .finish() } } impl ::hash::Hash for sockaddr_un { fn hash<H: ::hash::Hasher>(&self, state: &mut H) { self.sun_len.hash(state); self.sun_family.hash(state); self.sun_path.hash(state); } } impl PartialEq for sockaddr_storage { fn eq(&self, other: &sockaddr_storage) -> bool { self.ss_len == other.ss_len && self.ss_family == other.ss_family && self .__ss_pad1 .iter() .zip(other.__ss_pad1.iter()) .all(|(a, b)| a == b) && self.__ss_pad2 == other.__ss_pad2 && self .__ss_pad3 .iter() .zip(other.__ss_pad3.iter()) .all(|(a, b)| a == b) } } impl Eq for sockaddr_storage {} impl ::fmt::Debug for sockaddr_storage { fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result { f.debug_struct("sockaddr_storage") .field("ss_len", &self.ss_len) .field("ss_family", &self.ss_family) .field("__ss_pad1", &self.__ss_pad1) .field("__ss_pad2", &self.__ss_pad2) // FIXME: .field("__ss_pad3", &self.__ss_pad3) .finish() } } impl ::hash::Hash for sockaddr_storage { fn hash<H: ::hash::Hasher>(&self, state: &mut H) { self.ss_len.hash(state); self.ss_family.hash(state); self.__ss_pad1.hash(state); self.__ss_pad2.hash(state); self.__ss_pad3.hash(state); } } impl PartialEq for dirent { fn eq(&self, other: &dirent) -> bool { self.d_dev == other.d_dev && self.d_pdev == other.d_pdev && self.d_ino == other.d_ino && self.d_pino == other.d_pino && self.d_reclen == other.d_reclen && self .d_name .iter() .zip(other.d_name.iter()) .all(|(a,b)| a == b) } } impl Eq for dirent {} impl ::fmt::Debug for dirent { fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result { f.debug_struct("dirent") .field("d_dev", &self.d_dev) .field("d_pdev", &self.d_pdev) .field("d_ino", &self.d_ino) .field("d_pino", &self.d_pino) .field("d_reclen", &self.d_reclen) // FIXME: .field("d_name", &self.d_name) .finish() } } impl ::hash::Hash for dirent { fn hash<H: ::hash::Hasher>(&self, state: &mut H) { self.d_dev.hash(state); self.d_pdev.hash(state); self.d_ino.hash(state); self.d_pino.hash(state); self.d_reclen.hash(state); self.d_name.hash(state); } } impl PartialEq for sigevent { fn eq(&self, other: &sigevent) -> bool { self.sigev_notify == other.sigev_notify && self.sigev_signo == other.sigev_signo && self.sigev_value == other.sigev_value && self.sigev_notify_attributes == other.sigev_notify_attributes } } impl Eq for sigevent {} impl ::fmt::Debug for sigevent { fn fmt(&self, f: &mut ::fmt::Formatter) -> ::fmt::Result { f.debug_struct("sigevent") .field("sigev_notify", &self.sigev_notify) .field("sigev_signo", &self.sigev_signo) .field("sigev_value", &self.sigev_value) .field("sigev_notify_attributes", &self.sigev_notify_attributes) .finish() } } impl ::hash::Hash for sigevent { fn hash<H: ::hash::Hasher>(&self, state: &mut H) { self.sigev_notify.hash(state); self.sigev_signo.hash(state); self.sigev_value.hash(state); self.sigev_notify_attributes.hash(state); } } } } pub const EXIT_FAILURE: ::c_int = 1; pub const EXIT_SUCCESS: ::c_int = 0; pub const RAND_MAX: ::c_int = 2147483647; pub const EOF: ::c_int = -1; pub const SEEK_SET: ::c_int = 0; pub const SEEK_CUR: ::c_int = 1; pub const SEEK_END: ::c_int = 2; pub const _IOFBF: ::c_int = 0; pub const _IONBF: ::c_int = 2; pub const _IOLBF: ::c_int = 1; pub const F_DUPFD: ::c_int = 0x0001; pub const F_GETFD: ::c_int = 0x0002; pub const F_SETFD: ::c_int = 0x0004; pub const F_GETFL: ::c_int = 0x0008; pub const F_SETFL: ::c_int = 0x0010; pub const F_GETLK: ::c_int = 0x0020; pub const F_SETLK: ::c_int = 0x0080; pub const F_SETLKW: ::c_int = 0x0100; pub const F_DUPFD_CLOEXEC: ::c_int = 0x0200; pub const F_RDLCK: ::c_int = 0x0040; pub const F_UNLCK: ::c_int = 0x0200; pub const F_WRLCK: ::c_int = 0x0400; pub const AT_FDCWD: ::c_int = -1; pub const AT_SYMLINK_NOFOLLOW: ::c_int = 0x01; pub const AT_SYMLINK_FOLLOW: ::c_int = 0x02; pub const AT_REMOVEDIR: ::c_int = 0x04; pub const AT_EACCESS: ::c_int = 0x08; pub const POLLIN: ::c_short = 0x0001; pub const POLLOUT: ::c_short = 0x0002; pub const POLLRDNORM: ::c_short = POLLIN; pub const POLLWRNORM: ::c_short = POLLOUT; pub const POLLRDBAND: ::c_short = 0x0008; pub const POLLWRBAND: ::c_short = 0x0010; pub const POLLPRI: ::c_short = 0x0020; pub const POLLERR: ::c_short = 0x0004; pub const POLLHUP: ::c_short = 0x0080; pub const POLLNVAL: ::c_short = 0x1000; pub const PTHREAD_CREATE_JOINABLE: ::c_int = 0; pub const PTHREAD_CREATE_DETACHED: ::c_int = 1; pub const CLOCK_REALTIME: ::c_int = -1; pub const CLOCK_MONOTONIC: ::c_int = 0; pub const RLIMIT_CORE: ::c_int = 0; pub const RLIMIT_CPU: ::c_int = 1; pub const RLIMIT_DATA: ::c_int = 2; pub const RLIMIT_FSIZE: ::c_int = 3; pub const RLIMIT_NOFILE: ::c_int = 4; pub const RLIMIT_STACK: ::c_int = 5; pub const RLIMIT_AS: ::c_int = 6; // Haiku specific pub const RLIMIT_NOVMON: ::c_int = 7; pub const RLIM_NLIMITS: ::c_int = 8; pub const RUSAGE_SELF: ::c_int = 0; pub const RTLD_LAZY: ::c_int = 0; pub const NCCS: usize = 11; pub const O_RDONLY: ::c_int = 0x0000; pub const O_WRONLY: ::c_int = 0x0001; pub const O_RDWR: ::c_int = 0x0002; pub const O_ACCMODE: ::c_int = 0x0003; pub const O_EXCL: ::c_int = 0x0100; pub const O_CREAT: ::c_int = 0x0200; pub const O_TRUNC: ::c_int = 0x0400; pub const O_NOCTTY: ::c_int = 0x1000; pub const O_NOTRAVERSE: ::c_int = 0x2000; pub const O_CLOEXEC: ::c_int = 0x00000040; pub const O_NONBLOCK: ::c_int = 0x00000080; pub const O_APPEND: ::c_int = 0x00000800; pub const O_SYNC: ::c_int = 0x00010000; pub const O_RSYNC: ::c_int = 0x00020000; pub const O_DSYNC: ::c_int = 0x00040000; pub const O_NOFOLLOW: ::c_int = 0x00080000; pub const O_NOCACHE: ::c_int = 0x00100000; pub const O_DIRECTORY: ::c_int = 0x00200000; pub const S_IFIFO: ::mode_t = 4096; pub const S_IFCHR: ::mode_t = 8192; pub const S_IFBLK: ::mode_t = 24576; pub const S_IFDIR: ::mode_t = 16384; pub const S_IFREG: ::mode_t = 32768; pub const S_IFLNK: ::mode_t = 40960; pub const S_IFSOCK: ::mode_t = 49152; pub const S_IFMT: ::mode_t = 61440; pub const S_IRWXU: ::mode_t = 0o00700; pub const S_IRUSR: ::mode_t = 0o00400; pub const S_IWUSR: ::mode_t = 0o00200; pub const S_IXUSR: ::mode_t = 0o00100; pub const S_IRWXG: ::mode_t = 0o00070; pub const S_IRGRP: ::mode_t = 0o00040; pub const S_IWGRP: ::mode_t = 0o00020; pub const S_IXGRP: ::mode_t = 0o00010; pub const S_IRWXO: ::mode_t = 0o00007; pub const S_IROTH: ::mode_t = 0o00004; pub const S_IWOTH: ::mode_t = 0o00002; pub const S_IXOTH: ::mode_t = 0o00001; pub const F_OK: ::c_int = 0; pub const R_OK: ::c_int = 4; pub const W_OK: ::c_int = 2; pub const X_OK: ::c_int = 1; pub const STDIN_FILENO: ::c_int = 0; pub const STDOUT_FILENO: ::c_int = 1; pub const STDERR_FILENO: ::c_int = 2; pub const SIGHUP: ::c_int = 1; pub const SIGINT: ::c_int = 2; pub const SIGQUIT: ::c_int = 3; pub const SIGILL: ::c_int = 4; pub const SIGCHLD: ::c_int = 5; pub const SIGABRT: ::c_int = 6; pub const SIGPIPE: ::c_int = 7; pub const SIGFPE: ::c_int = 8; pub const SIGKILL: ::c_int = 9; pub const SIGSTOP: ::c_int = 10; pub const SIGSEGV: ::c_int = 11; pub const SIGCONT: ::c_int = 12; pub const SIGTSTP: ::c_int = 13; pub const SIGALRM: ::c_int = 14; pub const SIGTERM: ::c_int = 15; pub const SIGTTIN: ::c_int = 16; pub const SIGTTOU: ::c_int = 17; pub const SIGUSR1: ::c_int = 18; pub const SIGUSR2: ::c_int = 19; pub const SIGWINCH: ::c_int = 20; pub const SIGKILLTHR: ::c_int = 21; pub const SIGTRAP: ::c_int = 22; pub const SIGPOLL: ::c_int = 23; pub const SIGPROF: ::c_int = 24; pub const SIGSYS: ::c_int = 25; pub const SIGURG: ::c_int = 26; pub const SIGVTALRM: ::c_int = 27; pub const SIGXCPU: ::c_int = 28; pub const SIGXFSZ: ::c_int = 29; pub const SIGBUS: ::c_int = 30; pub const SIG_BLOCK: ::c_int = 1; pub const SIG_UNBLOCK: ::c_int = 2; pub const SIG_SETMASK: ::c_int = 3; pub const SIGEV_NONE: ::c_int = 0; pub const SIGEV_SIGNAL: ::c_int = 1; pub const SIGEV_THREAD: ::c_int = 2; pub const EAI_AGAIN: ::c_int = 2; pub const EAI_BADFLAGS: ::c_int = 3; pub const EAI_FAIL: ::c_int = 4; pub const EAI_FAMILY: ::c_int = 5; pub const EAI_MEMORY: ::c_int = 6; pub const EAI_NODATA: ::c_int = 7; pub const EAI_NONAME: ::c_int = 8; pub const EAI_SERVICE: ::c_int = 9; pub const EAI_SOCKTYPE: ::c_int = 10; pub const EAI_SYSTEM: ::c_int = 11; pub const EAI_OVERFLOW: ::c_int = 14; pub const PROT_NONE: ::c_int = 0; pub const PROT_READ: ::c_int = 1; pub const PROT_WRITE: ::c_int = 2; pub const PROT_EXEC: ::c_int = 4; pub const LC_ALL: ::c_int = 0; pub const LC_COLLATE: ::c_int = 1; pub const LC_CTYPE: ::c_int = 2; pub const LC_MONETARY: ::c_int = 3; pub const LC_NUMERIC: ::c_int = 4; pub const LC_TIME: ::c_int = 5; pub const LC_MESSAGES: ::c_int = 6; // FIXME: Haiku does not have MAP_FILE, but libstd/os.rs requires it pub const MAP_FILE: ::c_int = 0x00; pub const MAP_SHARED: ::c_int = 0x01; pub const MAP_PRIVATE: ::c_int = 0x02; pub const MAP_FIXED: ::c_int = 0x04; pub const MAP_ANONYMOUS: ::c_int = 0x08; pub const MAP_ANON: ::c_int = MAP_ANONYMOUS; pub const MAP_FAILED: *mut ::c_void = !0 as *mut ::c_void; pub const MS_ASYNC: ::c_int = 0x01; pub const MS_INVALIDATE: ::c_int = 0x04; pub const MS_SYNC: ::c_int = 0x02; pub const E2BIG: ::c_int = -2147454975; pub const ECHILD: ::c_int = -2147454974; pub const EDEADLK: ::c_int = -2147454973; pub const EFBIG: ::c_int = -2147454972; pub const EMLINK: ::c_int = -2147454971; pub const ENFILE: ::c_int = -2147454970; pub const ENODEV: ::c_int = -2147454969; pub const ENOLCK: ::c_int = -2147454968; pub const ENOSYS: ::c_int = -2147454967; pub const ENOTTY: ::c_int = -2147454966; pub const ENXIO: ::c_int = -2147454965; pub const ESPIPE: ::c_int = -2147454964; pub const ESRCH: ::c_int = -2147454963; pub const EFPOS: ::c_int = -2147454962; pub const ESIGPARM: ::c_int = -2147454961; pub const EDOM: ::c_int = -2147454960; pub const ERANGE: ::c_int = -2147454959; pub const EPROTOTYPE: ::c_int = -2147454958; pub const EPROTONOSUPPORT: ::c_int = -2147454957; pub const EPFNOSUPPORT: ::c_int = -2147454956; pub const EAFNOSUPPORT: ::c_int = -2147454955; pub const EADDRINUSE: ::c_int = -2147454954; pub const EADDRNOTAVAIL: ::c_int = -2147454953; pub const ENETDOWN: ::c_int = -2147454952; pub const ENETUNREACH: ::c_int = -2147454951; pub const ENETRESET: ::c_int = -2147454950; pub const ECONNABORTED: ::c_int = -2147454949; pub const ECONNRESET: ::c_int = -2147454948; pub const EISCONN: ::c_int = -2147454947; pub const ENOTCONN: ::c_int = -2147454946; pub const ESHUTDOWN: ::c_int = -2147454945; pub const ECONNREFUSED: ::c_int = -2147454944; pub const EHOSTUNREACH: ::c_int = -2147454943; pub const ENOPROTOOPT: ::c_int = -2147454942; pub const ENOBUFS: ::c_int = -2147454941; pub const EINPROGRESS: ::c_int = -2147454940; pub const EALREADY: ::c_int = -2147454939; pub const EILSEQ: ::c_int = -2147454938; pub const ENOMSG: ::c_int = -2147454937; pub const ESTALE: ::c_int = -2147454936; pub const EOVERFLOW: ::c_int = -2147454935; pub const EMSGSIZE: ::c_int = -2147454934; pub const EOPNOTSUPP: ::c_int = -2147454933; pub const ENOTSOCK: ::c_int = -2147454932; pub const EHOSTDOWN: ::c_int = -2147454931; pub const EBADMSG: ::c_int = -2147454930; pub const ECANCELED: ::c_int = -2147454929; pub const EDESTADDRREQ: ::c_int = -2147454928; pub const EDQUOT: ::c_int = -2147454927; pub const EIDRM: ::c_int = -2147454926; pub const EMULTIHOP: ::c_int = -2147454925; pub const ENODATA: ::c_int = -2147454924; pub const ENOLINK: ::c_int = -2147454923; pub const ENOSR: ::c_int = -2147454922; pub const ENOSTR: ::c_int = -2147454921; pub const ENOTSUP: ::c_int = -2147454920; pub const EPROTO: ::c_int = -2147454919; pub const ETIME: ::c_int = -2147454918; pub const ETXTBSY: ::c_int = -2147454917; pub const ENOATTR: ::c_int = -2147454916; // INT_MIN pub const ENOMEM: ::c_int = -2147483648; // POSIX errors that can be mapped to BeOS error codes pub const EACCES: ::c_int = -2147483646; pub const EINTR: ::c_int = -2147483638; pub const EIO: ::c_int = -2147483647; pub const EBUSY: ::c_int = -2147483634; pub const EFAULT: ::c_int = -2147478783; pub const ETIMEDOUT: ::c_int = -2147483639; pub const EAGAIN: ::c_int = -2147483637; pub const EWOULDBLOCK: ::c_int = -2147483637; pub const EBADF: ::c_int = -2147459072; pub const EEXIST: ::c_int = -2147459070; pub const EINVAL: ::c_int = -2147483643; pub const ENAMETOOLONG: ::c_int = -2147459068; pub const ENOENT: ::c_int = -2147459069; pub const EPERM: ::c_int = -2147483633; pub const ENOTDIR: ::c_int = -2147459067; pub const EISDIR: ::c_int = -2147459063; pub const ENOTEMPTY: ::c_int = -2147459066; pub const ENOSPC: ::c_int = -2147459065; pub const EROFS: ::c_int = -2147459064; pub const EMFILE: ::c_int = -2147459062; pub const EXDEV: ::c_int = -2147459061; pub const ELOOP: ::c_int = -2147459060; pub const ENOEXEC: ::c_int = -2147478782; pub const EPIPE: ::c_int = -2147459059; pub const IPPROTO_RAW: ::c_int = 255; // These are prefixed with POSIX_ on Haiku pub const MADV_NORMAL: ::c_int = 1; pub const MADV_SEQUENTIAL: ::c_int = 2; pub const MADV_RANDOM: ::c_int = 3; pub const MADV_WILLNEED: ::c_int = 4; pub const MADV_DONTNEED: ::c_int = 5; // https://github.com/haiku/haiku/blob/master/headers/posix/net/if.h#L80 pub const IFF_UP: ::c_int = 0x0001; pub const IFF_BROADCAST: ::c_int = 0x0002; // valid broadcast address pub const IFF_LOOPBACK: ::c_int = 0x0008; pub const IFF_POINTOPOINT: ::c_int = 0x0010; // point-to-point link pub const IFF_NOARP: ::c_int = 0x0040; // no address resolution pub const IFF_AUTOUP: ::c_int = 0x0080; // auto dial pub const IFF_PROMISC: ::c_int = 0x0100; // receive all packets pub const IFF_ALLMULTI: ::c_int = 0x0200; // receive all multicast packets pub const IFF_SIMPLEX: ::c_int = 0x0800; // doesn't receive own transmissions pub const IFF_LINK: ::c_int = 0x1000; // has link pub const IFF_AUTO_CONFIGURED: ::c_int = 0x2000; pub const IFF_CONFIGURING: ::c_int = 0x4000; pub const IFF_MULTICAST: ::c_int = 0x8000; // supports multicast pub const AF_UNSPEC: ::c_int = 0; pub const AF_INET: ::c_int = 1; pub const AF_APPLETALK: ::c_int = 2; pub const AF_ROUTE: ::c_int = 3; pub const AF_LINK: ::c_int = 4; pub const AF_INET6: ::c_int = 5; pub const AF_DLI: ::c_int = 6; pub const AF_IPX: ::c_int = 7; pub const AF_NOTIFY: ::c_int = 8; pub const AF_LOCAL: ::c_int = 9; pub const AF_UNIX: ::c_int = AF_LOCAL; pub const AF_BLUETOOTH: ::c_int = 10; pub const IP_OPTIONS: ::c_int = 1; pub const IP_HDRINCL: ::c_int = 2; pub const IP_TOS: ::c_int = 3; pub const IP_TTL: ::c_int = 4; pub const IP_RECVOPTS: ::c_int = 5; pub const IP_RECVRETOPTS: ::c_int = 6; pub const IP_RECVDSTADDR: ::c_int = 7; pub const IP_RETOPTS: ::c_int = 8; pub const IP_MULTICAST_IF: ::c_int = 9; pub const IP_MULTICAST_TTL: ::c_int = 10; pub const IP_MULTICAST_LOOP: ::c_int = 11; pub const IP_ADD_MEMBERSHIP: ::c_int = 12; pub const IP_DROP_MEMBERSHIP: ::c_int = 13; pub const IP_BLOCK_SOURCE: ::c_int = 14; pub const IP_UNBLOCK_SOURCE: ::c_int = 15; pub const IP_ADD_SOURCE_MEMBERSHIP: ::c_int = 16; pub const IP_DROP_SOURCE_MEMBERSHIP: ::c_int = 17; pub const TCP_NODELAY: ::c_int = 0x01; pub const TCP_MAXSEG: ::c_int = 0x02; pub const TCP_NOPUSH: ::c_int = 0x04; pub const TCP_NOOPT: ::c_int = 0x08; pub const IF_NAMESIZE: ::size_t = 32; pub const IFNAMSIZ: ::size_t = IF_NAMESIZE; pub const IPV6_MULTICAST_IF: ::c_int = 24; pub const IPV6_MULTICAST_HOPS: ::c_int = 25; pub const IPV6_MULTICAST_LOOP: ::c_int = 26; pub const IPV6_UNICAST_HOPS: ::c_int = 27; pub const IPV6_JOIN_GROUP: ::c_int = 28; pub const IPV6_LEAVE_GROUP: ::c_int = 29; pub const IPV6_V6ONLY: ::c_int = 30; pub const IPV6_PKTINFO: ::c_int = 31; pub const IPV6_RECVPKTINFO: ::c_int = 32; pub const IPV6_HOPLIMIT: ::c_int = 33; pub const IPV6_RECVHOPLIMIT: ::c_int = 34; pub const IPV6_HOPOPTS: ::c_int = 35; pub const IPV6_DSTOPTS: ::c_int = 36; pub const IPV6_RTHDR: ::c_int = 37; pub const MSG_OOB: ::c_int = 0x0001; pub const MSG_PEEK: ::c_int = 0x0002; pub const MSG_DONTROUTE: ::c_int = 0x0004; pub const MSG_EOR: ::c_int = 0x0008; pub const MSG_TRUNC: ::c_int = 0x0010; pub const MSG_CTRUNC: ::c_int = 0x0020; pub const MSG_WAITALL: ::c_int = 0x0040; pub const MSG_DONTWAIT: ::c_int = 0x0080; pub const MSG_BCAST: ::c_int = 0x0100; pub const MSG_MCAST: ::c_int = 0x0200; pub const MSG_EOF: ::c_int = 0x0400; pub const MSG_NOSIGNAL: ::c_int = 0x0800; pub const SHUT_RD: ::c_int = 0; pub const SHUT_WR: ::c_int = 1; pub const SHUT_RDWR: ::c_int = 2; pub const LOCK_SH: ::c_int = 0x01; pub const LOCK_EX: ::c_int = 0x02; pub const LOCK_NB: ::c_int = 0x04; pub const LOCK_UN: ::c_int = 0x08; pub const SIGSTKSZ: ::size_t = 16384; pub const IOV_MAX: ::c_int = 1024; pub const PATH_MAX: ::c_int = 1024; pub const SA_NOCLDSTOP: ::c_int = 0x01; pub const SA_NOCLDWAIT: ::c_int = 0x02; pub const SA_RESETHAND: ::c_int = 0x04; pub const SA_NODEFER: ::c_int = 0x08; pub const SA_RESTART: ::c_int = 0x10; pub const SA_ONSTACK: ::c_int = 0x20; pub const SA_SIGINFO: ::c_int = 0x40; pub const SA_NOMASK: ::c_int = SA_NODEFER; pub const SA_STACK: ::c_int = SA_ONSTACK; pub const SA_ONESHOT: ::c_int = SA_RESETHAND; pub const FD_SETSIZE: usize = 1024; pub const RTLD_LOCAL: ::c_int = 0x0; pub const RTLD_NOW: ::c_int = 0x1; pub const RTLD_GLOBAL: ::c_int = 0x2; pub const RTLD_DEFAULT: *mut ::c_void = 0isize as *mut ::c_void; pub const BUFSIZ: ::c_uint = 8192; pub const FILENAME_MAX: ::c_uint = 256; pub const FOPEN_MAX: ::c_uint = 128; pub const L_tmpnam: ::c_uint = 512; pub const TMP_MAX: ::c_uint = 32768; pub const _PC_CHOWN_RESTRICTED: ::c_int = 1; pub const _PC_MAX_CANON: ::c_int = 2; pub const _PC_MAX_INPUT: ::c_int = 3; pub const _PC_NAME_MAX: ::c_int = 4; pub const _PC_NO_TRUNC: ::c_int = 5; pub const _PC_PATH_MAX: ::c_int = 6; pub const _PC_PIPE_BUF: ::c_int = 7; pub const _PC_VDISABLE: ::c_int = 8; pub const _PC_LINK_MAX: ::c_int = 25; pub const _PC_SYNC_IO: ::c_int = 26; pub const _PC_ASYNC_IO: ::c_int = 27; pub const _PC_PRIO_IO: ::c_int = 28; pub const _PC_SOCK_MAXBUF: ::c_int = 29; pub const _PC_FILESIZEBITS: ::c_int = 30; pub const _PC_REC_INCR_XFER_SIZE: ::c_int = 31; pub const _PC_REC_MAX_XFER_SIZE: ::c_int = 32; pub const _PC_REC_MIN_XFER_SIZE: ::c_int = 33; pub const _PC_REC_XFER_ALIGN: ::c_int = 34; pub const _PC_ALLOC_SIZE_MIN: ::c_int = 35; pub const _PC_SYMLINK_MAX: ::c_int = 36; pub const _PC_2_SYMLINKS: ::c_int = 37; pub const _PC_XATTR_EXISTS: ::c_int = 38; pub const _PC_XATTR_ENABLED: ::c_int = 39; pub const FIONBIO: ::c_ulong = 0xbe000000; pub const FIONREAD: ::c_ulong = 0xbe000001; pub const FIOSEEKDATA: ::c_ulong = 0xbe000002; pub const FIOSEEKHOLE: ::c_ulong = 0xbe000003; pub const _SC_ARG_MAX: ::c_int = 15; pub const _SC_CHILD_MAX: ::c_int = 16; pub const _SC_CLK_TCK: ::c_int = 17; pub const _SC_JOB_CONTROL: ::c_int = 18; pub const _SC_NGROUPS_MAX: ::c_int = 19; pub const _SC_OPEN_MAX: ::c_int = 20; pub const _SC_SAVED_IDS: ::c_int = 21; pub const _SC_STREAM_MAX: ::c_int = 22; pub const _SC_TZNAME_MAX: ::c_int = 23; pub const _SC_VERSION: ::c_int = 24; pub const _SC_GETGR_R_SIZE_MAX: ::c_int = 25; pub const _SC_GETPW_R_SIZE_MAX: ::c_int = 26; pub const _SC_PAGESIZE: ::c_int = 27; pub const _SC_PAGE_SIZE: ::c_int = 27; pub const _SC_SEM_NSEMS_MAX: ::c_int = 28; pub const _SC_SEM_VALUE_MAX: ::c_int = 29; pub const _SC_SEMAPHORES: ::c_int = 30; pub const _SC_THREADS: ::c_int = 31; pub const _SC_IOV_MAX: ::c_int = 32; pub const _SC_UIO_MAXIOV: ::c_int = 32; pub const _SC_NPROCESSORS_CONF: ::c_int = 34; pub const _SC_NPROCESSORS_ONLN: ::c_int = 35; pub const _SC_ATEXIT_MAX: ::c_int = 37; pub const _SC_PASS_MAX: ::c_int = 39; pub const _SC_PHYS_PAGES: ::c_int = 40; pub const _SC_AVPHYS_PAGES: ::c_int = 41; pub const _SC_PIPE: ::c_int = 42; pub const _SC_SELECT: ::c_int = 43; pub const _SC_POLL: ::c_int = 44; pub const _SC_MAPPED_FILES: ::c_int = 45; pub const _SC_THREAD_PROCESS_SHARED: ::c_int = 46; pub const _SC_THREAD_STACK_MIN: ::c_int = 47; pub const _SC_THREAD_ATTR_STACKADDR: ::c_int = 48; pub const _SC_THREAD_ATTR_STACKSIZE: ::c_int = 49; pub const _SC_THREAD_PRIORITY_SCHEDULING: ::c_int = 50; pub const _SC_REALTIME_SIGNALS: ::c_int = 51; pub const _SC_MEMORY_PROTECTION: ::c_int = 52; pub const _SC_SIGQUEUE_MAX: ::c_int = 53; pub const _SC_RTSIG_MAX: ::c_int = 54; pub const _SC_MONOTONIC_CLOCK: ::c_int = 55; pub const _SC_DELAYTIMER_MAX: ::c_int = 56; pub const _SC_TIMER_MAX: ::c_int = 57; pub const _SC_TIMERS: ::c_int = 58; pub const _SC_CPUTIME: ::c_int = 59; pub const _SC_THREAD_CPUTIME: ::c_int = 60; pub const _SC_HOST_NAME_MAX: ::c_int = 61; pub const _SC_REGEXP: ::c_int = 62; pub const _SC_SYMLOOP_MAX: ::c_int = 63; pub const _SC_SHELL: ::c_int = 64; pub const PTHREAD_STACK_MIN: ::size_t = 8192; pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t { flags: 0, lock: 0, unused: -42, owner: -1, owner_count: 0, }; pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t { flags: 0, unused: -42, mutex: 0 as *mut _, waiter_count: 0, lock: 0, }; pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t { flags: 0, owner: -1, lock_sem: 0, lock_count: 0, reader_count: 0, writer_count: 0, waiters: [0 as *mut _; 2], }; pub const PTHREAD_MUTEX_DEFAULT: ::c_int = 0; pub const PTHREAD_MUTEX_NORMAL: ::c_int = 1; pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 2; pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 3; pub const FIOCLEX: c_ulong = 0; // FIXME: does not exist on Haiku! pub const RUSAGE_CHILDREN: ::c_int = -1; pub const SOCK_STREAM: ::c_int = 1; pub const SOCK_DGRAM: ::c_int = 2; pub const SOCK_RAW: ::c_int = 3; pub const SOCK_SEQPACKET: ::c_int = 5; pub const SOL_SOCKET: ::c_int = -1; pub const SO_ACCEPTCONN: ::c_int = 0x00000001; pub const SO_BROADCAST: ::c_int = 0x00000002; pub const SO_DEBUG: ::c_int = 0x00000004; pub const SO_DONTROUTE: ::c_int = 0x00000008; pub const SO_KEEPALIVE: ::c_int = 0x00000010; pub const SO_OOBINLINE: ::c_int = 0x00000020; pub const SO_REUSEADDR: ::c_int = 0x00000040; pub const SO_REUSEPORT: ::c_int = 0x00000080; pub const SO_USELOOPBACK: ::c_int = 0x00000100; pub const SO_LINGER: ::c_int = 0x00000200; pub const SO_SNDBUF: ::c_int = 0x40000001; pub const SO_SNDLOWAT: ::c_int = 0x40000002; pub const SO_SNDTIMEO: ::c_int = 0x40000003; pub const SO_RCVBUF: ::c_int = 0x40000004; pub const SO_RCVLOWAT: ::c_int = 0x40000005; pub const SO_RCVTIMEO: ::c_int = 0x40000006; pub const SO_ERROR: ::c_int = 0x40000007; pub const SO_TYPE: ::c_int = 0x40000008; pub const SO_NONBLOCK: ::c_int = 0x40000009; pub const SO_BINDTODEVICE: ::c_int = 0x4000000a; pub const SO_PEERCRED: ::c_int = 0x4000000b; pub const SCM_RIGHTS: ::c_int = 0x01; pub const NI_MAXHOST: ::size_t = 1025; pub const WNOHANG: ::c_int = 0x01; pub const WUNTRACED: ::c_int = 0x02; pub const WCONTINUED: ::c_int = 0x04; pub const WEXITED: ::c_int = 0x08; pub const WSTOPPED: ::c_int = 0x10; pub const WNOWAIT: ::c_int = 0x20; pub const CLD_EXITED: ::c_int = 60; pub const CLD_KILLED: ::c_int = 61; pub const CLD_DUMPED: ::c_int = 62; pub const CLD_TRAPPED: ::c_int = 63; pub const CLD_STOPPED: ::c_int = 64; pub const CLD_CONTINUED: ::c_int = 65; pub const P_ALL: idtype_t = 0; pub const P_PID: idtype_t = 1; pub const P_PGID: idtype_t = 2; pub const UTIME_OMIT: c_long = 1000000001; pub const UTIME_NOW: c_long = 1000000000; pub const VINTR: usize = 0; pub const VQUIT: usize = 1; pub const VERASE: usize = 2; pub const VKILL: usize = 3; pub const VEOF: usize = 4; pub const VEOL: usize = 5; pub const VMIN: usize = 4; pub const VTIME: usize = 5; pub const VEOL2: usize = 6; pub const VSWTCH: usize = 7; pub const VSTART: usize = 8; pub const VSTOP: usize = 9; pub const VSUSP: usize = 10; pub const IGNBRK: ::tcflag_t = 0x01; pub const BRKINT: ::tcflag_t = 0x02; pub const IGNPAR: ::tcflag_t = 0x04; pub const PARMRK: ::tcflag_t = 0x08; pub const INPCK: ::tcflag_t = 0x10; pub const ISTRIP: ::tcflag_t = 0x20; pub const INLCR: ::tcflag_t = 0x40; pub const IGNCR: ::tcflag_t = 0x80; pub const ICRNL: ::tcflag_t = 0x100; pub const IUCLC: ::tcflag_t = 0x200; pub const IXON: ::tcflag_t = 0x400; pub const IXANY: ::tcflag_t = 0x800; pub const IXOFF: ::tcflag_t = 0x1000; pub const OPOST: ::tcflag_t = 0x00000001; pub const OLCUC: ::tcflag_t = 0x00000002; pub const ONLCR: ::tcflag_t = 0x00000004; pub const OCRNL: ::tcflag_t = 0x00000008; pub const ONOCR: ::tcflag_t = 0x00000010; pub const ONLRET: ::tcflag_t = 0x00000020; pub const OFILL: ::tcflag_t = 0x00000040; pub const OFDEL: ::tcflag_t = 0x00000080; pub const NLDLY: ::tcflag_t = 0x00000100; pub const NL0: ::tcflag_t = 0x00000000; pub const NL1: ::tcflag_t = 0x00000100; pub const CRDLY: ::tcflag_t = 0x00000600; pub const CR0: ::tcflag_t = 0x00000000; pub const CR1: ::tcflag_t = 0x00000200; pub const CR2: ::tcflag_t = 0x00000400; pub const CR3: ::tcflag_t = 0x00000600; pub const TABDLY: ::tcflag_t = 0x00001800; pub const TAB0: ::tcflag_t = 0x00000000; pub const TAB1: ::tcflag_t = 0x00000800; pub const TAB2: ::tcflag_t = 0x00001000; pub const TAB3: ::tcflag_t = 0x00001800; pub const BSDLY: ::tcflag_t = 0x00002000; pub const BS0: ::tcflag_t = 0x00000000; pub const BS1: ::tcflag_t = 0x00002000; pub const VTDLY: ::tcflag_t = 0x00004000; pub const VT0: ::tcflag_t = 0x00000000; pub const VT1: ::tcflag_t = 0x00004000; pub const FFDLY: ::tcflag_t = 0x00008000; pub const FF0: ::tcflag_t = 0x00000000; pub const FF1: ::tcflag_t = 0x00008000; pub const CSIZE: ::tcflag_t = 0x00000020; pub const CS5: ::tcflag_t = 0x00000000; pub const CS6: ::tcflag_t = 0x00000000; pub const CS7: ::tcflag_t = 0x00000000; pub const CS8: ::tcflag_t = 0x00000020; pub const CSTOPB: ::tcflag_t = 0x00000040; pub const CREAD: ::tcflag_t = 0x00000080; pub const PARENB: ::tcflag_t = 0x00000100; pub const PARODD: ::tcflag_t = 0x00000200; pub const HUPCL: ::tcflag_t = 0x00000400; pub const CLOCAL: ::tcflag_t = 0x00000800; pub const XLOBLK: ::tcflag_t = 0x00001000; pub const CTSFLOW: ::tcflag_t = 0x00002000; pub const RTSFLOW: ::tcflag_t = 0x00004000; pub const CRTSCTS: ::tcflag_t = RTSFLOW | CTSFLOW; pub const ISIG: ::tcflag_t = 0x00000001; pub const ICANON: ::tcflag_t = 0x00000002; pub const XCASE: ::tcflag_t = 0x00000004; pub const ECHO: ::tcflag_t = 0x00000008; pub const ECHOE: ::tcflag_t = 0x00000010; pub const ECHOK: ::tcflag_t = 0x00000020; pub const ECHONL: ::tcflag_t = 0x00000040; pub const NOFLSH: ::tcflag_t = 0x00000080; pub const TOSTOP: ::tcflag_t = 0x00000100; pub const IEXTEN: ::tcflag_t = 0x00000200; pub const ECHOCTL: ::tcflag_t = 0x00000400; pub const ECHOPRT: ::tcflag_t = 0x00000800; pub const ECHOKE: ::tcflag_t = 0x00001000; pub const FLUSHO: ::tcflag_t = 0x00002000; pub const PENDIN: ::tcflag_t = 0x00004000; pub const TCGB_CTS: ::c_int = 0x01; pub const TCGB_DSR: ::c_int = 0x02; pub const TCGB_RI: ::c_int = 0x04; pub const TCGB_DCD: ::c_int = 0x08; pub const TIOCM_CTS: ::c_int = TCGB_CTS; pub const TIOCM_CD: ::c_int = TCGB_DCD; pub const TIOCM_CAR: ::c_int = TIOCM_CD; pub const TIOCM_RI: ::c_int = TCGB_RI; pub const TIOCM_DSR: ::c_int = TCGB_DSR; pub const TIOCM_DTR: ::c_int = 0x10; pub const TIOCM_RTS: ::c_int = 0x20; pub const B0: speed_t = 0x00; pub const B50: speed_t = 0x01; pub const B75: speed_t = 0x02; pub const B110: speed_t = 0x03; pub const B134: speed_t = 0x04; pub const B150: speed_t = 0x05; pub const B200: speed_t = 0x06; pub const B300: speed_t = 0x07; pub const B600: speed_t = 0x08; pub const B1200: speed_t = 0x09; pub const B1800: speed_t = 0x0A; pub const B2400: speed_t = 0x0B; pub const B4800: speed_t = 0x0C; pub const B9600: speed_t = 0x0D; pub const B19200: speed_t = 0x0E; pub const B38400: speed_t = 0x0F; pub const B57600: speed_t = 0x10; pub const B115200: speed_t = 0x11; pub const B230400: speed_t = 0x12; pub const B31250: speed_t = 0x13; pub const TCSANOW: ::c_int = 0x01; pub const TCSADRAIN: ::c_int = 0x02; pub const TCSAFLUSH: ::c_int = 0x04; pub const TCOOFF: ::c_int = 0x01; pub const TCOON: ::c_int = 0x02; pub const TCIOFF: ::c_int = 0x04; pub const TCION: ::c_int = 0x08; pub const TCIFLUSH: ::c_int = 0x01; pub const TCOFLUSH: ::c_int = 0x02; pub const TCIOFLUSH: ::c_int = 0x03; pub const TCGETA: ::c_ulong = 0x8000; pub const TCSETA: ::c_ulong = TCGETA + 1; pub const TCSETAF: ::c_ulong = TCGETA + 2; pub const TCSETAW: ::c_ulong = TCGETA + 3; pub const TCWAITEVENT: ::c_ulong = TCGETA + 4; pub const TCSBRK: ::c_ulong = TCGETA + 5; pub const TCFLSH: ::c_ulong = TCGETA + 6; pub const TCXONC: ::c_ulong = TCGETA + 7; pub const TCQUERYCONNECTED: ::c_ulong = TCGETA + 8; pub const TCGETBITS: ::c_ulong = TCGETA + 9; pub const TCSETDTR: ::c_ulong = TCGETA + 10; pub const TCSETRTS: ::c_ulong = TCGETA + 11; pub const TIOCGWINSZ: ::c_ulong = TCGETA + 12; pub const TIOCSWINSZ: ::c_ulong = TCGETA + 13; pub const TCVTIME: ::c_ulong = TCGETA + 14; pub const TIOCGPGRP: ::c_ulong = TCGETA + 15; pub const TIOCSPGRP: ::c_ulong = TCGETA + 16; pub const TIOCSCTTY: ::c_ulong = TCGETA + 17; pub const TIOCMGET: ::c_ulong = TCGETA + 18; pub const TIOCMSET: ::c_ulong = TCGETA + 19; pub const TIOCSBRK: ::c_ulong = TCGETA + 20; pub const TIOCCBRK: ::c_ulong = TCGETA + 21; pub const TIOCMBIS: ::c_ulong = TCGETA + 22; pub const TIOCMBIC: ::c_ulong = TCGETA + 23; pub const PRIO_PROCESS: ::c_int = 0; pub const PRIO_PGRP: ::c_int = 1; pub const PRIO_USER: ::c_int = 2; pub const LOG_PID: ::c_int = 1 << 12; pub const LOG_CONS: ::c_int = 2 << 12; pub const LOG_ODELAY: ::c_int = 4 << 12; pub const LOG_NDELAY: ::c_int = 8 << 12; pub const LOG_SERIAL: ::c_int = 16 << 12; pub const LOG_PERROR: ::c_int = 32 << 12; pub const LOG_NOWAIT: ::c_int = 64 << 12; const_fn! { {const} fn CMSG_ALIGN(len: usize) -> usize { len + ::mem::size_of::<usize>() - 1 & !(::mem::size_of::<usize>() - 1) } } f! { pub fn CMSG_FIRSTHDR(mhdr: *const msghdr) -> *mut cmsghdr { if (*mhdr).msg_controllen as usize >= ::mem::size_of::<cmsghdr>() { (*mhdr).msg_control as *mut cmsghdr } else { 0 as *mut cmsghdr } } pub fn CMSG_DATA(cmsg: *const ::cmsghdr) -> *mut ::c_uchar { (cmsg as *mut ::c_uchar) .offset(CMSG_ALIGN(::mem::size_of::<::cmsghdr>()) as isize) } pub {const} fn CMSG_SPACE(length: ::c_uint) -> ::c_uint { (CMSG_ALIGN(length as usize) + CMSG_ALIGN(::mem::size_of::<cmsghdr>())) as ::c_uint } pub fn CMSG_LEN(length: ::c_uint) -> ::c_uint { CMSG_ALIGN(::mem::size_of::<cmsghdr>()) as ::c_uint + length } pub fn CMSG_NXTHDR(mhdr: *const msghdr, cmsg: *const cmsghdr) -> *mut cmsghdr { if cmsg.is_null() { return ::CMSG_FIRSTHDR(mhdr); }; let next = cmsg as usize + CMSG_ALIGN((*cmsg).cmsg_len as usize) + CMSG_ALIGN(::mem::size_of::<::cmsghdr>()); let max = (*mhdr).msg_control as usize + (*mhdr).msg_controllen as usize; if next > max { 0 as *mut ::cmsghdr } else { (cmsg as usize + CMSG_ALIGN((*cmsg).cmsg_len as usize)) as *mut ::cmsghdr } } pub fn FD_CLR(fd: ::c_int, set: *mut fd_set) -> () { let fd = fd as usize; let size = ::mem::size_of_val(&(*set).fds_bits[0]) * 8; (*set).fds_bits[fd / size] &= !(1 << (fd % size)); return } pub fn FD_ISSET(fd: ::c_int, set: *const fd_set) -> bool { let fd = fd as usize; let size = ::mem::size_of_val(&(*set).fds_bits[0]) * 8; return ((*set).fds_bits[fd / size] & (1 << (fd % size))) != 0 } pub fn FD_SET(fd: ::c_int, set: *mut fd_set) -> () { let fd = fd as usize; let size = ::mem::size_of_val(&(*set).fds_bits[0]) * 8; (*set).fds_bits[fd / size] |= 1 << (fd % size); return } pub fn FD_ZERO(set: *mut fd_set) -> () { for slot in (*set).fds_bits.iter_mut() { *slot = 0; } } } safe_f! { pub {const} fn WIFEXITED(status: ::c_int) -> bool { (status & !0xff) == 0 } pub {const} fn WEXITSTATUS(status: ::c_int) -> ::c_int { status & 0xff } pub {const} fn WIFSIGNALED(status: ::c_int) -> bool { ((status >> 8) & 0xff) != 0 } pub {const} fn WTERMSIG(status: ::c_int) -> ::c_int { (status >> 8) & 0xff } pub {const} fn WIFSTOPPED(status: ::c_int) -> bool { ((status >> 16) & 0xff) != 0 } pub {const} fn WSTOPSIG(status: ::c_int) -> ::c_int { (status >> 16) & 0xff } // actually WIFCORED, but this is used everywhere else pub {const} fn WCOREDUMP(status: ::c_int) -> bool { (status & 0x10000) != 0 } pub {const} fn WIFCONTINUED(status: ::c_int) -> bool { (status & 0x20000) != 0 } } extern "C" { pub fn getrlimit(resource: ::c_int, rlim: *mut ::rlimit) -> ::c_int; pub fn setrlimit(resource: ::c_int, rlim: *const ::rlimit) -> ::c_int; pub fn getpriority(which: ::c_int, who: id_t) -> ::c_int; pub fn setpriority(which: ::c_int, who: id_t, priority: ::c_int) -> ::c_int; pub fn utimensat( fd: ::c_int, path: *const ::c_char, times: *const ::timespec, flag: ::c_int, ) -> ::c_int; pub fn futimens(fd: ::c_int, times: *const ::timespec) -> ::c_int; pub fn strerror_r(errnum: ::c_int, buf: *mut c_char, buflen: ::size_t) -> ::c_int; pub fn _errnop() -> *mut ::c_int; pub fn abs(i: ::c_int) -> ::c_int; pub fn atof(s: *const ::c_char) -> ::c_double; pub fn labs(i: ::c_long) -> ::c_long; pub fn rand() -> ::c_int; pub fn srand(seed: ::c_uint); } #[link(name = "bsd")] extern "C" { pub fn sem_destroy(sem: *mut sem_t) -> ::c_int; pub fn sem_init(sem: *mut sem_t, pshared: ::c_int, value: ::c_uint) -> ::c_int; pub fn clock_gettime(clk_id: ::c_int, tp: *mut ::timespec) -> ::c_int; pub fn clock_settime(clk_id: ::c_int, tp: *const ::timespec) -> ::c_int; pub fn pthread_create( thread: *mut ::pthread_t, attr: *const ::pthread_attr_t, f: extern "C" fn(*mut ::c_void) -> *mut ::c_void, value: *mut ::c_void, ) -> ::c_int; pub fn pthread_attr_getguardsize( attr: *const ::pthread_attr_t, guardsize: *mut ::size_t, ) -> ::c_int; pub fn pthread_attr_getstack( attr: *const ::pthread_attr_t, stackaddr: *mut *mut ::c_void, stacksize: *mut ::size_t, ) -> ::c_int; pub fn pthread_condattr_getclock( attr: *const pthread_condattr_t, clock_id: *mut clockid_t, ) -> ::c_int; pub fn pthread_condattr_setclock( attr: *mut pthread_condattr_t, clock_id: ::clockid_t, ) -> ::c_int; pub fn memalign(align: ::size_t, size: ::size_t) -> *mut ::c_void; pub fn setgroups(ngroups: ::c_int, ptr: *const ::gid_t) -> ::c_int; pub fn ioctl(fd: ::c_int, request: ::c_ulong, ...) -> ::c_int; pub fn mprotect(addr: *mut ::c_void, len: ::size_t, prot: ::c_int) -> ::c_int; pub fn dirfd(dirp: *mut ::DIR) -> ::c_int; pub fn getnameinfo( sa: *const ::sockaddr, salen: ::socklen_t, host: *mut ::c_char, hostlen: ::socklen_t, serv: *mut ::c_char, sevlen: ::socklen_t, flags: ::c_int, ) -> ::c_int; pub fn pthread_mutex_timedlock( lock: *mut pthread_mutex_t, abstime: *const ::timespec, ) -> ::c_int; pub fn waitid(idtype: idtype_t, id: id_t, infop: *mut ::siginfo_t, options: ::c_int) -> ::c_int; pub fn glob( pattern: *const ::c_char, flags: ::c_int, errfunc: ::Option<extern "C" fn(epath: *const ::c_char, errno: ::c_int) -> ::c_int>, pglob: *mut ::glob_t, ) -> ::c_int; pub fn globfree(pglob: *mut ::glob_t); pub fn gettimeofday(tp: *mut ::timeval, tz: *mut ::c_void) -> ::c_int; pub fn posix_madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) -> ::c_int; pub fn shm_open(name: *const ::c_char, oflag: ::c_int, mode: ::mode_t) -> ::c_int; pub fn shm_unlink(name: *const ::c_char) -> ::c_int; pub fn seekdir(dirp: *mut ::DIR, loc: ::c_long); pub fn telldir(dirp: *mut ::DIR) -> ::c_long; pub fn madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) -> ::c_int; pub fn msync(addr: *mut ::c_void, len: ::size_t, flags: ::c_int) -> ::c_int; pub fn recvfrom( socket: ::c_int, buf: *mut ::c_void, len: ::size_t, flags: ::c_int, addr: *mut ::sockaddr, addrlen: *mut ::socklen_t, ) -> ::ssize_t; pub fn mkstemps(template: *mut ::c_char, suffixlen: ::c_int) -> ::c_int; pub fn lutimes(file: *const ::c_char, times: *const ::timeval) -> ::c_int; pub fn nl_langinfo(item: ::nl_item) -> *mut ::c_char; pub fn bind(socket: ::c_int, address: *const ::sockaddr, address_len: ::socklen_t) -> ::c_int; pub fn writev(fd: ::c_int, iov: *const ::iovec, count: ::c_int) -> ::ssize_t; pub fn readv(fd: ::c_int, iov: *const ::iovec, count: ::c_int) -> ::ssize_t; pub fn sendmsg(fd: ::c_int, msg: *const ::msghdr, flags: ::c_int) -> ::ssize_t; pub fn recvmsg(fd: ::c_int, msg: *mut ::msghdr, flags: ::c_int) -> ::ssize_t; pub fn execvpe( file: *const ::c_char, argv: *const *const ::c_char, environment: *const *const ::c_char, ) -> ::c_int; pub fn getgrgid_r( gid: ::gid_t, grp: *mut ::group, buf: *mut ::c_char, buflen: ::size_t, result: *mut *mut ::group, ) -> ::c_int; pub fn sigaltstack(ss: *const stack_t, oss: *mut stack_t) -> ::c_int; pub fn sem_close(sem: *mut sem_t) -> ::c_int; pub fn getdtablesize() -> ::c_int; pub fn getgrnam_r( name: *const ::c_char, grp: *mut ::group, buf: *mut ::c_char, buflen: ::size_t, result: *mut *mut ::group, ) -> ::c_int; pub fn pthread_sigmask(how: ::c_int, set: *const sigset_t, oldset: *mut sigset_t) -> ::c_int; pub fn sem_open(name: *const ::c_char, oflag: ::c_int, ...) -> *mut sem_t; pub fn getgrnam(name: *const ::c_char) -> *mut ::group; pub fn pthread_kill(thread: ::pthread_t, sig: ::c_int) -> ::c_int; pub fn sem_unlink(name: *const ::c_char) -> ::c_int; pub fn daemon(nochdir: ::c_int, noclose: ::c_int) -> ::c_int; pub fn getpwnam_r( name: *const ::c_char, pwd: *mut passwd, buf: *mut ::c_char, buflen: ::size_t, result: *mut *mut passwd, ) -> ::c_int; pub fn getpwuid_r( uid: ::uid_t, pwd: *mut passwd, buf: *mut ::c_char, buflen: ::size_t, result: *mut *mut passwd, ) -> ::c_int; pub fn sigwait(set: *const sigset_t, sig: *mut ::c_int) -> ::c_int; pub fn pthread_atfork( prepare: ::Option<unsafe extern "C" fn()>, parent: ::Option<unsafe extern "C" fn()>, child: ::Option<unsafe extern "C" fn()>, ) -> ::c_int; pub fn getgrgid(gid: ::gid_t) -> *mut ::group; pub fn popen(command: *const c_char, mode: *const c_char) -> *mut ::FILE; pub fn openpty( amaster: *mut ::c_int, aslave: *mut ::c_int, name: *mut ::c_char, termp: *mut termios, winp: *mut ::winsize, ) -> ::c_int; pub fn forkpty( amaster: *mut ::c_int, name: *mut ::c_char, termp: *mut termios, winp: *mut ::winsize, ) -> ::pid_t; pub fn sethostname(name: *const ::c_char, len: ::size_t) -> ::c_int; pub fn uname(buf: *mut ::utsname) -> ::c_int; } cfg_if! { if #[cfg(target_pointer_width = "64")] { mod b64; pub use self::b64::*; } else { mod b32; pub use self::b32::*; } } mod native; pub use self::native::*;
33.145712
98
0.621623
3887d5633acf5ba5fc6a1a4f12439f819f65f873
9,886
#[doc = "Reader of register MB52_8B_CS"] pub type R = crate::R<u32, super::MB52_8B_CS>; #[doc = "Writer for register MB52_8B_CS"] pub type W = crate::W<u32, super::MB52_8B_CS>; #[doc = "Register MB52_8B_CS `reset()`'s with value 0"] impl crate::ResetValue for super::MB52_8B_CS { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `TIME_STAMP`"] pub type TIME_STAMP_R = crate::R<u16, u16>; #[doc = "Write proxy for field `TIME_STAMP`"] pub struct TIME_STAMP_W<'a> { w: &'a mut W, } impl<'a> TIME_STAMP_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !0xffff) | ((value as u32) & 0xffff); self.w } } #[doc = "Reader of field `DLC`"] pub type DLC_R = crate::R<u8, u8>; #[doc = "Write proxy for field `DLC`"] pub struct DLC_W<'a> { w: &'a mut W, } impl<'a> DLC_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 & !(0x0f << 16)) | (((value as u32) & 0x0f) << 16); self.w } } #[doc = "Reader of field `RTR`"] pub type RTR_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RTR`"] pub struct RTR_W<'a> { w: &'a mut W, } impl<'a> RTR_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20); self.w } } #[doc = "Reader of field `IDE`"] pub type IDE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `IDE`"] pub struct IDE_W<'a> { w: &'a mut W, } impl<'a> IDE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21); self.w } } #[doc = "Reader of field `SRR`"] pub type SRR_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SRR`"] pub struct SRR_W<'a> { w: &'a mut W, } impl<'a> SRR_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22); self.w } } #[doc = "Reader of field `CODE`"] pub type CODE_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CODE`"] pub struct CODE_W<'a> { w: &'a mut W, } impl<'a> CODE_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 & !(0x0f << 24)) | (((value as u32) & 0x0f) << 24); self.w } } #[doc = "Reader of field `ESI`"] pub type ESI_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ESI`"] pub struct ESI_W<'a> { w: &'a mut W, } impl<'a> ESI_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 29)) | (((value as u32) & 0x01) << 29); self.w } } #[doc = "Reader of field `BRS`"] pub type BRS_R = crate::R<bool, bool>; #[doc = "Write proxy for field `BRS`"] pub struct BRS_W<'a> { w: &'a mut W, } impl<'a> BRS_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 30)) | (((value as u32) & 0x01) << 30); self.w } } #[doc = "Reader of field `EDL`"] pub type EDL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `EDL`"] pub struct EDL_W<'a> { w: &'a mut W, } impl<'a> EDL_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31); self.w } } impl R { #[doc = "Bits 0:15 - Free-Running Counter Time stamp. This 16-bit field is a copy of the Free-Running Timer, captured for Tx and Rx frames at the time when the beginning of the Identifier field appears on the CAN bus."] #[inline(always)] pub fn time_stamp(&self) -> TIME_STAMP_R { TIME_STAMP_R::new((self.bits & 0xffff) as u16) } #[doc = "Bits 16:19 - Length of the data to be stored/transmitted."] #[inline(always)] pub fn dlc(&self) -> DLC_R { DLC_R::new(((self.bits >> 16) & 0x0f) as u8) } #[doc = "Bit 20 - Remote Transmission Request. One/zero for remote/data frame."] #[inline(always)] pub fn rtr(&self) -> RTR_R { RTR_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 21 - ID Extended. One/zero for extended/standard format frame."] #[inline(always)] pub fn ide(&self) -> IDE_R { IDE_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 22 - Substitute Remote Request. Contains a fixed recessive bit."] #[inline(always)] pub fn srr(&self) -> SRR_R { SRR_R::new(((self.bits >> 22) & 0x01) != 0) } #[doc = "Bits 24:27 - Message Buffer Code. This 4-bit field can be accessed (read or write) by the CPU and by the FlexCAN module itself, as part of the message buffer matching and arbitration process."] #[inline(always)] pub fn code(&self) -> CODE_R { CODE_R::new(((self.bits >> 24) & 0x0f) as u8) } #[doc = "Bit 29 - Error State Indicator. This bit indicates if the transmitting node is error active or error passive."] #[inline(always)] pub fn esi(&self) -> ESI_R { ESI_R::new(((self.bits >> 29) & 0x01) != 0) } #[doc = "Bit 30 - Bit Rate Switch. This bit defines whether the bit rate is switched inside a CAN FD format frame."] #[inline(always)] pub fn brs(&self) -> BRS_R { BRS_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 31 - Extended Data Length. This bit distinguishes between CAN format and CAN FD format frames. The EDL bit must not be set for Message Buffers configured to RANSWER with code field 0b1010."] #[inline(always)] pub fn edl(&self) -> EDL_R { EDL_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bits 0:15 - Free-Running Counter Time stamp. This 16-bit field is a copy of the Free-Running Timer, captured for Tx and Rx frames at the time when the beginning of the Identifier field appears on the CAN bus."] #[inline(always)] pub fn time_stamp(&mut self) -> TIME_STAMP_W { TIME_STAMP_W { w: self } } #[doc = "Bits 16:19 - Length of the data to be stored/transmitted."] #[inline(always)] pub fn dlc(&mut self) -> DLC_W { DLC_W { w: self } } #[doc = "Bit 20 - Remote Transmission Request. One/zero for remote/data frame."] #[inline(always)] pub fn rtr(&mut self) -> RTR_W { RTR_W { w: self } } #[doc = "Bit 21 - ID Extended. One/zero for extended/standard format frame."] #[inline(always)] pub fn ide(&mut self) -> IDE_W { IDE_W { w: self } } #[doc = "Bit 22 - Substitute Remote Request. Contains a fixed recessive bit."] #[inline(always)] pub fn srr(&mut self) -> SRR_W { SRR_W { w: self } } #[doc = "Bits 24:27 - Message Buffer Code. This 4-bit field can be accessed (read or write) by the CPU and by the FlexCAN module itself, as part of the message buffer matching and arbitration process."] #[inline(always)] pub fn code(&mut self) -> CODE_W { CODE_W { w: self } } #[doc = "Bit 29 - Error State Indicator. This bit indicates if the transmitting node is error active or error passive."] #[inline(always)] pub fn esi(&mut self) -> ESI_W { ESI_W { w: self } } #[doc = "Bit 30 - Bit Rate Switch. This bit defines whether the bit rate is switched inside a CAN FD format frame."] #[inline(always)] pub fn brs(&mut self) -> BRS_W { BRS_W { w: self } } #[doc = "Bit 31 - Extended Data Length. This bit distinguishes between CAN format and CAN FD format frames. The EDL bit must not be set for Message Buffers configured to RANSWER with code field 0b1010."] #[inline(always)] pub fn edl(&mut self) -> EDL_W { EDL_W { w: self } } }
33.740614
223
0.569189
5085e31cad9988424f8643300f2dfc58ef77ba63
3,419
use crate::{ parse::{DataRegion, Function}, Remapper, }; use parity_wasm::elements::Instruction; pub struct MatchingContext<'a, 'wasm> { data_regions: &'a [DataRegion], options: &'a Remapper<'wasm>, } impl<'a, 'wasm> MatchingContext<'a, 'wasm> { pub fn new(data_regions: &'a [DataRegion], options: &'a Remapper<'wasm>) -> Self { Self { data_regions, options, } } pub fn find_matches<'func>( &self, input: &Function, others: &'func [Function], threshold: f32, ) -> Vec<(&'func Function, f32)> { others .into_iter() .map(|other| (other, self.get_match_weight_for(input, other))) .filter(|(_, weight)| *weight >= threshold) .collect() } fn get_match_weight_for(&self, input: &Function, other: &Function) -> f32 { let input_instructions = &input.instructions; let other_instructions = &other.instructions; let max_instructions = input_instructions.len().max(other_instructions.len()); if !self.does_signiture_match(input, other) { return 0.0; } else if self.options.require_exact_function_locals && input.local_types != other.local_types { return 0.0; } let matching_instruction_count = input_instructions .into_iter() .zip(other_instructions.into_iter()) .filter(|(left, right)| self.do_instructions_match(left, right)) .count(); let matching_percentage = matching_instruction_count as f32 / max_instructions as f32; matching_percentage } fn do_instructions_match(&self, left: &Instruction, right: &Instruction) -> bool { let ingore_constant_data_section_pointers = self.options.ingore_constant_data_section_pointers; // TODO: Find a way to do this in a cleaner more modular way. match (left, right) { (Instruction::I32Store(_, left_offset), Instruction::I32Store(_, right_offset)) if ingore_constant_data_section_pointers => { self.both_locations_in_data_regions(*left_offset, *right_offset) } (Instruction::I32Const(left_const), Instruction::I32Const(right_const)) if ingore_constant_data_section_pointers => { let in_data_region = self.both_locations_in_data_regions(*left_const as u32, *right_const as u32); in_data_region || left_const == right_const } (Instruction::CallIndirect(_, _), Instruction::CallIndirect(_, _)) => true, (Instruction::Call(_), Instruction::Call(_)) => true, (_, _) => left == right, } } fn does_signiture_match(&self, input: &Function, other: &Function) -> bool { let input = input; input.param_types == other.param_types && input.return_type == other.return_type } fn both_locations_in_data_regions(&self, left: u32, right: u32) -> bool { let left_inside = self .data_regions .iter() .any(|region| region.is_offset_inside(left)); let right_inside = self .data_regions .iter() .any(|region| region.is_offset_inside(right)); left_inside && right_inside } }
34.887755
97
0.592571
91e7a1b433320f87522c612c5bc225867a07192d
19,285
use crate::{ asset_loading, assets::GameAssets, bot, burro::Burro, burro::BurroDeathEvent, cleanup, collision, follow_text, game_camera, game_state, inspect, player, AppState, }; use bevy::gltf::Gltf; use bevy::prelude::*; use std::collections::HashMap; pub struct DebugRoomPlugin; impl Plugin for DebugRoomPlugin { fn build(&self, app: &mut App) { app.add_system_set( SystemSet::on_enter(AppState::Debug) .with_system(game_camera::spawn_camera) .with_system(setup), ) .insert_resource(RoundEndTimer { round_ending: false, cooldown: 0.0, }) .add_event::<PlayersDiedEarlyEvent>() .add_system_set( SystemSet::on_update(AppState::InGame) .with_system(check_for_next_level) .with_system(check_for_all_players_dead) .with_system(handle_players_died_early), ) .add_system_set( SystemSet::on_enter(AppState::ScoreDisplay) .with_system(despawn_round_end_text) .with_system(stop_firing), ) .add_system_set( SystemSet::on_exit(AppState::InGame) .with_system(cleanup::<CleanupMarker>) .with_system(game_camera::despawn_camera), ); } } fn check_for_next_level( mut game_state: ResMut<game_state::GameState>, mut assets_handler: asset_loading::AssetsHandler, mut game_assets: ResMut<GameAssets>, ) { if game_state.current_level_over { game_state.current_level += 1; assets_handler.load_next_level(&game_state, &mut game_assets); } } fn stop_firing(mut players: Query<&mut player::Player>) { for mut player in players.iter_mut() { player.is_firing = false; } } struct PlayersDiedEarlyEvent; #[derive(Component)] struct RoundEndText; struct RoundEndTimer { round_ending: bool, cooldown: f32, } fn despawn_round_end_text(mut commands: Commands, texts: Query<Entity, With<RoundEndText>>) { for entity in texts.iter() { commands.entity(entity).despawn_recursive(); } } fn handle_players_died_early( mut players_died_early_event_reader: EventReader<PlayersDiedEarlyEvent>, mut text: Query<&mut Visibility, With<RoundEndText>>, mut round_end_timer: ResMut<RoundEndTimer>, mut burro_death_event_writer: EventWriter<BurroDeathEvent>, remaining_burros: Query<(Entity, &Burro)>, time: Res<Time>, ) { if round_end_timer.round_ending { round_end_timer.cooldown -= time.delta_seconds(); round_end_timer.cooldown = round_end_timer.cooldown.clamp(-10.0, 5.0); if round_end_timer.cooldown <= 0.0 { for (entity, remaining_burro) in remaining_burros.iter() { burro_death_event_writer.send(BurroDeathEvent { entity, skin: remaining_burro.burro_skin, }); } } } else { for _ in players_died_early_event_reader.iter() { for mut visibility in text.iter_mut() { visibility.is_visible = true; } round_end_timer.cooldown = 5.0; round_end_timer.round_ending = true; } } } fn check_for_all_players_dead( game_state: Res<game_state::GameState>, mut players_died_early_event_writer: EventWriter<PlayersDiedEarlyEvent>, ) { let are_any_players_alive = game_state .burros .iter() .filter(|b| !b.is_bot && !game_state.dead_burros.contains(&b.skin)) .count() > 0; if !are_any_players_alive { players_died_early_event_writer.send(PlayersDiedEarlyEvent); } } #[derive(Component)] struct CleanupMarker; pub fn load( assets_handler: &mut asset_loading::AssetsHandler, game_assets: &mut ResMut<GameAssets>, game_state: &ResMut<game_state::GameState>, ) { match game_state.current_level { 1 => assets_handler.add_glb(&mut game_assets.level, "models/level_02.glb"), 2 => assets_handler.add_glb(&mut game_assets.level, "models/level_03.glb"), 3 => assets_handler.add_glb(&mut game_assets.level, "models/level_06.glb"), 4 => assets_handler.add_glb(&mut game_assets.level, "models/level_05.glb"), 5 => assets_handler.add_glb(&mut game_assets.level, "models/level_04.glb"), 6 => assets_handler.add_glb(&mut game_assets.level, "models/level_01.glb"), _ => assets_handler.add_glb(&mut game_assets.level, "models/level_00.glb"), } assets_handler.add_audio(&mut game_assets.bloop_sfx, "audio/bloop.wav"); assets_handler.add_audio(&mut game_assets.laser_sfx, "audio/laser.wav"); // assets_handler.add_audio(&mut game_assets.smoke_sfx, "audio/smoke.wav"); // assets_handler.add_audio(&mut game_assets.eliminated_sfx, "audio/eliminated.wav"); assets_handler.add_audio(&mut game_assets.candy_hit_sfx, "audio/candy_hit.wav"); assets_handler.add_audio(&mut game_assets.laser_hit_sfx, "audio/laser_hit.wav"); assets_handler.add_mesh( &mut game_assets.candy.mesh, "models/candy.gltf#Mesh0/Primitive0", ); assets_handler.add_mesh( &mut game_assets.laser.mesh, "models/laser.gltf#Mesh0/Primitive0", ); assets_handler.add_mesh( &mut game_assets.burro.mesh, "models/burro.gltf#Mesh0/Primitive0", ); assets_handler.add_material( &mut game_assets.pinata_texture, "textures/pinata.png", false, ); assets_handler.add_material(&mut game_assets.meow_texture, "textures/meow.png", false); assets_handler.add_material(&mut game_assets.salud_texture, "textures/salud.png", false); assets_handler.add_material( &mut game_assets.mexico_texture, "textures/mexico.png", false, ); assets_handler.add_material( &mut game_assets.medianoche_texture, "textures/medianoche.png", false, ); assets_handler.add_material(&mut game_assets.morir_texture, "textures/morir.png", false); assets_handler.add_material( &mut game_assets.gators_texture, "textures/gators.png", false, ); assets_handler.add_material(&mut game_assets.aguas_texture, "textures/aguas.png", false); assets_handler.add_material( &mut game_assets.mechaburro_texture, "textures/mechaburro.png", false, ); assets_handler.add_material( &mut game_assets.pinata_logo_texture, "textures/pinata_icon.png", true, ); assets_handler.add_material( &mut game_assets.meow_logo_texture, "textures/meow_icon.png", true, ); assets_handler.add_material( &mut game_assets.salud_logo_texture, "textures/salud_icon.png", true, ); assets_handler.add_material( &mut game_assets.mexico_logo_texture, "textures/mexico_icon.png", true, ); assets_handler.add_material( &mut game_assets.medianoche_logo_texture, "textures/medianoche_icon.png", true, ); assets_handler.add_material( &mut game_assets.morir_logo_texture, "textures/morir_icon.png", true, ); assets_handler.add_material( &mut game_assets.gators_logo_texture, "textures/gators_icon.png", true, ); assets_handler.add_material( &mut game_assets.aguas_logo_texture, "textures/aguas_icon.png", true, ); assets_handler.add_material( &mut game_assets.level_background, "textures/no_manches.png", true, ); assets_handler.add_material(&mut game_assets.heart_texture, "textures/heart.png", true); } fn setup( mut commands: Commands, mut scene_spawner: ResMut<SceneSpawner>, game_assets: Res<GameAssets>, assets_gltf: Res<Assets<Gltf>>, mut collidables: ResMut<collision::Collidables>, mut game_state: ResMut<game_state::GameState>, mut app_state: ResMut<State<AppState>>, mut clear_color: ResMut<ClearColor>, mut camera_settings: ResMut<game_camera::CameraSettings>, mut round_end_timer: ResMut<RoundEndTimer>, inspector_data: Res<inspect::InspectorData>, ) { camera_settings.set_camera(20.0, Vec3::ZERO, 0.4, false, 0.5, 30.0); game_state.current_level_over = false; game_state.on_new_level(); round_end_timer.cooldown = 0.0; round_end_timer.round_ending = false; // SETTING LEVEL BACKGROUND *clear_color = match game_state.current_level { 0 => ClearColor(Color::rgb(0.55, 0.92, 0.96)), //light blue 1 => ClearColor(Color::rgb(1.0, 0.65, 0.62)), // orange 2 => ClearColor(Color::rgb(0.72, 0.98, 0.75)), // green 3 => ClearColor(Color::rgb(0.81, 0.72, 0.94)), // purple 4 => ClearColor(Color::rgb(1.0, 0.65, 0.62)), // orange 5 => ClearColor(Color::rgb(0.72, 0.98, 0.75)), // green 6 => ClearColor(Color::rgb(0.81, 0.72, 0.94)), // purple _ => ClearColor(Color::rgb(1.0, 0.65, 0.62)), }; commands.insert_resource(AmbientLight { color: Color::WHITE, brightness: 0.50, }); if let Some(gltf) = assets_gltf.get(&game_assets.level) { let parent = commands .spawn_bundle(( Transform::from_xyz(0.0, 0.0, 0.0), GlobalTransform::identity(), )) .insert(CleanupMarker) .id(); scene_spawner.spawn_as_child(gltf.scenes[0].clone(), parent); } // commands.spawn_bundle(mesh::MeshBuilder::plane_repeating( // &mut meshes, // &mut images, // &game_assets.level_background, // 80.0, // Some(Vec3::new(0.0, -3.0, 0.0)), // Some(Quat::from_rotation_y(std::f32::consts::PI / 2.0)), // )) // .insert(CleanupMarker) // .insert_bundle(mesh::MeshBuilder::add_scrolling_bundle(-Vec3::X * 3.0)); use game_state::BurroSkin::*; let level_positions: HashMap<usize, HashMap<game_state::BurroSkin, (f32, f32)>> = HashMap::from([ // level 1 ( 0, HashMap::from([ (Pinata, (-14.0, -14.0)), (Meow, (-14.0, 14.0)), (Salud, (14.0, -14.0)), (Mexico, (14.0, 14.0)), (Medianoche, (-4.0, -4.0)), (Morir, (-4.0, 4.0)), (Gators, (4.0, -4.0)), (Aguas, (4.0, 4.0)), ]), ), // level 2 ( 1, HashMap::from([ (Pinata, (-14.0, -14.0)), (Meow, (-14.0, 14.0)), (Salud, (14.0, -14.0)), (Mexico, (14.0, 14.0)), (Medianoche, (-8.0, -8.0)), (Morir, (-8.0, 8.0)), (Gators, (8.0, -8.0)), (Aguas, (8.0, 8.0)), ]), ), // level 3 ( 2, HashMap::from([ (Pinata, (-14.0, -4.0)), (Meow, (-12.0, 4.0)), (Salud, (14.0, -4.0)), (Mexico, (12.0, 4.0)), (Medianoche, (-6.0, -8.0)), (Morir, (-6.0, 8.0)), (Gators, (6.0, -10.0)), (Aguas, (6.0, 10.0)), ]), ), // level 4 ( 3, HashMap::from([ (Pinata, (-14.0, -14.0)), (Meow, (-14.0, 14.0)), (Salud, (-5.0, -13.0)), (Mexico, (-5.0, 13.0)), (Medianoche, (-6.0, 0.0)), (Morir, (8.0, 0.0)), (Gators, (0.0, -8.0)), (Aguas, (0.0, 8.0)), ]), ), // level 5 ( 4, HashMap::from([ (Pinata, (-14.0, -14.0)), (Meow, (-6.0, 14.0)), (Salud, (6.0, -3.0)), (Mexico, (6.0, 3.0)), (Medianoche, (-6.0, 0.0)), (Morir, (6.0, 0.0)), (Gators, (0.0, -8.0)), (Aguas, (14.0, 12.0)), ]), ), // level 6 ( 5, HashMap::from([ (Pinata, (-14.0, -14.0)), (Meow, (-14.0, 14.0)), (Salud, (14.0, -14.0)), (Mexico, (14.0, 14.0)), (Medianoche, (-8.0, 0.0)), (Morir, (8.0, 0.0)), (Gators, (0.0, -8.0)), (Aguas, (0.0, 8.0)), ]), ), // level 7 ( 6, HashMap::from([ (Pinata, (-14.0, -14.0)), (Meow, (-14.0, 14.0)), (Salud, (14.0, -14.0)), (Mexico, (14.0, 14.0)), (Medianoche, (-4.0, -4.0)), (Morir, (-4.0, 4.0)), (Gators, (4.0, -4.0)), (Aguas, (4.0, 4.0)), ]), ), ]); game_state.burros.iter().for_each(|b| { let (skin, position) = match b.skin { Pinata => ( &game_assets.pinata_texture.material, level_positions[&game_state.current_level][&Pinata], ), Meow => ( &game_assets.meow_texture.material, level_positions[&game_state.current_level][&Meow], ), Salud => ( &game_assets.salud_texture.material, level_positions[&game_state.current_level][&Salud], ), Mexico => ( &game_assets.mexico_texture.material, level_positions[&game_state.current_level][&Mexico], ), Medianoche => ( &game_assets.medianoche_texture.material, level_positions[&game_state.current_level][&Medianoche], ), Morir => ( &game_assets.morir_texture.material, level_positions[&game_state.current_level][&Morir], ), Gators => ( &game_assets.gators_texture.material, level_positions[&game_state.current_level][&Gators], ), Aguas => ( &game_assets.aguas_texture.material, level_positions[&game_state.current_level][&Aguas], ), }; let burro_bundle = PbrBundle { mesh: game_assets.burro.mesh.clone(), material: skin.clone(), transform: { let mut transform = Transform::from_xyz(position.0, 1.0, position.1); transform.rotation = Quat::from_axis_angle(Vec3::Y, std::f32::consts::PI); transform }, ..Default::default() }; if b.is_bot { commands .spawn_bundle(burro_bundle) .insert(CleanupMarker) .insert_bundle(bot::BotBundle::new(b.skin, inspector_data.burro_speed)); } else { let entity = commands .spawn_bundle(burro_bundle) .insert(CleanupMarker) .insert_bundle(player::PlayerBundle::new( b.skin, inspector_data.burro_speed, )) .id(); let player_map = game_state.get_skin_player_map(); let (text, color) = player::get_player_indicator(player_map[&b.skin]); commands .spawn_bundle(TextBundle { style: Style { align_self: AlignSelf::FlexEnd, position_type: PositionType::Absolute, position: Rect { bottom: Val::Px(5.0), left: Val::Px(15.0), ..Default::default() }, size: Size { width: Val::Px(200.0), ..Default::default() }, ..Default::default() }, text: Text::with_section( text.to_string(), TextStyle { font: game_assets.font.clone(), font_size: 40.0, color, }, TextAlignment { ..Default::default() }, ), ..Default::default() }) .insert(CleanupMarker) .insert(follow_text::FollowText { following: entity }); } }); collidables.reset(); commands .spawn_bundle(NodeBundle { style: Style { size: Size::new(Val::Percent(100.0), Val::Percent(10.0)), position_type: PositionType::Absolute, margin: Rect { top: Val::Px(20.0), ..Default::default() }, justify_content: JustifyContent::Center, align_items: AlignItems::FlexEnd, ..Default::default() }, color: Color::NONE.into(), ..Default::default() }) .insert(CleanupMarker) .with_children(|parent| { parent .spawn_bundle(TextBundle { visibility: Visibility { is_visible: false }, style: Style { position_type: PositionType::Relative, margin: Rect { left: Val::Auto, right: Val::Auto, bottom: Val::Auto, top: Val::Auto, }, align_items: AlignItems::Center, justify_content: JustifyContent::Center, ..Default::default() }, text: Text::with_section( "Round ending in 5 seconds".to_string(), TextStyle { font: game_assets.font.clone(), font_size: 40.0, color: Color::WHITE, }, TextAlignment { horizontal: HorizontalAlign::Center, ..Default::default() }, ), ..Default::default() }) .insert(RoundEndText) .insert(CleanupMarker); }); app_state.push(AppState::MechaPicker).unwrap(); }
34.936594
93
0.503448
612c8a3b8eb679466ae194c86a0134578449bf79
31,105
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use syntax::attr::HasAttrs; use syntax::parse::ParseSess; use syntax::source_map::{self, BytePos, Pos, SourceMap, Span}; use syntax::{ast, visit}; use attr::*; use comment::{CodeCharKind, CommentCodeSlices, FindUncommented}; use config::{BraceStyle, Config}; use items::{ format_impl, format_trait, format_trait_alias, is_mod_decl, is_use_item, rewrite_associated_impl_type, rewrite_associated_type, rewrite_existential_impl_type, rewrite_existential_type, rewrite_extern_crate, rewrite_type_alias, FnSig, StaticParts, StructParts, }; use macros::{rewrite_macro, rewrite_macro_def, MacroPosition}; use rewrite::{Rewrite, RewriteContext}; use shape::{Indent, Shape}; use source_map::{LineRangeUtils, SpanUtils}; use spanned::Spanned; use utils::{ self, contains_skip, count_newlines, inner_attributes, mk_sp, ptr_vec_to_ref_vec, rewrite_ident, DEPR_SKIP_ANNOTATION, }; use {ErrorKind, FormatReport, FormattingError}; use std::cell::RefCell; /// Creates a string slice corresponding to the specified span. pub struct SnippetProvider<'a> { /// A pointer to the content of the file we are formatting. big_snippet: &'a str, /// A position of the start of `big_snippet`, used as an offset. start_pos: usize, } impl<'a> SnippetProvider<'a> { pub fn span_to_snippet(&self, span: Span) -> Option<&str> { let start_index = span.lo().to_usize().checked_sub(self.start_pos)?; let end_index = span.hi().to_usize().checked_sub(self.start_pos)?; Some(&self.big_snippet[start_index..end_index]) } pub fn new(start_pos: BytePos, big_snippet: &'a str) -> Self { let start_pos = start_pos.to_usize(); SnippetProvider { big_snippet, start_pos, } } } pub struct FmtVisitor<'a> { parent_context: Option<&'a RewriteContext<'a>>, pub parse_session: &'a ParseSess, pub source_map: &'a SourceMap, pub buffer: String, pub last_pos: BytePos, // FIXME: use an RAII util or closure for indenting pub block_indent: Indent, pub config: &'a Config, pub is_if_else_block: bool, pub snippet_provider: &'a SnippetProvider<'a>, pub line_number: usize, /// List of 1-based line ranges which were annotated with skip /// Both bounds are inclusifs. pub skipped_range: Vec<(usize, usize)>, pub macro_rewrite_failure: bool, pub(crate) report: FormatReport, } impl<'a> Drop for FmtVisitor<'a> { fn drop(&mut self) { if let Some(ctx) = self.parent_context { if self.macro_rewrite_failure { ctx.macro_rewrite_failure.replace(true); } } } } impl<'b, 'a: 'b> FmtVisitor<'a> { fn set_parent_context(&mut self, context: &'a RewriteContext) { self.parent_context = Some(context); } pub fn shape(&self) -> Shape { Shape::indented(self.block_indent, self.config) } fn visit_stmt(&mut self, stmt: &ast::Stmt) { debug!( "visit_stmt: {:?} {:?}", self.source_map.lookup_char_pos(stmt.span.lo()), self.source_map.lookup_char_pos(stmt.span.hi()) ); match stmt.node { ast::StmtKind::Item(ref item) => { self.visit_item(item); // Handle potential `;` after the item. self.format_missing(stmt.span.hi()); } ast::StmtKind::Local(..) | ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => { let attrs = get_attrs_from_stmt(stmt); if contains_skip(attrs) { self.push_skipped_with_span(attrs, stmt.span()); } else { let shape = self.shape(); let rewrite = self.with_context(|ctx| stmt.rewrite(&ctx, shape)); self.push_rewrite(stmt.span(), rewrite) } } ast::StmtKind::Mac(ref mac) => { let (ref mac, _macro_style, ref attrs) = **mac; if self.visit_attrs(attrs, ast::AttrStyle::Outer) { self.push_skipped_with_span(attrs, stmt.span()); } else { self.visit_mac(mac, None, MacroPosition::Statement); } self.format_missing(stmt.span.hi()); } } } pub fn visit_block( &mut self, b: &ast::Block, inner_attrs: Option<&[ast::Attribute]>, has_braces: bool, ) { debug!( "visit_block: {:?} {:?}", self.source_map.lookup_char_pos(b.span.lo()), self.source_map.lookup_char_pos(b.span.hi()) ); // Check if this block has braces. let brace_compensation = BytePos(if has_braces { 1 } else { 0 }); self.last_pos = self.last_pos + brace_compensation; self.block_indent = self.block_indent.block_indent(self.config); self.push_str("{"); if let Some(first_stmt) = b.stmts.first() { let attr_lo = inner_attrs .and_then(|attrs| inner_attributes(attrs).first().map(|attr| attr.span.lo())) .or_else(|| { // Attributes for an item in a statement position // do not belong to the statement. (rust-lang/rust#34459) if let ast::StmtKind::Item(ref item) = first_stmt.node { item.attrs.first() } else { first_stmt.attrs().first() } .and_then(|attr| { // Some stmts can have embedded attributes. // e.g. `match { #![attr] ... }` let attr_lo = attr.span.lo(); if attr_lo < first_stmt.span.lo() { Some(attr_lo) } else { None } }) }); let snippet = self.snippet(mk_sp( self.last_pos, attr_lo.unwrap_or_else(|| first_stmt.span.lo()), )); let len = CommentCodeSlices::new(snippet) .nth(0) .and_then(|(kind, _, s)| { if kind == CodeCharKind::Normal { s.rfind('\n') } else { None } }); if let Some(len) = len { self.last_pos = self.last_pos + BytePos::from_usize(len); } } // Format inner attributes if available. let skip_rewrite = if let Some(attrs) = inner_attrs { self.visit_attrs(attrs, ast::AttrStyle::Inner) } else { false }; if skip_rewrite { self.push_rewrite(b.span, None); self.close_block(false); self.last_pos = source!(self, b.span).hi(); return; } self.walk_block_stmts(b); if !b.stmts.is_empty() { if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) { if utils::semicolon_for_expr(&self.get_context(), expr) { self.push_str(";"); } } } let mut remove_len = BytePos(0); if let Some(stmt) = b.stmts.last() { let snippet = self.snippet(mk_sp( stmt.span.hi(), source!(self, b.span).hi() - brace_compensation, )); let len = CommentCodeSlices::new(snippet) .last() .and_then(|(kind, _, s)| { if kind == CodeCharKind::Normal && s.trim().is_empty() { Some(s.len()) } else { None } }); if let Some(len) = len { remove_len = BytePos::from_usize(len); } } let unindent_comment = self.is_if_else_block && !b.stmts.is_empty() && { let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len; let snippet = self.snippet(mk_sp(self.last_pos, end_pos)); snippet.contains("//") || snippet.contains("/*") }; // FIXME: we should compress any newlines here to just one if unindent_comment { self.block_indent = self.block_indent.block_unindent(self.config); } self.format_missing_with_indent( source!(self, b.span).hi() - brace_compensation - remove_len, ); if unindent_comment { self.block_indent = self.block_indent.block_indent(self.config); } self.close_block(unindent_comment); self.last_pos = source!(self, b.span).hi(); } // FIXME: this is a terrible hack to indent the comments between the last // item in the block and the closing brace to the block's level. // The closing brace itself, however, should be indented at a shallower // level. fn close_block(&mut self, unindent_comment: bool) { let total_len = self.buffer.len(); let chars_too_many = if unindent_comment { 0 } else if self.config.hard_tabs() { 1 } else { self.config.tab_spaces() }; self.buffer.truncate(total_len - chars_too_many); self.push_str("}"); self.block_indent = self.block_indent.block_unindent(self.config); } // Note that this only gets called for function definitions. Required methods // on traits do not get handled here. fn visit_fn( &mut self, fk: visit::FnKind, generics: &ast::Generics, fd: &ast::FnDecl, s: Span, defaultness: ast::Defaultness, inner_attrs: Option<&[ast::Attribute]>, ) { let indent = self.block_indent; let block; let rewrite = match fk { visit::FnKind::ItemFn(ident, _, _, b) | visit::FnKind::Method(ident, _, _, b) => { block = b; self.rewrite_fn( indent, ident, &FnSig::from_fn_kind(&fk, generics, fd, defaultness), mk_sp(s.lo(), b.span.lo()), b, inner_attrs, ) } visit::FnKind::Closure(_) => unreachable!(), }; if let Some(fn_str) = rewrite { self.format_missing_with_indent(source!(self, s).lo()); self.push_str(&fn_str); if let Some(c) = fn_str.chars().last() { if c == '}' { self.last_pos = source!(self, block.span).hi(); return; } } } else { self.format_missing(source!(self, block.span).lo()); } self.last_pos = source!(self, block.span).lo(); self.visit_block(block, inner_attrs, true) } pub fn visit_item(&mut self, item: &ast::Item) { skip_out_of_file_lines_range_visitor!(self, item.span); // This is where we bail out if there is a skip attribute. This is only // complex in the module case. It is complex because the module could be // in a separate file and there might be attributes in both files, but // the AST lumps them all together. let filtered_attrs; let mut attrs = &item.attrs; match item.node { // For use items, skip rewriting attributes. Just check for a skip attribute. ast::ItemKind::Use(..) => { if contains_skip(attrs) { self.push_skipped_with_span(attrs.as_slice(), item.span()); return; } } // Module is inline, in this case we treat it like any other item. _ if !is_mod_decl(item) => { if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) { self.push_skipped_with_span(item.attrs.as_slice(), item.span()); return; } } // Module is not inline, but should be skipped. ast::ItemKind::Mod(..) if contains_skip(&item.attrs) => { return; } // Module is not inline and should not be skipped. We want // to process only the attributes in the current file. ast::ItemKind::Mod(..) => { filtered_attrs = filter_inline_attrs(&item.attrs, item.span()); // Assert because if we should skip it should be caught by // the above case. assert!(!self.visit_attrs(&filtered_attrs, ast::AttrStyle::Outer)); attrs = &filtered_attrs; } _ => { if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) { self.push_skipped_with_span(item.attrs.as_slice(), item.span()); return; } } } match item.node { ast::ItemKind::Use(ref tree) => self.format_import(item, tree), ast::ItemKind::Impl(..) => { let snippet = self.snippet(item.span); let where_span_end = snippet .find_uncommented("{") .map(|x| BytePos(x as u32) + source!(self, item.span).lo()); let block_indent = self.block_indent; let rw = self.with_context(|ctx| format_impl(&ctx, item, block_indent, where_span_end)); self.push_rewrite(item.span, rw); } ast::ItemKind::Trait(..) => { let block_indent = self.block_indent; let rw = self.with_context(|ctx| format_trait(&ctx, item, block_indent)); self.push_rewrite(item.span, rw); } ast::ItemKind::TraitAlias(ref generics, ref generic_bounds) => { let shape = Shape::indented(self.block_indent, self.config); let rw = format_trait_alias( &self.get_context(), item.ident, generics, generic_bounds, shape, ); self.push_rewrite(item.span, rw); } ast::ItemKind::ExternCrate(_) => { let rw = rewrite_extern_crate(&self.get_context(), item); self.push_rewrite(item.span, rw); } ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => { self.visit_struct(&StructParts::from_item(item)); } ast::ItemKind::Enum(ref def, ref generics) => { self.format_missing_with_indent(source!(self, item.span).lo()); self.visit_enum(item.ident, &item.vis, def, generics, item.span); self.last_pos = source!(self, item.span).hi(); } ast::ItemKind::Mod(ref module) => { let is_inline = !is_mod_decl(item); self.format_missing_with_indent(source!(self, item.span).lo()); self.format_mod(module, &item.vis, item.span, item.ident, attrs, is_inline); } ast::ItemKind::Mac(ref mac) => { self.visit_mac(mac, Some(item.ident), MacroPosition::Item); } ast::ItemKind::ForeignMod(ref foreign_mod) => { self.format_missing_with_indent(source!(self, item.span).lo()); self.format_foreign_mod(foreign_mod, item.span); } ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => { self.visit_static(&StaticParts::from_item(item)); } ast::ItemKind::Fn(ref decl, fn_header, ref generics, ref body) => { let inner_attrs = inner_attributes(&item.attrs); self.visit_fn( visit::FnKind::ItemFn(item.ident, fn_header, &item.vis, body), generics, decl, item.span, ast::Defaultness::Final, Some(&inner_attrs), ) } ast::ItemKind::Ty(ref ty, ref generics) => { let rewrite = rewrite_type_alias( &self.get_context(), self.block_indent, item.ident, ty, generics, &item.vis, ); self.push_rewrite(item.span, rewrite); } ast::ItemKind::Existential(ref generic_bounds, ref generics) => { let rewrite = rewrite_existential_type( &self.get_context(), self.block_indent, item.ident, generic_bounds, generics, &item.vis, ); self.push_rewrite(item.span, rewrite); } ast::ItemKind::GlobalAsm(..) => { let snippet = Some(self.snippet(item.span).to_owned()); self.push_rewrite(item.span, snippet); } ast::ItemKind::MacroDef(ref def) => { let rewrite = rewrite_macro_def( &self.get_context(), self.shape(), self.block_indent, def, item.ident, &item.vis, item.span, ); self.push_rewrite(item.span, rewrite); } } } pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) { skip_out_of_file_lines_range_visitor!(self, ti.span); if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) { self.push_skipped_with_span(ti.attrs.as_slice(), ti.span()); return; } match ti.node { ast::TraitItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)), ast::TraitItemKind::Method(ref sig, None) => { let indent = self.block_indent; let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span); self.push_rewrite(ti.span, rewrite); } ast::TraitItemKind::Method(ref sig, Some(ref body)) => { let inner_attrs = inner_attributes(&ti.attrs); self.visit_fn( visit::FnKind::Method(ti.ident, sig, None, body), &ti.generics, &sig.decl, ti.span, ast::Defaultness::Final, Some(&inner_attrs), ); } ast::TraitItemKind::Type(ref generic_bounds, ref type_default) => { let rewrite = rewrite_associated_type( ti.ident, type_default.as_ref(), &ti.generics, Some(generic_bounds), &self.get_context(), self.block_indent, ); self.push_rewrite(ti.span, rewrite); } ast::TraitItemKind::Macro(ref mac) => { self.visit_mac(mac, Some(ti.ident), MacroPosition::Item); } } } pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) { skip_out_of_file_lines_range_visitor!(self, ii.span); if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) { self.push_skipped_with_span(ii.attrs.as_slice(), ii.span()); return; } match ii.node { ast::ImplItemKind::Method(ref sig, ref body) => { let inner_attrs = inner_attributes(&ii.attrs); self.visit_fn( visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body), &ii.generics, &sig.decl, ii.span, ii.defaultness, Some(&inner_attrs), ); } ast::ImplItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)), ast::ImplItemKind::Type(ref ty) => { let rewrite = rewrite_associated_impl_type( ii.ident, ii.defaultness, Some(ty), &ii.generics, &self.get_context(), self.block_indent, ); self.push_rewrite(ii.span, rewrite); } ast::ImplItemKind::Existential(ref generic_bounds) => { let rewrite = rewrite_existential_impl_type( &self.get_context(), ii.ident, &ii.generics, generic_bounds, self.block_indent, ); self.push_rewrite(ii.span, rewrite); } ast::ImplItemKind::Macro(ref mac) => { self.visit_mac(mac, Some(ii.ident), MacroPosition::Item); } } } fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) { skip_out_of_file_lines_range_visitor!(self, mac.span); // 1 = ; let shape = self.shape().sub_width(1).unwrap(); let rewrite = self.with_context(|ctx| rewrite_macro(mac, ident, ctx, shape, pos)); self.push_rewrite(mac.span, rewrite); } pub fn push_str(&mut self, s: &str) { self.line_number += count_newlines(s); self.buffer.push_str(s); } #[allow(clippy::needless_pass_by_value)] fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) { if let Some(ref s) = rewrite { self.push_str(s); } else { let snippet = self.snippet(span); self.push_str(snippet); } self.last_pos = source!(self, span).hi(); } pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) { self.format_missing_with_indent(source!(self, span).lo()); self.push_rewrite_inner(span, rewrite); } pub fn push_skipped_with_span(&mut self, attrs: &[ast::Attribute], item_span: Span) { self.format_missing_with_indent(source!(self, item_span).lo()); // do not take into account the lines with attributes as part of the skipped range let attrs_end = attrs .iter() .map(|attr| self.source_map.lookup_char_pos(attr.span().hi()).line) .max() .unwrap_or(1); // Add 1 to get the line past the last attribute let lo = attrs_end + 1; self.push_rewrite_inner(item_span, None); let hi = self.line_number + 1; self.skipped_range.push((lo, hi)); } pub fn from_context(ctx: &'a RewriteContext) -> FmtVisitor<'a> { let mut visitor = FmtVisitor::from_source_map( ctx.parse_session, ctx.config, ctx.snippet_provider, ctx.report.clone(), ); visitor.set_parent_context(ctx); visitor } pub(crate) fn from_source_map( parse_session: &'a ParseSess, config: &'a Config, snippet_provider: &'a SnippetProvider, report: FormatReport, ) -> FmtVisitor<'a> { FmtVisitor { parent_context: None, parse_session, source_map: parse_session.source_map(), buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2), last_pos: BytePos(0), block_indent: Indent::empty(), config, is_if_else_block: false, snippet_provider, line_number: 0, skipped_range: vec![], macro_rewrite_failure: false, report, } } pub fn opt_snippet(&'b self, span: Span) -> Option<&'a str> { self.snippet_provider.span_to_snippet(span) } pub fn snippet(&'b self, span: Span) -> &'a str { self.opt_snippet(span).unwrap() } // Returns true if we should skip the following item. pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool { for attr in attrs { if attr.name() == DEPR_SKIP_ANNOTATION { let file_name = self.source_map.span_to_filename(attr.span).into(); self.report.append( file_name, vec![FormattingError::from_span( attr.span, &self.source_map, ErrorKind::DeprecatedAttr, )], ); } else if attr.path.segments[0].ident.to_string() == "rustfmt" && (attr.path.segments.len() == 1 || attr.path.segments[1].ident.to_string() != "skip") { let file_name = self.source_map.span_to_filename(attr.span).into(); self.report.append( file_name, vec![FormattingError::from_span( attr.span, &self.source_map, ErrorKind::BadAttr, )], ); } } if contains_skip(attrs) { return true; } let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect(); if attrs.is_empty() { return false; } let rewrite = attrs.rewrite(&self.get_context(), self.shape()); let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi()); self.push_rewrite(span, rewrite); false } fn walk_mod_items(&mut self, m: &ast::Mod) { self.visit_items_with_reordering(&ptr_vec_to_ref_vec(&m.items)); } fn walk_stmts(&mut self, stmts: &[ast::Stmt]) { fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> { match stmt.node { ast::StmtKind::Item(ref item) => Some(&**item), _ => None, } } if stmts.is_empty() { return; } // Extract leading `use ...;`. let items: Vec<_> = stmts .iter() .take_while(|stmt| to_stmt_item(stmt).map_or(false, is_use_item)) .filter_map(|stmt| to_stmt_item(stmt)) .collect(); if items.is_empty() { self.visit_stmt(&stmts[0]); self.walk_stmts(&stmts[1..]); } else { self.visit_items_with_reordering(&items); self.walk_stmts(&stmts[items.len()..]); } } fn walk_block_stmts(&mut self, b: &ast::Block) { self.walk_stmts(&b.stmts) } fn format_mod( &mut self, m: &ast::Mod, vis: &ast::Visibility, s: Span, ident: ast::Ident, attrs: &[ast::Attribute], is_internal: bool, ) { let vis_str = utils::format_visibility(&self.get_context(), vis); self.push_str(&*vis_str); self.push_str("mod "); // Calling `to_owned()` to work around borrow checker. let ident_str = rewrite_ident(&self.get_context(), ident).to_owned(); self.push_str(&ident_str); if is_internal { match self.config.brace_style() { BraceStyle::AlwaysNextLine => { let indent_str = self.block_indent.to_string_with_newline(self.config); self.push_str(&indent_str); self.push_str("{"); } _ => self.push_str(" {"), } // Hackery to account for the closing }. let mod_lo = self.snippet_provider.span_after(source!(self, s), "{"); let body_snippet = self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1))); let body_snippet = body_snippet.trim(); if body_snippet.is_empty() { self.push_str("}"); } else { self.last_pos = mod_lo; self.block_indent = self.block_indent.block_indent(self.config); self.visit_attrs(attrs, ast::AttrStyle::Inner); self.walk_mod_items(m); self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1)); self.close_block(false); } self.last_pos = source!(self, m.inner).hi(); } else { self.push_str(";"); self.last_pos = source!(self, s).hi(); } } pub fn format_separate_mod(&mut self, m: &ast::Mod, source_file: &source_map::SourceFile) { self.block_indent = Indent::empty(); self.walk_mod_items(m); self.format_missing_with_indent(source_file.end_pos); } pub fn skip_empty_lines(&mut self, end_pos: BytePos) { while let Some(pos) = self .snippet_provider .opt_span_after(mk_sp(self.last_pos, end_pos), "\n") { if let Some(snippet) = self.opt_snippet(mk_sp(self.last_pos, pos)) { if snippet.trim().is_empty() { self.last_pos = pos; } else { return; } } } } pub fn with_context<F>(&mut self, f: F) -> Option<String> where F: Fn(&RewriteContext) -> Option<String>, { // FIXME borrow checker fighting - can be simplified a lot with NLL. let (result, mrf) = { let context = self.get_context(); let result = f(&context); let mrf = &context.macro_rewrite_failure.borrow(); (result, *std::ops::Deref::deref(mrf)) }; self.macro_rewrite_failure |= mrf; result } pub fn get_context(&self) -> RewriteContext { RewriteContext { parse_session: self.parse_session, source_map: self.source_map, config: self.config, inside_macro: RefCell::new(false), use_block: RefCell::new(false), is_if_else_block: RefCell::new(false), force_one_line_chain: RefCell::new(false), snippet_provider: self.snippet_provider, macro_rewrite_failure: RefCell::new(false), report: self.report.clone(), } } }
37.430806
99
0.517602