hexsha
stringlengths
40
40
size
int64
4
1.05M
content
stringlengths
4
1.05M
avg_line_length
float64
1.33
100
max_line_length
int64
1
1k
alphanum_fraction
float64
0.25
1
3331b5cdb40e1951c2e0c47d8aa98b676d382bb2
237
use crate::gc::Handle; use super::value::Value; /// A value from another frame #[derive(Debug, Clone)] pub struct Upvalue(pub Handle<Value>); impl Upvalue { pub(crate) fn mark_visited(&self) { Value::mark(&self.0) } }
16.928571
39
0.64557
3862be9cb174b5dd7855c118e0712551abe368a9
1,348
//! The "kernel" is the interface from the interpreter to the outside world. use dada_ir::func::Function; use parking_lot::Mutex; #[async_trait::async_trait] pub trait Kernel: Send + Sync { /// Implementation for the `print` intrinsic, that prints a line of text. async fn print(&self, text: &str) -> eyre::Result<()>; /// Prints a newline. async fn print_newline(&self) -> eyre::Result<()> { self.print("\n").await } } pub struct BufferKernel { buffer: Mutex<String>, } impl BufferKernel { pub fn new() -> Self { Self { buffer: Default::default(), } } pub async fn interpret(&self, db: &dyn crate::Db, function: Function) -> eyre::Result<()> { crate::interpret(function, db, self).await } pub async fn interpret_and_buffer(&self, db: &dyn crate::Db, function: Function) { match crate::interpret(function, db, self).await { Ok(()) => {} Err(e) => { self.buffer.lock().push_str(&e.to_string()); } } } pub fn into_buffer(self) -> String { Mutex::into_inner(self.buffer) } } #[async_trait::async_trait] impl Kernel for BufferKernel { async fn print(&self, message: &str) -> eyre::Result<()> { self.buffer.lock().push_str(message); Ok(()) } }
25.433962
95
0.579377
b9343a323a0931718befce6589afab97715530d7
26,325
use super::{ catalog::chunk::ChunkMetadata, pred::to_read_buffer_predicate, streams::ReadFilterResultsStream, }; use data_types::chunk_metadata::ChunkAddr; use data_types::{ chunk_metadata::{ChunkId, ChunkOrder}, delete_predicate::DeletePredicate, partition_metadata, }; use datafusion::physical_plan::SendableRecordBatchStream; use datafusion_util::MemoryStream; use internal_types::access::AccessRecorder; use iox_object_store::ParquetFilePath; use mutable_buffer::snapshot::ChunkSnapshot; use observability_deps::tracing::debug; use parquet_file::chunk::ParquetChunk; use partition_metadata::TableSummary; use predicate::predicate::{Predicate, PredicateMatch}; use query::{exec::stringset::StringSet, QueryChunk, QueryChunkMeta}; use read_buffer::RBChunk; use schema::InfluxColumnType; use schema::{selection::Selection, sort::SortKey, Schema}; use snafu::{OptionExt, ResultExt, Snafu}; use std::{ collections::{BTreeMap, BTreeSet}, sync::Arc, }; use time::Time; #[allow(clippy::enum_variant_names)] #[derive(Debug, Snafu)] pub enum Error { #[snafu(display("Mutable Buffer Chunk Error: {}", source))] MutableBufferChunk { source: mutable_buffer::snapshot::Error, }, #[snafu(display("Read Buffer Error in chunk {}: {}", chunk_id, source))] ReadBufferChunkError { source: read_buffer::Error, chunk_id: ChunkId, }, #[snafu(display("Read Buffer Error in chunk {}: {}", chunk_id, msg))] ReadBufferError { chunk_id: ChunkId, msg: String }, #[snafu(display("Parquet File Error in chunk {}: {}", chunk_id, source))] ParquetFileChunkError { source: parquet_file::chunk::Error, chunk_id: ChunkId, }, #[snafu(display("Internal error restricting schema: {}", source))] InternalSelectingSchema { source: schema::Error }, #[snafu(display("Predicate conversion error: {}", source))] PredicateConversion { source: super::pred::Error }, #[snafu(display( "Internal error: mutable buffer does not support predicate pushdown, but got: {:?}", predicate ))] InternalPredicateNotSupported { predicate: Predicate }, #[snafu(display("internal error creating plan: {}", source))] InternalPlanCreation { source: datafusion::error::DataFusionError, }, #[snafu(display("arrow conversion error: {}", source))] ArrowConversion { source: arrow::error::ArrowError }, } pub type Result<T, E = Error> = std::result::Result<T, E>; /// A IOx DatabaseChunk can come from one of three places: /// MutableBuffer, ReadBuffer, or a ParquetFile #[derive(Debug)] pub struct DbChunk { addr: ChunkAddr, access_recorder: AccessRecorder, state: State, meta: Arc<ChunkMetadata>, time_of_first_write: Time, time_of_last_write: Time, order: ChunkOrder, } #[derive(Debug)] enum State { MutableBuffer { chunk: Arc<ChunkSnapshot> }, ReadBuffer { chunk: Arc<RBChunk> }, ParquetFile { chunk: Arc<ParquetChunk> }, } impl DbChunk { /// Create a DBChunk snapshot of the catalog chunk pub fn snapshot(chunk: &super::catalog::chunk::CatalogChunk) -> Arc<Self> { let addr = chunk.addr().clone(); use super::catalog::chunk::{ChunkStage, ChunkStageFrozenRepr}; let (state, meta) = match chunk.stage() { ChunkStage::Open { mb_chunk, .. } => { let (snapshot, just_cached) = mb_chunk.snapshot(); // the snapshot might be cached, so we need to update the chunk metrics if just_cached { chunk.update_metrics(); } let state = State::MutableBuffer { chunk: Arc::clone(&snapshot), }; let meta = ChunkMetadata { table_summary: Arc::new(mb_chunk.table_summary()), schema: snapshot.full_schema(), delete_predicates: vec![], // open chunk does not have delete predicate }; (state, Arc::new(meta)) } ChunkStage::Frozen { representation, meta, .. } => { let state = match &representation { ChunkStageFrozenRepr::MutableBufferSnapshot(snapshot) => State::MutableBuffer { chunk: Arc::clone(snapshot), }, ChunkStageFrozenRepr::ReadBuffer(repr) => State::ReadBuffer { chunk: Arc::clone(repr), }, }; (state, Arc::clone(meta)) } ChunkStage::Persisted { parquet, read_buffer, meta, .. } => { let state = if let Some(read_buffer) = &read_buffer { State::ReadBuffer { chunk: Arc::clone(read_buffer), } } else { State::ParquetFile { chunk: Arc::clone(parquet), } }; (state, Arc::clone(meta)) } }; Arc::new(Self { addr, access_recorder: chunk.access_recorder().clone(), state, meta, time_of_first_write: chunk.time_of_first_write(), time_of_last_write: chunk.time_of_last_write(), order: chunk.order(), }) } /// Return the snapshot of the chunk with type ParquetFile /// This function should be only invoked when you know your chunk /// is ParquetFile type whose state is Persisted. The /// reason we have this function is because the above snapshot /// function always returns the read buffer one for the same state pub fn parquet_file_snapshot(chunk: &super::catalog::chunk::CatalogChunk) -> Arc<Self> { use super::catalog::chunk::ChunkStage; let (state, meta) = match chunk.stage() { ChunkStage::Persisted { parquet, meta, .. } => { let chunk = Arc::clone(parquet); let state = State::ParquetFile { chunk }; (state, Arc::clone(meta)) } _ => { panic!("Internal error: This chunk's stage is not Persisted"); } }; Arc::new(Self { addr: chunk.addr().clone(), meta, state, access_recorder: chunk.access_recorder().clone(), time_of_first_write: chunk.time_of_first_write(), time_of_last_write: chunk.time_of_last_write(), order: chunk.order(), }) } /// Return the Path in ObjectStorage where this chunk is /// persisted, if any pub fn object_store_path(&self) -> Option<&ParquetFilePath> { match &self.state { State::ParquetFile { chunk } => Some(chunk.path()), _ => None, } } /// Returns the contained `ParquetChunk`, if this chunk is stored as parquet pub fn parquet_chunk(&self) -> Option<&Arc<ParquetChunk>> { match &self.state { State::ParquetFile { chunk } => Some(chunk), _ => None, } } /// Return the address of this chunk pub fn addr(&self) -> &ChunkAddr { &self.addr } /// Return the name of the table in this chunk pub fn table_name(&self) -> &Arc<str> { &self.addr.table_name } pub fn time_of_first_write(&self) -> Time { self.time_of_first_write } pub fn time_of_last_write(&self) -> Time { self.time_of_last_write } /// NOTE: valid Read Buffer predicates are not guaranteed to be applicable /// to an arbitrary Read Buffer chunk, because the applicability of a /// predicate depends on the schema of the chunk. Callers should validate /// predicates against chunks they are to be executed against using /// `read_buffer::Chunk::validate_predicate` fn to_rub_negated_predicates( delete_predicates: &[Arc<Predicate>], ) -> Result<Vec<read_buffer::Predicate>> { let mut rub_preds: Vec<read_buffer::Predicate> = vec![]; for pred in delete_predicates { let rub_pred = to_read_buffer_predicate(pred).context(PredicateConversion)?; rub_preds.push(rub_pred); } debug!(?rub_preds, "RUB delete predicates"); Ok(rub_preds) } /// Return true if any of the fields called for in the `predicate` /// contain at least 1 null value. Returns false ONLY if all /// fields that pass `predicate` are entirely non null fn fields_have_nulls(&self, predicate: &Predicate) -> bool { self.meta.schema.iter().any(|(influx_column_type, field)| { if matches!(influx_column_type, Some(InfluxColumnType::Field(_))) && predicate.should_include_field(field.name()) { match self.meta.table_summary.column(field.name()) { Some(column_summary) => { // only if this is false can we return false column_summary.null_count() > 0 } None => { // don't know the stats for this column, so assume there can be nulls true } } } else { // not a field column false } }) } } impl QueryChunk for DbChunk { type Error = Error; fn id(&self) -> ChunkId { self.addr.chunk_id } fn table_name(&self) -> &str { self.addr.table_name.as_ref() } fn may_contain_pk_duplicates(&self) -> bool { // Assume that only data in the MUB can contain duplicates // within itself as it has the raw incoming stream of writes. // // All other types of chunks are deduplicated as part of // of the reorganization plan run as part of their creation matches!(self.state, State::MutableBuffer { .. }) } fn apply_predicate_to_metadata(&self, predicate: &Predicate) -> Result<PredicateMatch> { if !predicate.should_include_table(self.table_name().as_ref()) { return Ok(PredicateMatch::Zero); } let pred_result = match &self.state { State::MutableBuffer { chunk, .. } => { if predicate.has_exprs() || chunk.has_timerange(&predicate.range) { // TODO some more work to figure out if we // definite have / do not have result PredicateMatch::Unknown } else { PredicateMatch::Zero } } State::ReadBuffer { chunk, .. } => { // If the predicate is not supported by the Read Buffer then // it can't determine if the predicate can be answered by // meta-data only. A future improvement could be to apply this // logic to chunk meta-data without involving the backing // execution engine. let rb_predicate = match to_read_buffer_predicate(predicate) { Ok(rb_predicate) => rb_predicate, Err(e) => { debug!(?predicate, %e, "Cannot push down predicate to RUB, will fully scan"); return Ok(PredicateMatch::Unknown); } }; // TODO: currently this will provide an exact answer, which may // be expensive in pathological cases. It might make more // sense to implement logic that works to rule out chunks based // on meta-data only. This should be possible without needing to // know the execution engine the chunk is held in. if chunk.satisfies_predicate(&rb_predicate) { // if any of the fields referred to in the // predicate has nulls, don't know without more // work if the rows that matched had non null values if self.fields_have_nulls(predicate) { PredicateMatch::Unknown } else { PredicateMatch::AtLeastOneNonNullField } } else { PredicateMatch::Zero } } State::ParquetFile { chunk, .. } => { if predicate.has_exprs() || chunk.has_timerange(predicate.range.as_ref()) { PredicateMatch::Unknown } else { PredicateMatch::Zero } } }; Ok(pred_result) } fn read_filter( &self, predicate: &Predicate, selection: Selection<'_>, ) -> Result<SendableRecordBatchStream, Self::Error> { // Predicate is not required to be applied for correctness. We only pushed it down // when possible for performance gain debug!(table=?self.table_name(), chunk_id=%self.addr().chunk_id, ?predicate, ?selection, "read_filter called"); self.access_recorder.record_access(); let delete_predicates: Vec<_> = self .meta .delete_predicates .iter() .map(|pred| Arc::new(pred.as_ref().clone().into())) .collect(); // merge the negated delete predicates into the select predicate let mut pred_with_deleted_exprs = predicate.clone(); pred_with_deleted_exprs.merge_delete_predicates(&delete_predicates); debug!(?pred_with_deleted_exprs, "Merged negated predicate"); match &self.state { State::MutableBuffer { chunk, .. } => { let batch = chunk.read_filter(selection).context(MutableBufferChunk)?; Ok(Box::pin(MemoryStream::new(vec![batch]))) } State::ReadBuffer { chunk, .. } => { // Only apply pushdownable predicates let rb_predicate = chunk // A predicate unsupported by the Read Buffer or against // this chunk's schema is replaced with a default empty // predicate. .validate_predicate(to_read_buffer_predicate(predicate).unwrap_or_default()) .unwrap_or_default(); debug!(?rb_predicate, "RUB predicate"); // combine all delete expressions to RUB's negated ones let negated_delete_exprs = Self::to_rub_negated_predicates(&delete_predicates)? .into_iter() // Any delete predicates unsupported by the Read Buffer will be elided. .filter_map(|p| chunk.validate_predicate(p).ok()) .collect::<Vec<_>>(); debug!( ?negated_delete_exprs, "Negated Predicate pushed down to RUB" ); let read_results = chunk .read_filter(rb_predicate, selection, negated_delete_exprs) .context(ReadBufferChunkError { chunk_id: self.id(), })?; let schema = chunk .read_filter_table_schema(selection) .context(ReadBufferChunkError { chunk_id: self.id(), })?; Ok(Box::pin(ReadFilterResultsStream::new( read_results, schema.into(), ))) } State::ParquetFile { chunk, .. } => chunk .read_filter(&pred_with_deleted_exprs, selection) .context(ParquetFileChunkError { chunk_id: self.id(), }), } } fn column_names( &self, predicate: &Predicate, columns: Selection<'_>, ) -> Result<Option<StringSet>, Self::Error> { match &self.state { State::MutableBuffer { chunk, .. } => { if !predicate.is_empty() { // TODO: Support predicates return Ok(None); } self.access_recorder.record_access(); Ok(chunk.column_names(columns)) } State::ReadBuffer { chunk, .. } => { let rb_predicate = match to_read_buffer_predicate(predicate) { Ok(rb_predicate) => rb_predicate, Err(e) => { debug!(?predicate, %e, "read buffer predicate not supported for column_names, falling back"); return Ok(None); } }; self.access_recorder.record_access(); // TODO(edd): wire up delete predicates to be pushed down to // the read buffer. Ok(Some( chunk .column_names(rb_predicate, vec![], columns, BTreeSet::new()) .context(ReadBufferChunkError { chunk_id: self.id(), })?, )) } State::ParquetFile { chunk, .. } => { if !predicate.is_empty() { // TODO: Support predicates when MB supports it return Ok(None); } self.access_recorder.record_access(); Ok(chunk.column_names(columns)) } } } fn column_values( &self, column_name: &str, predicate: &Predicate, ) -> Result<Option<StringSet>, Self::Error> { match &self.state { State::MutableBuffer { .. } => { // There is no advantage to manually implementing this // vs just letting DataFusion do its thing Ok(None) } State::ReadBuffer { chunk, .. } => { let rb_predicate = match to_read_buffer_predicate(predicate) { Ok(rb_predicate) => rb_predicate, Err(e) => { debug!(?predicate, %e, "read buffer predicate not supported for column_names, falling back"); return Ok(None); } }; self.access_recorder.record_access(); let mut values = chunk .column_values( rb_predicate, Selection::Some(&[column_name]), BTreeMap::new(), ) .context(ReadBufferChunkError { chunk_id: self.id(), })?; // The InfluxRPC frontend only supports getting column values // for one column at a time (this is a restriction on the Influx // Read gRPC API too). However, the Read Buffer support multiple // columns and will return a map - we just need to pull the // column out to get the set of values. let values = values .remove(column_name) .with_context(|| ReadBufferError { chunk_id: self.id(), msg: format!( "failed to find column_name {:?} in results of tag_values", column_name ), })?; Ok(Some(values)) } State::ParquetFile { .. } => { // Since DataFusion can read Parquet, there is no advantage to // manually implementing this vs just letting DataFusion do its thing Ok(None) } } } /// Returns true if the chunk is sorted on its pk /// Since data is compacted prior being moved to RUBs, data in RUBs and OBs /// should be sorted on their PK as the results of compacting. /// However, since we current sorted data based on their cardinality (see compute_sort_key), /// 2 different chunks may be sorted on different order of key columns. fn is_sorted_on_pk(&self) -> bool { self.schema().is_sorted_on_pk() } /// Returns the sort key of the chunk if any fn sort_key(&self) -> Option<SortKey<'_>> { self.meta.schema.sort_key() } fn chunk_type(&self) -> &str { match &self.state { State::MutableBuffer { .. } => "MUB", State::ReadBuffer { .. } => "RUB", State::ParquetFile { .. } => "OS", } } fn order(&self) -> ChunkOrder { self.order } } impl QueryChunkMeta for DbChunk { fn summary(&self) -> &TableSummary { self.meta.table_summary.as_ref() } fn schema(&self) -> Arc<Schema> { Arc::clone(&self.meta.schema) } // return a reference to delete predicates of the chunk fn delete_predicates(&self) -> &[Arc<DeletePredicate>] { let pred = &self.meta.delete_predicates; debug!(?pred, "Delete predicate in DbChunk"); pred } } #[cfg(test)] mod tests { use super::*; use crate::db::{ catalog::chunk::{CatalogChunk, ChunkStage}, test_helpers::write_lp, }; use crate::utils::make_db_time; use data_types::chunk_metadata::ChunkStorage; use std::time::Duration; async fn test_chunk_access(chunk: &CatalogChunk, time: Arc<time::MockProvider>) { let m1 = chunk.access_recorder().get_metrics(); let snapshot = DbChunk::snapshot(chunk); let m2 = chunk.access_recorder().get_metrics(); let t1 = time.inc(Duration::from_secs(1)); snapshot .read_filter(&Default::default(), Selection::All) .unwrap(); let m3 = chunk.access_recorder().get_metrics(); let t2 = time.inc(Duration::from_secs(1)); let column_names = snapshot .column_names(&Default::default(), Selection::All) .unwrap() .is_some(); let m4 = chunk.access_recorder().get_metrics(); let t3 = time.inc(Duration::from_secs(1)); let column_values = snapshot .column_values("tag", &Default::default()) .unwrap() .is_some(); let m5 = chunk.access_recorder().get_metrics(); // Snapshot shouldn't count as an access assert_eq!(m1, m2); // Query should count as an access assert_eq!(m2.count + 1, m3.count); assert!(m2.last_access < m3.last_access); assert_eq!(m3.last_access, t1); // If column names successful should record access match column_names { true => { assert_eq!(m3.count + 1, m4.count); assert_eq!(m4.last_access, t2); } false => { assert_eq!(m3, m4); } } // If column values successful should record access match column_values { true => { assert_eq!(m4.count + 1, m5.count); assert!(m4.last_access < m5.last_access); assert_eq!(m5.last_access, t3); } false => { assert_eq!(m4, m5); } } } #[tokio::test] async fn mub_records_access() { let (db, time) = make_db_time().await; write_lp(&db, "cpu,tag=1 bar=1 1"); let chunks = db.catalog.chunks(); assert_eq!(chunks.len(), 1); let chunk = chunks.into_iter().next().unwrap(); let chunk = chunk.read(); assert_eq!(chunk.storage().1, ChunkStorage::OpenMutableBuffer); test_chunk_access(&chunk, time).await; } #[tokio::test] async fn rub_records_access() { let (db, time) = make_db_time().await; write_lp(&db, "cpu,tag=1 bar=1 1"); db.compact_partition("cpu", "1970-01-01T00").await.unwrap(); let chunks = db.catalog.chunks(); assert_eq!(chunks.len(), 1); let chunk = chunks.into_iter().next().unwrap(); let chunk = chunk.read(); assert_eq!(chunk.storage().1, ChunkStorage::ReadBuffer); test_chunk_access(&chunk, time).await } #[tokio::test] async fn parquet_records_access() { let (db, time) = make_db_time().await; let t0 = time.inc(Duration::from_secs(324)); write_lp(&db, "cpu,tag=1 bar=1 1"); let id = db .persist_partition("cpu", "1970-01-01T00", true) .await .unwrap() .unwrap() .id(); db.unload_read_buffer("cpu", "1970-01-01T00", id).unwrap(); let chunks = db.catalog.chunks(); assert_eq!(chunks.len(), 1); let chunk = chunks.into_iter().next().unwrap(); let chunk = chunk.read(); assert_eq!(chunk.storage().1, ChunkStorage::ObjectStoreOnly); let first_write = chunk.time_of_first_write(); let last_write = chunk.time_of_last_write(); assert_eq!(first_write, t0); assert_eq!(last_write, t0); test_chunk_access(&chunk, time).await } #[tokio::test] async fn parquet_snapshot() { let (db, time) = make_db_time().await; let w0 = time.inc(Duration::from_secs(10)); write_lp(&db, "cpu,tag=1 bar=1 1"); let w1 = time.inc(Duration::from_secs(10)); write_lp(&db, "cpu,tag=2 bar=2 2"); db.persist_partition("cpu", "1970-01-01T00", true) .await .unwrap(); let chunks = db.catalog.chunks(); assert_eq!(chunks.len(), 1); let chunk = chunks.into_iter().next().unwrap(); let chunk = chunk.read(); assert!(matches!(chunk.stage(), ChunkStage::Persisted { .. })); let snapshot = DbChunk::parquet_file_snapshot(&chunk); let first_write = snapshot.time_of_first_write(); let last_write = snapshot.time_of_last_write(); assert_eq!(w0, first_write); assert_eq!(w1, last_write); } }
36.012312
119
0.540323
726ae6fab100918158c55acf22be556c41b44bac
26,680
//! Functions concerning immediate values and operands, and reading from operands. //! All high-level functions to read from memory work on operands as sources. use std::convert::TryInto; use rustc::{mir, ty}; use rustc::ty::layout::{ self, Size, LayoutOf, TyLayout, HasDataLayout, IntegerExt, VariantIdx, }; use rustc::mir::interpret::{ GlobalId, AllocId, ConstValue, Pointer, Scalar, InterpResult, sign_extend, truncate, }; use super::{ InterpCx, Machine, MemPlace, MPlaceTy, PlaceTy, Place, }; pub use rustc::mir::interpret::ScalarMaybeUndef; /// A `Value` represents a single immediate self-contained Rust value. /// /// For optimization of a few very common cases, there is also a representation for a pair of /// primitive values (`ScalarPair`). It allows Miri to avoid making allocations for checked binary /// operations and fat pointers. This idea was taken from rustc's codegen. /// In particular, thanks to `ScalarPair`, arithmetic operations and casts can be entirely /// defined on `Immediate`, and do not have to work with a `Place`. #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)] pub enum Immediate<Tag=(), Id=AllocId> { Scalar(ScalarMaybeUndef<Tag, Id>), ScalarPair(ScalarMaybeUndef<Tag, Id>, ScalarMaybeUndef<Tag, Id>), } impl<Tag> From<ScalarMaybeUndef<Tag>> for Immediate<Tag> { #[inline(always)] fn from(val: ScalarMaybeUndef<Tag>) -> Self { Immediate::Scalar(val) } } impl<Tag> From<Scalar<Tag>> for Immediate<Tag> { #[inline(always)] fn from(val: Scalar<Tag>) -> Self { Immediate::Scalar(val.into()) } } impl<'tcx, Tag> Immediate<Tag> { pub fn new_slice( val: Scalar<Tag>, len: u64, cx: &impl HasDataLayout ) -> Self { Immediate::ScalarPair( val.into(), Scalar::from_uint(len, cx.data_layout().pointer_size).into(), ) } pub fn new_dyn_trait(val: Scalar<Tag>, vtable: Pointer<Tag>) -> Self { Immediate::ScalarPair(val.into(), Scalar::Ptr(vtable).into()) } #[inline] pub fn to_scalar_or_undef(self) -> ScalarMaybeUndef<Tag> { match self { Immediate::Scalar(val) => val, Immediate::ScalarPair(..) => bug!("Got a fat pointer where a scalar was expected"), } } #[inline] pub fn to_scalar(self) -> InterpResult<'tcx, Scalar<Tag>> { self.to_scalar_or_undef().not_undef() } #[inline] pub fn to_scalar_pair(self) -> InterpResult<'tcx, (Scalar<Tag>, Scalar<Tag>)> { match self { Immediate::Scalar(..) => bug!("Got a thin pointer where a scalar pair was expected"), Immediate::ScalarPair(a, b) => Ok((a.not_undef()?, b.not_undef()?)) } } /// Converts the immediate into a pointer (or a pointer-sized integer). /// Throws away the second half of a ScalarPair! #[inline] pub fn to_scalar_ptr(self) -> InterpResult<'tcx, Scalar<Tag>> { match self { Immediate::Scalar(ptr) | Immediate::ScalarPair(ptr, _) => ptr.not_undef(), } } /// Converts the value into its metadata. /// Throws away the first half of a ScalarPair! #[inline] pub fn to_meta(self) -> InterpResult<'tcx, Option<Scalar<Tag>>> { Ok(match self { Immediate::Scalar(_) => None, Immediate::ScalarPair(_, meta) => Some(meta.not_undef()?), }) } } // ScalarPair needs a type to interpret, so we often have an immediate and a type together // as input for binary and cast operations. #[derive(Copy, Clone, Debug)] pub struct ImmTy<'tcx, Tag=()> { pub(crate) imm: Immediate<Tag>, pub layout: TyLayout<'tcx>, } impl<'tcx, Tag> ::std::ops::Deref for ImmTy<'tcx, Tag> { type Target = Immediate<Tag>; #[inline(always)] fn deref(&self) -> &Immediate<Tag> { &self.imm } } /// An `Operand` is the result of computing a `mir::Operand`. It can be immediate, /// or still in memory. The latter is an optimization, to delay reading that chunk of /// memory and to avoid having to store arbitrary-sized data here. #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)] pub enum Operand<Tag=(), Id=AllocId> { Immediate(Immediate<Tag, Id>), Indirect(MemPlace<Tag, Id>), } impl<Tag> Operand<Tag> { #[inline] pub fn assert_mem_place(self) -> MemPlace<Tag> where Tag: ::std::fmt::Debug { match self { Operand::Indirect(mplace) => mplace, _ => bug!("assert_mem_place: expected Operand::Indirect, got {:?}", self), } } #[inline] pub fn assert_immediate(self) -> Immediate<Tag> where Tag: ::std::fmt::Debug { match self { Operand::Immediate(imm) => imm, _ => bug!("assert_immediate: expected Operand::Immediate, got {:?}", self), } } } #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)] pub struct OpTy<'tcx, Tag=()> { op: Operand<Tag>, // Keep this private, it helps enforce invariants pub layout: TyLayout<'tcx>, } impl<'tcx, Tag> ::std::ops::Deref for OpTy<'tcx, Tag> { type Target = Operand<Tag>; #[inline(always)] fn deref(&self) -> &Operand<Tag> { &self.op } } impl<'tcx, Tag: Copy> From<MPlaceTy<'tcx, Tag>> for OpTy<'tcx, Tag> { #[inline(always)] fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self { OpTy { op: Operand::Indirect(*mplace), layout: mplace.layout } } } impl<'tcx, Tag> From<ImmTy<'tcx, Tag>> for OpTy<'tcx, Tag> { #[inline(always)] fn from(val: ImmTy<'tcx, Tag>) -> Self { OpTy { op: Operand::Immediate(val.imm), layout: val.layout } } } impl<'tcx, Tag: Copy> ImmTy<'tcx, Tag> { #[inline] pub fn from_scalar(val: Scalar<Tag>, layout: TyLayout<'tcx>) -> Self { ImmTy { imm: val.into(), layout } } #[inline] pub fn from_uint(i: impl Into<u128>, layout: TyLayout<'tcx>) -> Self { Self::from_scalar(Scalar::from_uint(i, layout.size), layout) } #[inline] pub fn from_int(i: impl Into<i128>, layout: TyLayout<'tcx>) -> Self { Self::from_scalar(Scalar::from_int(i, layout.size), layout) } #[inline] pub fn to_bits(self) -> InterpResult<'tcx, u128> { self.to_scalar()?.to_bits(self.layout.size) } } // Use the existing layout if given (but sanity check in debug mode), // or compute the layout. #[inline(always)] pub(super) fn from_known_layout<'tcx>( layout: Option<TyLayout<'tcx>>, compute: impl FnOnce() -> InterpResult<'tcx, TyLayout<'tcx>> ) -> InterpResult<'tcx, TyLayout<'tcx>> { match layout { None => compute(), Some(layout) => { if cfg!(debug_assertions) { let layout2 = compute()?; assert_eq!(layout.details, layout2.details, "Mismatch in layout of supposedly equal-layout types {:?} and {:?}", layout.ty, layout2.ty); } Ok(layout) } } } impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { /// Normalice `place.ptr` to a `Pointer` if this is a place and not a ZST. /// Can be helpful to avoid lots of `force_ptr` calls later, if this place is used a lot. #[inline] pub fn force_op_ptr( &self, op: OpTy<'tcx, M::PointerTag>, ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { match op.try_as_mplace() { Ok(mplace) => Ok(self.force_mplace_ptr(mplace)?.into()), Err(imm) => Ok(imm.into()), // Nothing to cast/force } } /// Try reading an immediate in memory; this is interesting particularly for `ScalarPair`. /// Returns `None` if the layout does not permit loading this as a value. fn try_read_immediate_from_mplace( &self, mplace: MPlaceTy<'tcx, M::PointerTag>, ) -> InterpResult<'tcx, Option<ImmTy<'tcx, M::PointerTag>>> { if mplace.layout.is_unsized() { // Don't touch unsized return Ok(None); } let ptr = match self.check_mplace_access(mplace, None) .expect("places should be checked on creation") { Some(ptr) => ptr, None => return Ok(Some(ImmTy { // zero-sized type imm: Scalar::zst().into(), layout: mplace.layout, })), }; match mplace.layout.abi { layout::Abi::Scalar(..) => { let scalar = self.memory .get(ptr.alloc_id)? .read_scalar(self, ptr, mplace.layout.size)?; Ok(Some(ImmTy { imm: scalar.into(), layout: mplace.layout, })) } layout::Abi::ScalarPair(ref a, ref b) => { // We checked `ptr_align` above, so all fields will have the alignment they need. // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`, // which `ptr.offset(b_offset)` cannot possibly fail to satisfy. let (a, b) = (&a.value, &b.value); let (a_size, b_size) = (a.size(self), b.size(self)); let a_ptr = ptr; let b_offset = a_size.align_to(b.align(self).abi); assert!(b_offset.bytes() > 0); // we later use the offset to tell apart the fields let b_ptr = ptr.offset(b_offset, self)?; let a_val = self.memory .get(ptr.alloc_id)? .read_scalar(self, a_ptr, a_size)?; let b_val = self.memory .get(ptr.alloc_id)? .read_scalar(self, b_ptr, b_size)?; Ok(Some(ImmTy { imm: Immediate::ScalarPair(a_val, b_val), layout: mplace.layout, })) } _ => Ok(None), } } /// Try returning an immediate for the operand. /// If the layout does not permit loading this as an immediate, return where in memory /// we can find the data. /// Note that for a given layout, this operation will either always fail or always /// succeed! Whether it succeeds depends on whether the layout can be represented /// in a `Immediate`, not on which data is stored there currently. pub(crate) fn try_read_immediate( &self, src: OpTy<'tcx, M::PointerTag>, ) -> InterpResult<'tcx, Result<ImmTy<'tcx, M::PointerTag>, MPlaceTy<'tcx, M::PointerTag>>> { Ok(match src.try_as_mplace() { Ok(mplace) => { if let Some(val) = self.try_read_immediate_from_mplace(mplace)? { Ok(val) } else { Err(mplace) } }, Err(val) => Ok(val), }) } /// Read an immediate from a place, asserting that that is possible with the given layout. #[inline(always)] pub fn read_immediate( &self, op: OpTy<'tcx, M::PointerTag> ) -> InterpResult<'tcx, ImmTy<'tcx, M::PointerTag>> { if let Ok(imm) = self.try_read_immediate(op)? { Ok(imm) } else { bug!("primitive read failed for type: {:?}", op.layout.ty); } } /// Read a scalar from a place pub fn read_scalar( &self, op: OpTy<'tcx, M::PointerTag> ) -> InterpResult<'tcx, ScalarMaybeUndef<M::PointerTag>> { Ok(self.read_immediate(op)?.to_scalar_or_undef()) } // Turn the MPlace into a string (must already be dereferenced!) pub fn read_str( &self, mplace: MPlaceTy<'tcx, M::PointerTag>, ) -> InterpResult<'tcx, &str> { let len = mplace.len(self)?; let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len as u64))?; let str = ::std::str::from_utf8(bytes).map_err(|err| { err_unsup!(ValidationFailure(err.to_string())) })?; Ok(str) } /// Projection functions pub fn operand_field( &self, op: OpTy<'tcx, M::PointerTag>, field: u64, ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { let base = match op.try_as_mplace() { Ok(mplace) => { // The easy case let field = self.mplace_field(mplace, field)?; return Ok(field.into()); }, Err(value) => value }; let field = field.try_into().unwrap(); let field_layout = op.layout.field(self, field)?; if field_layout.is_zst() { let immediate = Scalar::zst().into(); return Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout }); } let offset = op.layout.fields.offset(field); let immediate = match *base { // the field covers the entire type _ if offset.bytes() == 0 && field_layout.size == op.layout.size => *base, // extract fields from types with `ScalarPair` ABI Immediate::ScalarPair(a, b) => { let val = if offset.bytes() == 0 { a } else { b }; Immediate::from(val) }, Immediate::Scalar(val) => bug!("field access on non aggregate {:#?}, {:#?}", val, op.layout), }; Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout }) } pub fn operand_downcast( &self, op: OpTy<'tcx, M::PointerTag>, variant: VariantIdx, ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { // Downcasts only change the layout Ok(match op.try_as_mplace() { Ok(mplace) => { self.mplace_downcast(mplace, variant)?.into() }, Err(..) => { let layout = op.layout.for_variant(self, variant); OpTy { layout, ..op } } }) } pub fn operand_projection( &self, base: OpTy<'tcx, M::PointerTag>, proj_elem: &mir::PlaceElem<'tcx>, ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { use rustc::mir::ProjectionElem::*; Ok(match *proj_elem { Field(field, _) => self.operand_field(base, field.index() as u64)?, Downcast(_, variant) => self.operand_downcast(base, variant)?, Deref => self.deref_operand(base)?.into(), Subslice { .. } | ConstantIndex { .. } | Index(_) => if base.layout.is_zst() { OpTy { op: Operand::Immediate(Scalar::zst().into()), // the actual index doesn't matter, so we just pick a convenient one like 0 layout: base.layout.field(self, 0)?, } } else { // The rest should only occur as mplace, we do not use Immediates for types // allowing such operations. This matches place_projection forcing an allocation. let mplace = base.assert_mem_place(); self.mplace_projection(mplace, proj_elem)?.into() } }) } /// This is used by [priroda](https://github.com/oli-obk/priroda) to get an OpTy from a local pub fn access_local( &self, frame: &super::Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>, local: mir::Local, layout: Option<TyLayout<'tcx>>, ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { assert_ne!(local, mir::RETURN_PLACE); let layout = self.layout_of_local(frame, local, layout)?; let op = if layout.is_zst() { // Do not read from ZST, they might not be initialized Operand::Immediate(Scalar::zst().into()) } else { frame.locals[local].access()? }; Ok(OpTy { op, layout }) } /// Every place can be read from, so we can turn them into an operand #[inline(always)] pub fn place_to_op( &self, place: PlaceTy<'tcx, M::PointerTag> ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { let op = match *place { Place::Ptr(mplace) => { Operand::Indirect(mplace) } Place::Local { frame, local } => *self.access_local(&self.stack[frame], local, None)? }; Ok(OpTy { op, layout: place.layout }) } // Evaluate a place with the goal of reading from it. This lets us sometimes // avoid allocations. pub(super) fn eval_place_to_op( &self, mir_place: &mir::Place<'tcx>, layout: Option<TyLayout<'tcx>>, ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { use rustc::mir::PlaceBase; mir_place.iterate(|place_base, place_projection| { let mut op = match place_base { PlaceBase::Local(mir::RETURN_PLACE) => throw_unsup!(ReadFromReturnPointer), PlaceBase::Local(local) => { // Do not use the layout passed in as argument if the base we are looking at // here is not the entire place. // FIXME use place_projection.is_empty() when is available let layout = if mir_place.projection.is_none() { layout } else { None }; self.access_local(self.frame(), *local, layout)? } PlaceBase::Static(place_static) => { self.eval_static_to_mplace(place_static)?.into() } }; for proj in place_projection { op = self.operand_projection(op, &proj.elem)? } trace!("eval_place_to_op: got {:?}", *op); Ok(op) }) } /// Evaluate the operand, returning a place where you can then find the data. /// If you already know the layout, you can save two table lookups /// by passing it in here. pub fn eval_operand( &self, mir_op: &mir::Operand<'tcx>, layout: Option<TyLayout<'tcx>>, ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { use rustc::mir::Operand::*; let op = match *mir_op { // FIXME: do some more logic on `move` to invalidate the old location Copy(ref place) | Move(ref place) => self.eval_place_to_op(place, layout)?, Constant(ref constant) => self.eval_const_to_op(constant.literal, layout)?, }; trace!("{:?}: {:?}", mir_op, *op); Ok(op) } /// Evaluate a bunch of operands at once pub(super) fn eval_operands( &self, ops: &[mir::Operand<'tcx>], ) -> InterpResult<'tcx, Vec<OpTy<'tcx, M::PointerTag>>> { ops.into_iter() .map(|op| self.eval_operand(op, None)) .collect() } // Used when the miri-engine runs into a constant and for extracting information from constants // in patterns via the `const_eval` module crate fn eval_const_to_op( &self, val: &'tcx ty::Const<'tcx>, layout: Option<TyLayout<'tcx>>, ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { let tag_scalar = |scalar| match scalar { Scalar::Ptr(ptr) => Scalar::Ptr(self.tag_static_base_pointer(ptr)), Scalar::Raw { data, size } => Scalar::Raw { data, size }, }; // Early-return cases. match val.val { ConstValue::Param(_) => // FIXME(oli-obk): try to monomorphize throw_inval!(TooGeneric), ConstValue::Unevaluated(def_id, substs) => { let instance = self.resolve(def_id, substs)?; return Ok(OpTy::from(self.const_eval_raw(GlobalId { instance, promoted: None, })?)); } _ => {} } // Other cases need layout. let layout = from_known_layout(layout, || { self.layout_of(self.monomorphize(val.ty)?) })?; let op = match val.val { ConstValue::ByRef { alloc, offset } => { let id = self.tcx.alloc_map.lock().create_memory_alloc(alloc); // We rely on mutability being set correctly in that allocation to prevent writes // where none should happen. let ptr = self.tag_static_base_pointer(Pointer::new(id, offset)); Operand::Indirect(MemPlace::from_ptr(ptr, layout.align.abi)) }, ConstValue::Scalar(x) => Operand::Immediate(tag_scalar(x).into()), ConstValue::Slice { data, start, end } => { // We rely on mutability being set correctly in `data` to prevent writes // where none should happen. let ptr = Pointer::new( self.tcx.alloc_map.lock().create_memory_alloc(data), Size::from_bytes(start as u64), // offset: `start` ); Operand::Immediate(Immediate::new_slice( self.tag_static_base_pointer(ptr).into(), (end - start) as u64, // len: `end - start` self, )) } ConstValue::Param(..) | ConstValue::Infer(..) | ConstValue::Placeholder(..) | ConstValue::Unevaluated(..) => bug!("eval_const_to_op: Unexpected ConstValue {:?}", val), }; Ok(OpTy { op, layout }) } /// Read discriminant, return the runtime value as well as the variant index. pub fn read_discriminant( &self, rval: OpTy<'tcx, M::PointerTag>, ) -> InterpResult<'tcx, (u128, VariantIdx)> { trace!("read_discriminant_value {:#?}", rval.layout); let (discr_kind, discr_index) = match rval.layout.variants { layout::Variants::Single { index } => { let discr_val = rval.layout.ty.discriminant_for_variant(*self.tcx, index).map_or( index.as_u32() as u128, |discr| discr.val); return Ok((discr_val, index)); } layout::Variants::Multiple { ref discr_kind, discr_index, .. } => (discr_kind, discr_index), }; // read raw discriminant value let discr_op = self.operand_field(rval, discr_index as u64)?; let discr_val = self.read_immediate(discr_op)?; let raw_discr = discr_val.to_scalar_or_undef(); trace!("discr value: {:?}", raw_discr); // post-process Ok(match *discr_kind { layout::DiscriminantKind::Tag => { let bits_discr = match raw_discr.to_bits(discr_val.layout.size) { Ok(raw_discr) => raw_discr, Err(_) => throw_unsup!(InvalidDiscriminant(raw_discr.erase_tag())), }; let real_discr = if discr_val.layout.ty.is_signed() { // going from layout tag type to typeck discriminant type // requires first sign extending with the layout discriminant let sexted = sign_extend(bits_discr, discr_val.layout.size) as i128; // and then zeroing with the typeck discriminant type let discr_ty = rval.layout.ty .ty_adt_def().expect("tagged layout corresponds to adt") .repr .discr_type(); let size = layout::Integer::from_attr(self, discr_ty).size(); let truncatee = sexted as u128; truncate(truncatee, size) } else { bits_discr }; // Make sure we catch invalid discriminants let index = match &rval.layout.ty.sty { ty::Adt(adt, _) => adt .discriminants(self.tcx.tcx) .find(|(_, var)| var.val == real_discr), ty::Generator(def_id, substs, _) => substs .discriminants(*def_id, self.tcx.tcx) .find(|(_, var)| var.val == real_discr), _ => bug!("tagged layout for non-adt non-generator"), }.ok_or_else( || err_unsup!(InvalidDiscriminant(raw_discr.erase_tag())) )?; (real_discr, index.0) }, layout::DiscriminantKind::Niche { dataful_variant, ref niche_variants, niche_start, } => { let variants_start = niche_variants.start().as_u32() as u128; let variants_end = niche_variants.end().as_u32() as u128; let raw_discr = raw_discr.not_undef().map_err(|_| { err_unsup!(InvalidDiscriminant(ScalarMaybeUndef::Undef)) })?; match raw_discr.to_bits_or_ptr(discr_val.layout.size, self) { Err(ptr) => { // The niche must be just 0 (which an inbounds pointer value never is) let ptr_valid = niche_start == 0 && variants_start == variants_end && !self.memory.ptr_may_be_null(ptr); if !ptr_valid { throw_unsup!(InvalidDiscriminant(raw_discr.erase_tag().into())) } (dataful_variant.as_u32() as u128, dataful_variant) }, Ok(raw_discr) => { let adjusted_discr = raw_discr.wrapping_sub(niche_start) .wrapping_add(variants_start); if variants_start <= adjusted_discr && adjusted_discr <= variants_end { let index = adjusted_discr as usize; assert_eq!(index as u128, adjusted_discr); assert!(index < rval.layout.ty .ty_adt_def() .expect("tagged layout for non adt") .variants.len()); (adjusted_discr, VariantIdx::from_usize(index)) } else { (dataful_variant.as_u32() as u128, dataful_variant) } }, } } }) } }
38.005698
99
0.536094
2f23a1bdbf35a4749e0cb1a99b930b3c12a1818a
41,670
/* Copyright 2017 Mozilla Foundation * * 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. */ // See https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md use std::boxed::Box; use std::vec::Vec; use limits::{ MAX_WASM_FUNCTIONS, MAX_WASM_FUNCTION_LOCALS, MAX_WASM_STRING_SIZE, MAX_WASM_TABLE_ENTRIES, }; use primitives::{ BinaryReaderError, CustomSectionKind, ExternalKind, FuncType, GlobalType, ImportSectionEntryType, LinkingType, MemoryType, Naming, Operator, RelocType, Result, SectionCode, TableType, Type, }; use readers::{ CodeSectionReader, Data, DataSectionReader, Element, ElementItems, ElementSectionReader, Export, ExportSectionReader, FunctionBody, FunctionSectionReader, Global, GlobalSectionReader, Import, ImportSectionReader, LinkingSectionReader, MemorySectionReader, ModuleReader, Name, NameSectionReader, NamingReader, OperatorsReader, Reloc, RelocSectionReader, Section, SectionReader, TableSectionReader, TypeSectionReader, }; use binary_reader::{BinaryReader, Range}; const MAX_DATA_CHUNK_SIZE: usize = MAX_WASM_STRING_SIZE; #[derive(Debug)] pub struct LocalName<'a> { pub index: u32, pub locals: Box<[Naming<'a>]>, } #[derive(Debug)] pub enum NameEntry<'a> { Module(&'a [u8]), Function(Box<[Naming<'a>]>), Local(Box<[LocalName<'a>]>), } #[derive(Debug)] pub struct RelocEntry { pub ty: RelocType, pub offset: u32, pub index: u32, pub addend: Option<u32>, } enum InitExpressionContinuation { GlobalSection, ElementSection, DataSection, } #[derive(Debug)] pub enum ParserState<'a> { Error(BinaryReaderError), Initial, BeginWasm { version: u32, }, EndWasm, BeginSection { code: SectionCode<'a>, range: Range, }, EndSection, SkippingSection, ReadingCustomSection(CustomSectionKind), ReadingSectionRawData, SectionRawData(&'a [u8]), TypeSectionEntry(FuncType), ImportSectionEntry { module: &'a [u8], field: &'a [u8], ty: ImportSectionEntryType, }, FunctionSectionEntry(u32), TableSectionEntry(TableType), MemorySectionEntry(MemoryType), ExportSectionEntry { field: &'a [u8], kind: ExternalKind, index: u32, }, NameSectionEntry(NameEntry<'a>), StartSectionEntry(u32), BeginInitExpressionBody, InitExpressionOperator(Operator<'a>), EndInitExpressionBody, BeginFunctionBody { range: Range, }, FunctionBodyLocals { locals: Box<[(u32, Type)]>, }, CodeOperator(Operator<'a>), EndFunctionBody, SkippingFunctionBody, BeginElementSectionEntry(u32), ElementSectionEntryBody(Box<[u32]>), EndElementSectionEntry, BeginDataSectionEntry(u32), EndDataSectionEntry, BeginDataSectionEntryBody(u32), DataSectionEntryBodyChunk(&'a [u8]), EndDataSectionEntryBody, BeginGlobalSectionEntry(GlobalType), EndGlobalSectionEntry, RelocSectionHeader(SectionCode<'a>), RelocSectionEntry(RelocEntry), LinkingSectionEntry(LinkingType), SourceMappingURL(&'a [u8]), } #[derive(Debug, Copy, Clone)] pub enum ParserInput { Default, SkipSection, SkipFunctionBody, ReadCustomSection, ReadSectionRawData, } pub trait WasmDecoder<'a> { fn read(&mut self) -> &ParserState<'a>; fn push_input(&mut self, input: ParserInput); fn read_with_input(&mut self, input: ParserInput) -> &ParserState<'a>; fn create_binary_reader<'b>(&mut self) -> BinaryReader<'b> where 'a: 'b; fn last_state(&self) -> &ParserState<'a>; } enum ParserSectionReader<'a> { None, CodeSectionReader(CodeSectionReader<'a>), DataSectionReader(DataSectionReader<'a>), ElementSectionReader(ElementSectionReader<'a>), ExportSectionReader(ExportSectionReader<'a>), FunctionSectionReader(FunctionSectionReader<'a>), GlobalSectionReader(GlobalSectionReader<'a>), ImportSectionReader(ImportSectionReader<'a>), MemorySectionReader(MemorySectionReader<'a>), TableSectionReader(TableSectionReader<'a>), TypeSectionReader(TypeSectionReader<'a>), NameSectionReader(NameSectionReader<'a>), LinkingSectionReader(LinkingSectionReader<'a>), RelocSectionReader(RelocSectionReader<'a>), } macro_rules! section_reader { ($self:ident, $ty_and_name:ident) => { if let ParserSectionReader::$ty_and_name(ref mut reader) = $self.section_reader { reader } else { panic!("expected {} reader", stringify!($ty_and_name)); } }; } macro_rules! start_section_reader { ($self:ident, $ty_and_name:ident, $factory:ident) => {{ let reader = $self .current_section .as_ref() .expect("section") .$factory()?; $self.section_entries_left = reader.get_count(); $self.section_reader = ParserSectionReader::$ty_and_name(reader); }}; } /// The `Parser` type. A simple event-driven parser of WebAssembly binary /// format. The `read(&mut self)` is used to iterate through WebAssembly records. pub struct Parser<'a> { data: &'a [u8], state: ParserState<'a>, module_reader: Option<ModuleReader<'a>>, current_section: Option<Section<'a>>, section_reader: ParserSectionReader<'a>, element_items: Option<ElementItems<'a>>, current_function_body: Option<FunctionBody<'a>>, init_expr_continuation: Option<InitExpressionContinuation>, current_data_segment: Option<&'a [u8]>, binary_reader: Option<BinaryReader<'a>>, operators_reader: Option<OperatorsReader<'a>>, section_entries_left: u32, } impl<'a> Parser<'a> { /// Constructs `Parser` type. /// /// # Examples /// ``` /// let data: &[u8] = &[0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, /// 0x01, 0x4, 0x01, 0x60, 0x00, 0x00, 0x03, 0x02, 0x01, 0x00, /// 0x0a, 0x05, 0x01, 0x03, 0x00, 0x01, 0x0b]; /// let mut parser = wasmparser::Parser::new(data); /// ``` pub fn new(data: &[u8]) -> Parser { Parser { data, state: ParserState::Initial, module_reader: None, current_section: None, section_reader: ParserSectionReader::None, element_items: None, current_function_body: None, init_expr_continuation: None, current_data_segment: None, binary_reader: None, operators_reader: None, section_entries_left: 0, } } pub fn eof(&self) -> bool { match self.state { ParserState::EndWasm => true, ParserState::BeginWasm { .. } | ParserState::EndSection => { self.module_reader.as_ref().expect("module reader").eof() } _ => false, // in-process of reading } } pub fn current_position(&self) -> usize { if let ParserState::Initial = self.state { return 0; } if self.binary_reader.is_some() { return self .binary_reader .as_ref() .expect("binary reader") .original_position(); } if self.operators_reader.is_some() { return self .operators_reader .as_ref() .expect("operators reader") .original_position(); } match self.section_reader { ParserSectionReader::CodeSectionReader(ref reader) => return reader.original_position(), ParserSectionReader::DataSectionReader(ref reader) => return reader.original_position(), ParserSectionReader::ElementSectionReader(ref reader) => { return reader.original_position() } ParserSectionReader::ExportSectionReader(ref reader) => { return reader.original_position() } ParserSectionReader::FunctionSectionReader(ref reader) => { return reader.original_position() } ParserSectionReader::GlobalSectionReader(ref reader) => { return reader.original_position() } ParserSectionReader::ImportSectionReader(ref reader) => { return reader.original_position() } ParserSectionReader::MemorySectionReader(ref reader) => { return reader.original_position() } ParserSectionReader::TableSectionReader(ref reader) => { return reader.original_position() } ParserSectionReader::TypeSectionReader(ref reader) => return reader.original_position(), ParserSectionReader::NameSectionReader(ref reader) => return reader.original_position(), ParserSectionReader::LinkingSectionReader(ref reader) => { return reader.original_position() } ParserSectionReader::RelocSectionReader(ref reader) => { return reader.original_position() } _ => (), }; // TODO might not cover all cases self.module_reader .as_ref() .expect("module reader") .current_position() } fn read_module(&mut self) -> Result<()> { let module_reader = ModuleReader::new(self.data)?; let version = module_reader.get_version(); self.module_reader = Some(module_reader); self.state = ParserState::BeginWasm { version }; Ok(()) } fn read_section_header(&mut self) -> Result<()> { let section = self.module_reader.as_mut().expect("module reader").read()?; let code = section.code; let range = section.get_range(); self.current_section = Some(section); self.state = ParserState::BeginSection { code, range }; Ok(()) } fn read_type_entry(&mut self) -> Result<()> { if self.section_entries_left == 0 { return self.check_section_end(); } let type_entry = section_reader!(self, TypeSectionReader).read()?; self.state = ParserState::TypeSectionEntry(type_entry); self.section_entries_left -= 1; Ok(()) } fn read_import_entry(&mut self) -> Result<()> { if self.section_entries_left == 0 { return self.check_section_end(); } let Import { module, field, ty } = section_reader!(self, ImportSectionReader).read()?; self.state = ParserState::ImportSectionEntry { module, field, ty }; self.section_entries_left -= 1; Ok(()) } fn read_function_entry(&mut self) -> Result<()> { if self.section_entries_left == 0 { return self.check_section_end(); } let func_type = section_reader!(self, FunctionSectionReader).read()?; self.state = ParserState::FunctionSectionEntry(func_type); self.section_entries_left -= 1; Ok(()) } fn read_memory_entry(&mut self) -> Result<()> { if self.section_entries_left == 0 { return self.check_section_end(); } let memory_type = section_reader!(self, MemorySectionReader).read()?; self.state = ParserState::MemorySectionEntry(memory_type); self.section_entries_left -= 1; Ok(()) } fn read_global_entry(&mut self) -> Result<()> { if self.section_entries_left == 0 { return self.check_section_end(); } let Global { ty, init_expr } = section_reader!(self, GlobalSectionReader).read()?; self.state = ParserState::BeginGlobalSectionEntry(ty); self.operators_reader = Some(init_expr.get_operators_reader()); self.section_entries_left -= 1; Ok(()) } fn read_init_expression_body(&mut self, cont: InitExpressionContinuation) { self.state = ParserState::BeginInitExpressionBody; self.init_expr_continuation = Some(cont); } fn read_init_expression_operator(&mut self) -> Result<()> { let op = self .operators_reader .as_mut() .expect("operator reader") .read()?; if let Operator::End = op { self.operators_reader = None; self.state = ParserState::EndInitExpressionBody; return Ok(()); } self.state = ParserState::InitExpressionOperator(op); Ok(()) } fn read_export_entry(&mut self) -> Result<()> { if self.section_entries_left == 0 { return self.check_section_end(); } let Export { field, kind, index } = section_reader!(self, ExportSectionReader).read()?; self.state = ParserState::ExportSectionEntry { field, kind, index }; self.section_entries_left -= 1; Ok(()) } fn read_element_entry(&mut self) -> Result<()> { if self.section_entries_left == 0 { return self.check_section_end(); } let Element { table_index, init_expr, items, } = section_reader!(self, ElementSectionReader).read()?; self.state = ParserState::BeginElementSectionEntry(table_index); self.operators_reader = Some(init_expr.get_operators_reader()); self.element_items = Some(items); self.section_entries_left -= 1; Ok(()) } fn read_element_entry_body(&mut self) -> Result<()> { let mut reader = self .element_items .take() .expect("element items") .get_items_reader()?; let num_elements = reader.get_count() as usize; if num_elements > MAX_WASM_TABLE_ENTRIES { return Err(BinaryReaderError { message: "num_elements is out of bounds", offset: 0, // reader.position - 1, // TODO offset }); } let mut elements: Vec<u32> = Vec::with_capacity(num_elements); for _ in 0..num_elements { elements.push(reader.read()?); } self.state = ParserState::ElementSectionEntryBody(elements.into_boxed_slice()); Ok(()) } fn read_function_body(&mut self) -> Result<()> { if self.section_entries_left == 0 { self.current_function_body = None; return self.check_section_end(); } let function_body = section_reader!(self, CodeSectionReader).read()?; let range = function_body.get_range(); self.state = ParserState::BeginFunctionBody { range }; self.current_function_body = Some(function_body); self.section_entries_left -= 1; Ok(()) } fn read_function_body_locals(&mut self) -> Result<()> { let function_body = self.current_function_body.as_mut().expect("function body"); let mut reader = function_body.get_locals_reader()?; let local_count = reader.get_count() as usize; if local_count > MAX_WASM_FUNCTION_LOCALS { return Err(BinaryReaderError { message: "local_count is out of bounds", offset: reader.original_position() - 1, }); } let mut locals: Vec<(u32, Type)> = Vec::with_capacity(local_count); let mut locals_total: usize = 0; for _ in 0..local_count { let (count, ty) = reader.read()?; locals_total = locals_total .checked_add(count as usize) .ok_or_else(|| BinaryReaderError { message: "locals_total is out of bounds", offset: reader.original_position() - 1, })?; if locals_total > MAX_WASM_FUNCTION_LOCALS { return Err(BinaryReaderError { message: "locals_total is out of bounds", offset: reader.original_position() - 1, }); } locals.push((count, ty)); } self.operators_reader = Some(function_body.get_operators_reader()?); self.state = ParserState::FunctionBodyLocals { locals: locals.into_boxed_slice(), }; Ok(()) } fn read_code_operator(&mut self) -> Result<()> { if self .operators_reader .as_ref() .expect("operator reader") .eof() { if let ParserState::CodeOperator(Operator::End) = self.state { self.state = ParserState::EndFunctionBody; self.operators_reader = None; self.current_function_body = None; return Ok(()); } let reader = self.operators_reader.as_ref().expect("operator reader"); return Err(BinaryReaderError { message: "Expected end of function marker", offset: reader.original_position(), }); } let reader = self.operators_reader.as_mut().expect("operator reader"); let op = reader.read()?; self.state = ParserState::CodeOperator(op); Ok(()) } fn read_table_entry(&mut self) -> Result<()> { if self.section_entries_left == 0 { return self.check_section_end(); } let table_entry = section_reader!(self, TableSectionReader).read()?; self.state = ParserState::TableSectionEntry(table_entry); self.section_entries_left -= 1; Ok(()) } fn read_data_entry(&mut self) -> Result<()> { if self.section_entries_left == 0 { return self.check_section_end(); } let Data { memory_index, init_expr, data, } = section_reader!(self, DataSectionReader).read()?; self.state = ParserState::BeginDataSectionEntry(memory_index); self.operators_reader = Some(init_expr.get_operators_reader()); self.current_data_segment = Some(data); self.section_entries_left -= 1; Ok(()) } fn read_data_entry_body(&mut self) -> Result<()> { let size = self.current_data_segment.expect("data entry").len(); self.state = ParserState::BeginDataSectionEntryBody(size as u32); Ok(()) } fn read_naming<'b>( mut naming_reader: NamingReader<'a>, limit: usize, ) -> Result<Box<[Naming<'b>]>> where 'a: 'b, { let count = naming_reader.get_count() as usize; if count > limit { return Err(BinaryReaderError { message: "name map size is out of bound", offset: naming_reader.original_position() - 1, }); } let mut result = Vec::with_capacity(count); for _ in 0..count { result.push(naming_reader.read()?); } Ok(result.into_boxed_slice()) } fn read_name_entry(&mut self) -> Result<()> { if section_reader!(self, NameSectionReader).eof() { return self.position_to_section_end(); } let entry = match section_reader!(self, NameSectionReader).read()? { Name::Module(name) => NameEntry::Module(name.get_name()?), Name::Function(func) => { NameEntry::Function(Self::read_naming(func.get_map()?, MAX_WASM_FUNCTIONS)?) } Name::Local(locals) => { let mut reader = locals.get_function_local_reader()?; let funcs_len = reader.get_count() as usize; if funcs_len > MAX_WASM_FUNCTIONS { return Err(BinaryReaderError { message: "function count is out of bounds", offset: reader.original_position() - 1, }); } let mut funcs: Vec<LocalName<'a>> = Vec::with_capacity(funcs_len); for _ in 0..funcs_len { let func = reader.read()?; funcs.push(LocalName { index: func.func_index, locals: Self::read_naming(func.get_map()?, MAX_WASM_FUNCTION_LOCALS)?, }); } NameEntry::Local(funcs.into_boxed_slice()) } }; self.state = ParserState::NameSectionEntry(entry); Ok(()) } fn read_source_mapping(&mut self) -> Result<()> { let url = self .current_section .as_ref() .expect("section") .get_sourcemappingurl_section_content()?; self.state = ParserState::SourceMappingURL(url); Ok(()) } // See https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md fn read_reloc_header(&mut self) -> Result<()> { let section_code = section_reader!(self, RelocSectionReader).get_section_code(); self.state = ParserState::RelocSectionHeader(section_code); Ok(()) } fn read_reloc_entry(&mut self) -> Result<()> { if self.section_entries_left == 0 { return self.check_section_end(); } let Reloc { ty, offset, index, addend, } = section_reader!(self, RelocSectionReader).read()?; self.state = ParserState::RelocSectionEntry(RelocEntry { ty, offset, index, addend, }); self.section_entries_left -= 1; Ok(()) } fn read_linking_entry(&mut self) -> Result<()> { if self.section_entries_left == 0 { return self.check_section_end(); } let entry = section_reader!(self, LinkingSectionReader).read()?; self.state = ParserState::LinkingSectionEntry(entry); self.section_entries_left -= 1; Ok(()) } fn read_section_body(&mut self) -> Result<()> { match self.state { ParserState::BeginSection { code: SectionCode::Type, .. } => { start_section_reader!(self, TypeSectionReader, get_type_section_reader); self.read_type_entry()?; } ParserState::BeginSection { code: SectionCode::Import, .. } => { start_section_reader!(self, ImportSectionReader, get_import_section_reader); self.read_import_entry()?; } ParserState::BeginSection { code: SectionCode::Function, .. } => { start_section_reader!(self, FunctionSectionReader, get_function_section_reader); self.read_function_entry()?; } ParserState::BeginSection { code: SectionCode::Memory, .. } => { start_section_reader!(self, MemorySectionReader, get_memory_section_reader); self.read_memory_entry()?; } ParserState::BeginSection { code: SectionCode::Global, .. } => { start_section_reader!(self, GlobalSectionReader, get_global_section_reader); self.read_global_entry()?; } ParserState::BeginSection { code: SectionCode::Export, .. } => { start_section_reader!(self, ExportSectionReader, get_export_section_reader); self.read_export_entry()?; } ParserState::BeginSection { code: SectionCode::Element, .. } => { start_section_reader!(self, ElementSectionReader, get_element_section_reader); self.read_element_entry()?; } ParserState::BeginSection { code: SectionCode::Code, .. } => { start_section_reader!(self, CodeSectionReader, get_code_section_reader); self.read_function_body()?; } ParserState::BeginSection { code: SectionCode::Table, .. } => { start_section_reader!(self, TableSectionReader, get_table_section_reader); self.read_table_entry()?; } ParserState::BeginSection { code: SectionCode::Data, .. } => { start_section_reader!(self, DataSectionReader, get_data_section_reader); self.read_data_entry()?; } ParserState::BeginSection { code: SectionCode::Start, .. } => { let func_index = self .current_section .as_ref() .expect("section") .get_start_section_content()?; self.state = ParserState::StartSectionEntry(func_index); } ParserState::BeginSection { code: SectionCode::Custom { .. }, .. } => { self.create_custom_section_binary_reader(); self.read_section_body_bytes()?; } _ => unreachable!(), } Ok(()) } fn create_custom_section_binary_reader(&mut self) { let reader = self .current_section .as_ref() .expect("section") .get_binary_reader(); self.binary_reader = Some(reader); } fn read_custom_section_body(&mut self) -> Result<()> { match self.state { ParserState::ReadingCustomSection(CustomSectionKind::Name) => { let reader = self .current_section .as_ref() .expect("section") .get_name_section_reader()?; self.section_reader = ParserSectionReader::NameSectionReader(reader); self.read_name_entry()?; } ParserState::ReadingCustomSection(CustomSectionKind::SourceMappingURL) => { self.read_source_mapping()?; } ParserState::ReadingCustomSection(CustomSectionKind::Reloc) => { start_section_reader!(self, RelocSectionReader, get_reloc_section_reader); self.read_reloc_header()?; } ParserState::ReadingCustomSection(CustomSectionKind::Linking) => { start_section_reader!(self, LinkingSectionReader, get_linking_section_reader); self.read_linking_entry()?; } ParserState::ReadingCustomSection(CustomSectionKind::Unknown) => { self.create_custom_section_binary_reader(); self.read_section_body_bytes()?; } _ => unreachable!(), } Ok(()) } fn position_to_section_end(&mut self) -> Result<()> { self.current_section = None; self.binary_reader = None; self.state = ParserState::EndSection; Ok(()) } fn check_section_end(&mut self) -> Result<()> { match self.section_reader { ParserSectionReader::CodeSectionReader(ref reader) => reader.ensure_end()?, ParserSectionReader::DataSectionReader(ref reader) => reader.ensure_end()?, ParserSectionReader::ElementSectionReader(ref reader) => reader.ensure_end()?, ParserSectionReader::ExportSectionReader(ref reader) => reader.ensure_end()?, ParserSectionReader::FunctionSectionReader(ref reader) => reader.ensure_end()?, ParserSectionReader::GlobalSectionReader(ref reader) => reader.ensure_end()?, ParserSectionReader::ImportSectionReader(ref reader) => reader.ensure_end()?, ParserSectionReader::MemorySectionReader(ref reader) => reader.ensure_end()?, ParserSectionReader::TableSectionReader(ref reader) => reader.ensure_end()?, ParserSectionReader::TypeSectionReader(ref reader) => reader.ensure_end()?, ParserSectionReader::LinkingSectionReader(ref reader) => reader.ensure_end()?, ParserSectionReader::RelocSectionReader(ref reader) => reader.ensure_end()?, _ => unreachable!(), } self.position_to_section_end() } fn read_section_body_bytes(&mut self) -> Result<()> { if self.binary_reader.as_ref().expect("binary reader").eof() { self.state = ParserState::EndSection; self.binary_reader = None; return Ok(()); } let binary_reader = self.binary_reader.as_mut().expect("binary reader"); let to_read = if binary_reader.buffer.len() - binary_reader.position < MAX_DATA_CHUNK_SIZE { binary_reader.buffer.len() - binary_reader.position } else { MAX_DATA_CHUNK_SIZE }; let bytes = binary_reader.read_bytes(to_read)?; self.state = ParserState::SectionRawData(bytes); Ok(()) } fn read_data_chunk(&mut self) -> Result<()> { let data = self.current_data_segment.expect("data"); if data.len() == 0 { self.state = ParserState::EndDataSectionEntryBody; self.current_data_segment = None; return Ok(()); } let to_read = if data.len() > MAX_DATA_CHUNK_SIZE { MAX_DATA_CHUNK_SIZE } else { data.len() }; let (head, tail) = data.split_at(to_read); self.current_data_segment = Some(tail); self.state = ParserState::DataSectionEntryBodyChunk(head); Ok(()) } fn read_next_section(&mut self) -> Result<()> { if self.module_reader.as_ref().expect("module_reader").eof() { self.current_section = None; self.state = ParserState::EndWasm; } else { self.read_section_header()?; } Ok(()) } fn read_wrapped(&mut self) -> Result<()> { match self.state { ParserState::EndWasm => panic!("Parser in end state"), ParserState::Error(_) => panic!("Parser in error state"), ParserState::Initial => self.read_module()?, ParserState::BeginWasm { .. } | ParserState::EndSection => self.read_next_section()?, ParserState::BeginSection { .. } => self.read_section_body()?, ParserState::SkippingSection => { self.position_to_section_end()?; self.read_next_section()?; } ParserState::TypeSectionEntry(_) => self.read_type_entry()?, ParserState::ImportSectionEntry { .. } => self.read_import_entry()?, ParserState::FunctionSectionEntry(_) => self.read_function_entry()?, ParserState::MemorySectionEntry(_) => self.read_memory_entry()?, ParserState::TableSectionEntry(_) => self.read_table_entry()?, ParserState::ExportSectionEntry { .. } => self.read_export_entry()?, ParserState::BeginGlobalSectionEntry(_) => { self.read_init_expression_body(InitExpressionContinuation::GlobalSection) } ParserState::EndGlobalSectionEntry => self.read_global_entry()?, ParserState::BeginElementSectionEntry(_) => { self.read_init_expression_body(InitExpressionContinuation::ElementSection) } ParserState::BeginInitExpressionBody | ParserState::InitExpressionOperator(_) => { self.read_init_expression_operator()? } ParserState::BeginDataSectionEntry(_) => { self.read_init_expression_body(InitExpressionContinuation::DataSection) } ParserState::EndInitExpressionBody => { match self.init_expr_continuation { Some(InitExpressionContinuation::GlobalSection) => { self.state = ParserState::EndGlobalSectionEntry } Some(InitExpressionContinuation::ElementSection) => { self.read_element_entry_body()? } Some(InitExpressionContinuation::DataSection) => self.read_data_entry_body()?, None => unreachable!(), } self.init_expr_continuation = None; } ParserState::BeginFunctionBody { .. } => self.read_function_body_locals()?, ParserState::FunctionBodyLocals { .. } | ParserState::CodeOperator(_) => { self.read_code_operator()? } ParserState::EndFunctionBody => self.read_function_body()?, ParserState::SkippingFunctionBody => { self.current_function_body = None; self.read_function_body()?; } ParserState::EndDataSectionEntry => self.read_data_entry()?, ParserState::BeginDataSectionEntryBody(_) | ParserState::DataSectionEntryBodyChunk(_) => self.read_data_chunk()?, ParserState::EndDataSectionEntryBody => { self.state = ParserState::EndDataSectionEntry; } ParserState::ElementSectionEntryBody(_) => { self.state = ParserState::EndElementSectionEntry; } ParserState::EndElementSectionEntry => self.read_element_entry()?, ParserState::StartSectionEntry(_) => self.position_to_section_end()?, ParserState::NameSectionEntry(_) => self.read_name_entry()?, ParserState::SourceMappingURL(_) => self.position_to_section_end()?, ParserState::RelocSectionHeader(_) => { let mut reader = self .current_section .as_ref() .expect("section") .get_binary_reader(); self.section_entries_left = reader.read_var_u32()?; self.binary_reader = Some(reader); self.read_reloc_entry()?; } ParserState::RelocSectionEntry(_) => self.read_reloc_entry()?, ParserState::LinkingSectionEntry(_) => self.read_linking_entry()?, ParserState::ReadingCustomSection(_) => self.read_custom_section_body()?, ParserState::ReadingSectionRawData | ParserState::SectionRawData(_) => { self.read_section_body_bytes()? } } Ok(()) } fn skip_section(&mut self) { match self.state { ParserState::Initial | ParserState::EndWasm | ParserState::Error(_) | ParserState::BeginWasm { .. } | ParserState::EndSection => panic!("Invalid reader state during skip section"), _ => self.state = ParserState::SkippingSection, } } fn skip_function_body(&mut self) { match self.state { ParserState::BeginFunctionBody { .. } | ParserState::FunctionBodyLocals { .. } | ParserState::CodeOperator(_) => self.state = ParserState::SkippingFunctionBody, _ => panic!("Invalid reader state during skip function body"), } } fn read_custom_section(&mut self) { match self.state { ParserState::BeginSection { code: SectionCode::Custom { kind, .. }, .. } => { self.state = ParserState::ReadingCustomSection(kind); } _ => panic!("Invalid reader state during reading custom section"), } } fn read_raw_section_data(&mut self) { match self.state { ParserState::BeginSection { .. } => { self.binary_reader = Some( self.current_section .as_ref() .expect("section") .get_binary_reader(), ); self.state = ParserState::ReadingSectionRawData; } _ => panic!("Invalid reader state during reading raw section data"), } } } impl<'a> WasmDecoder<'a> for Parser<'a> { /// Reads next record from the WebAssembly binary data. The methods returns /// reference to current state of the parser. See `ParserState` num. /// /// # Examples /// ``` /// # let data: &[u8] = &[0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, /// # 0x01, 0x4, 0x01, 0x60, 0x00, 0x00, 0x03, 0x02, 0x01, 0x00, /// # 0x0a, 0x05, 0x01, 0x03, 0x00, 0x01, 0x0b]; /// use wasmparser::WasmDecoder; /// let mut parser = wasmparser::Parser::new(data); /// { /// let state = parser.read(); /// println!("First state {:?}", state); /// } /// { /// let state = parser.read(); /// println!("Second state {:?}", state); /// } /// ``` fn read(&mut self) -> &ParserState<'a> { let result = self.read_wrapped(); if result.is_err() { self.state = ParserState::Error(result.err().unwrap()); } &self.state } fn push_input(&mut self, input: ParserInput) { match input { ParserInput::Default => (), ParserInput::SkipSection => self.skip_section(), ParserInput::SkipFunctionBody => self.skip_function_body(), ParserInput::ReadCustomSection => self.read_custom_section(), ParserInput::ReadSectionRawData => self.read_raw_section_data(), } } /// Creates a BinaryReader when current state is ParserState::BeginSection /// or ParserState::BeginFunctionBody. /// /// # Examples /// ``` /// # let data = &[0x0, 0x61, 0x73, 0x6d, 0x1, 0x0, 0x0, 0x0, 0x1, 0x84, /// # 0x80, 0x80, 0x80, 0x0, 0x1, 0x60, 0x0, 0x0, 0x3, 0x83, /// # 0x80, 0x80, 0x80, 0x0, 0x2, 0x0, 0x0, 0x6, 0x81, 0x80, /// # 0x80, 0x80, 0x0, 0x0, 0xa, 0x91, 0x80, 0x80, 0x80, 0x0, /// # 0x2, 0x83, 0x80, 0x80, 0x80, 0x0, 0x0, 0x1, 0xb, 0x83, /// # 0x80, 0x80, 0x80, 0x0, 0x0, 0x0, 0xb]; /// use wasmparser::{WasmDecoder, Parser, ParserState}; /// let mut parser = Parser::new(data); /// let mut function_readers = Vec::new(); /// loop { /// match *parser.read() { /// ParserState::Error(_) | /// ParserState::EndWasm => break, /// ParserState::BeginFunctionBody {..} => { /// let reader = parser.create_binary_reader(); /// function_readers.push(reader); /// } /// _ => continue /// } /// } /// for (i, reader) in function_readers.iter_mut().enumerate() { /// println!("Function {}", i); /// while let Ok(ref op) = reader.read_operator() { /// println!(" {:?}", op); /// } /// } /// ``` fn create_binary_reader<'b>(&mut self) -> BinaryReader<'b> where 'a: 'b, { match self.state { ParserState::BeginSection { .. } => self .current_section .as_ref() .expect("section") .get_binary_reader(), ParserState::BeginFunctionBody { .. } | ParserState::FunctionBodyLocals { .. } => self .current_function_body .as_ref() .expect("function body") .get_binary_reader(), _ => panic!("Invalid reader state during get binary reader operation"), } } /// Reads next record from the WebAssembly binary data. It also allows to /// control how parser will treat the next record(s). The method accepts the /// `ParserInput` parameter that allows e.g. to skip section or function /// operators. The methods returns reference to current state of the parser. /// /// # Examples /// ``` /// # let data: &[u8] = &[0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, /// # 0x01, 0x4, 0x01, 0x60, 0x00, 0x00, 0x03, 0x02, 0x01, 0x00, /// # 0x0a, 0x05, 0x01, 0x03, 0x00, 0x01, 0x0b]; /// use wasmparser::WasmDecoder; /// let mut parser = wasmparser::Parser::new(data); /// let mut next_input = wasmparser::ParserInput::Default; /// loop { /// let state = parser.read_with_input(next_input); /// match *state { /// wasmparser::ParserState::EndWasm => break, /// wasmparser::ParserState::BeginWasm { .. } | /// wasmparser::ParserState::EndSection => /// next_input = wasmparser::ParserInput::Default, /// wasmparser::ParserState::BeginSection { ref code, .. } => { /// println!("Found section: {:?}", code); /// next_input = wasmparser::ParserInput::SkipSection; /// }, /// _ => unreachable!() /// } /// } /// ``` fn read_with_input(&mut self, input: ParserInput) -> &ParserState<'a> { self.push_input(input); self.read() } fn last_state(&self) -> &ParserState<'a> { &self.state } }
37.33871
100
0.570698
d5a5225dabd731411cf29238e5173bbbbb4b9a3b
1,388
use ferris_base; mod utils; #[test] fn hot_destroys_melt() { let start = vec![ "............", "..🦀🔥......", "Fe==Me......", "Fe==U La==Ho", ]; let inputs = vec![ ferris_base::core::direction::Direction::RIGHT, ferris_base::core::direction::Direction::RIGHT, ]; let end = vec![ "............", "....🔥......", "Fe==Me......", "Fe==U La==Ho", ]; utils::assert_evolution(start, inputs, end); } #[test] fn hot_does_not_destroy_not_melt() { let start = vec![ "............", "..🦀🔥......", "............", "Fe==U La==Ho", ]; let inputs = vec![ ferris_base::core::direction::Direction::RIGHT, ferris_base::core::direction::Direction::RIGHT, ]; let end = vec![ "............", "....🔥🦀....", "............", "Fe==U La==Ho", ]; utils::assert_evolution(start, inputs, end); } #[test] fn both_hot_and_melt() { let start = vec![ "....La....🔥", "....==......", "🦀Me........", "Fe==U La==Ho", ]; let inputs = vec![ferris_base::core::direction::Direction::RIGHT]; let end = vec![ "....La......", "....==......", "..🦀Me......", "Fe==U La==Ho", ]; utils::assert_evolution(start, inputs, end); }
20.716418
70
0.397695
89579842bf27ad84158254def9b74ef1b8900eed
9,077
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use anyhow::{format_err, Error, Result}; use libra_config::config::{ RoleType, DEFAULT_BATCH_SIZE_LIMIT, DEFAULT_CONTENT_LENGTH_LIMIT, DEFAULT_PAGE_SIZE_LIMIT, }; use libra_crypto::HashValue; use libra_mempool::MempoolClientSender; use libra_types::{ account_address::AccountAddress, account_state_blob::{AccountStateBlob, AccountStateWithProof}, block_info::BlockInfo, chain_id::ChainId, contract_event::ContractEvent, epoch_change::EpochChangeProof, event::EventKey, ledger_info::{LedgerInfo, LedgerInfoWithSignatures}, proof::{ AccumulatorConsistencyProof, AccumulatorRangeProof, SparseMerkleProof, TransactionAccumulatorProof, TransactionInfoWithProof, TransactionListProof, }, transaction::{ Transaction, TransactionInfo, TransactionListWithProof, TransactionWithProof, Version, }, vm_status::KeptVMStatus, }; use std::{ collections::{BTreeMap, HashMap}, net::SocketAddr, sync::Arc, }; use storage_interface::{DbReader, Order, StartupInfo, TreeState}; use tokio::runtime::Runtime; /// Creates JSON RPC server for a Validator node /// Should only be used for unit-tests pub fn test_bootstrap( address: SocketAddr, libra_db: Arc<dyn DbReader>, mp_sender: MempoolClientSender, ) -> Runtime { crate::bootstrap( address, DEFAULT_BATCH_SIZE_LIMIT, DEFAULT_PAGE_SIZE_LIMIT, DEFAULT_CONTENT_LENGTH_LIMIT, libra_db, mp_sender, RoleType::Validator, ChainId::test(), ) } /// Lightweight mock of LibraDB #[derive(Clone)] pub struct MockLibraDB { pub version: u64, pub genesis: HashMap<AccountAddress, AccountStateBlob>, pub all_accounts: HashMap<AccountAddress, AccountStateBlob>, pub all_txns: Vec<(Transaction, KeptVMStatus)>, pub events: Vec<(u64, ContractEvent)>, pub account_state_with_proof: Vec<AccountStateWithProof>, pub timestamps: Vec<u64>, } impl DbReader for MockLibraDB { fn get_latest_account_state( &self, address: AccountAddress, ) -> Result<Option<AccountStateBlob>> { if let Some(blob) = self.genesis.get(&address) { Ok(Some(blob.clone())) } else if let Some(blob) = self.all_accounts.get(&address) { Ok(Some(blob.clone())) } else { Ok(None) } } fn get_latest_ledger_info(&self) -> Result<LedgerInfoWithSignatures> { Ok(LedgerInfoWithSignatures::new( LedgerInfo::new( BlockInfo::new( 0, self.version, HashValue::zero(), HashValue::zero(), self.version, self.get_block_timestamp(self.version).unwrap(), None, ), HashValue::zero(), ), BTreeMap::new(), )) } fn get_txn_by_account( &self, address: AccountAddress, seq_num: u64, _ledger_version: u64, fetch_events: bool, ) -> Result<Option<TransactionWithProof>, Error> { Ok(self .all_txns .iter() .enumerate() .find(|(_, (x, _))| { if let Ok(t) = x.as_signed_user_txn() { t.sender() == address && t.sequence_number() == seq_num } else { false } }) .map(|(v, (x, status))| TransactionWithProof { version: v as u64, transaction: x.clone(), events: if fetch_events { Some( self.events .iter() .filter(|(ev, _)| *ev == v as u64) .map(|(_, e)| e) .cloned() .collect(), ) } else { None }, proof: TransactionInfoWithProof::new( TransactionAccumulatorProof::new(vec![]), TransactionInfo::new( Default::default(), Default::default(), Default::default(), 0, status.clone(), ), ), })) } fn get_transactions( &self, start_version: u64, limit: u64, _ledger_version: u64, fetch_events: bool, ) -> Result<TransactionListWithProof, Error> { let mut transactions = vec![]; let mut txn_infos = vec![]; self.all_txns .iter() .skip(start_version as usize) .take(limit as usize) .for_each(|(t, status)| { transactions.push(t.clone()); txn_infos.push(TransactionInfo::new( Default::default(), Default::default(), Default::default(), 0, status.clone(), )); }); let first_transaction_version = transactions.first().map(|_| start_version); let proof = TransactionListProof::new(AccumulatorRangeProof::new_empty(), txn_infos); Ok(TransactionListWithProof { transactions, events: if fetch_events { Some( (start_version..start_version + limit) .map(|version| { self.events .iter() .filter(|(v, _)| *v == version) .map(|(_, e)| e) .cloned() .collect() }) .collect(), ) } else { None }, first_transaction_version, proof, }) } fn get_events( &self, key: &EventKey, start: u64, _order: Order, limit: u64, ) -> Result<Vec<(u64, ContractEvent)>> { let events = self .events .iter() .filter(|(_, e)| { e.key() == key && start <= e.sequence_number() && e.sequence_number() < start + limit }) .cloned() .collect(); Ok(events) } fn get_state_proof( &self, known_version: u64, ) -> Result<( LedgerInfoWithSignatures, EpochChangeProof, AccumulatorConsistencyProof, )> { let li = self.get_latest_ledger_info()?; let proofs = self.get_state_proof_with_ledger_info(known_version, li.clone())?; Ok(( LedgerInfoWithSignatures::new(li.ledger_info().clone(), BTreeMap::new()), proofs.0, proofs.1, )) } fn get_state_proof_with_ledger_info( &self, _known_version: u64, _ledger_info: LedgerInfoWithSignatures, ) -> Result<(EpochChangeProof, AccumulatorConsistencyProof)> { Ok(( EpochChangeProof::new(vec![], false), AccumulatorConsistencyProof::new(vec![]), )) } fn get_account_state_with_proof( &self, _address: AccountAddress, _version: Version, _ledger_version: Version, ) -> Result<AccountStateWithProof> { Ok(self .account_state_with_proof .get(0) .ok_or_else(|| format_err!("could not find account state"))? .clone()) } fn get_startup_info(&self) -> Result<Option<StartupInfo>> { unimplemented!() } fn get_account_state_with_proof_by_version( &self, address: AccountAddress, _version: u64, ) -> Result<(Option<AccountStateBlob>, SparseMerkleProof)> { Ok(( self.get_latest_account_state(address)?, SparseMerkleProof::new(None, vec![]), )) } fn get_latest_state_root(&self) -> Result<(u64, HashValue)> { unimplemented!() } fn get_latest_tree_state(&self) -> Result<TreeState> { unimplemented!() } fn get_epoch_ending_ledger_infos( &self, _start_epoch: u64, _end_epoch: u64, ) -> Result<EpochChangeProof> { unimplemented!() } fn get_epoch_ending_ledger_info(&self, _: u64) -> Result<LedgerInfoWithSignatures> { unimplemented!() } fn get_block_timestamp(&self, version: u64) -> Result<u64> { Ok(match self.timestamps.get(version as usize) { Some(t) => *t, None => *self.timestamps.last().unwrap(), }) } fn get_accumulator_root_hash(&self, _version: Version) -> Result<HashValue> { Ok(HashValue::zero()) } }
30.156146
94
0.517792
9b97cfc1bec3ec4cc0a933c92014a663f19aa3ca
372
use std::collections::VecDeque; #[cfg_attr(crux, crux_test)] fn crux_test() -> [i32; 5] { let mut v: VecDeque<_> = vec![1, 2, 3, 4, 5].into(); [ v.pop_back().unwrap(), v.pop_back().unwrap(), v.pop_back().unwrap(), v.pop_front().unwrap(), v.pop_back().unwrap(), ] } pub fn main() { println!("{:?}", crux_test()); }
20.666667
56
0.510753
48962ec7903a6474c9bb6e296700e7340f128610
5,134
//! provides functionalities and macro for building html elements macro_rules! declare_tags { ( $( $(#[$attr:meta])* $name:ident; )* ) => { $( doc_comment!{ concat!("Creates an html [",stringify!($name),"](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/",stringify!($name),") element"), $(#[$attr])* #[inline] #[allow(non_snake_case)] pub fn $name<MSG>(attrs: Vec<$crate::Attribute<MSG>>, children: Vec<$crate::Node<MSG>>) -> $crate::Node<MSG> { $crate::html::html_element(stringify!($name), attrs, children) } } )* } } /// declare self closing tags macro_rules! declare_sc_tags { ( $( $(#[$attr:meta])* $name:ident; )* ) => { /// self closing tags pub(crate) mod self_closing{ $( doc_comment!{ concat!("Creates an html [",stringify!($name),"](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/",stringify!($name),") element"), $(#[$attr])* #[inline] #[allow(non_snake_case)] pub fn $name<MSG>(attrs: Vec<$crate::Attribute<MSG>>, children: Vec<$crate::Node<MSG>>) -> $crate::Node<MSG> { $crate::html::html_element_self_closing(stringify!($name), attrs, children, true) } } )* } #[cfg(feature = "with-parser")] /// These are the self closing tags such as `<input/>`, `<br/>`, pub const HTML_SC_TAGS: [&'static str; 16] = [$(stringify!($name),)*]; } } macro_rules! declare_common_tags_and_macro { ($($(#[$attr:meta])* $name:ident;)*) => { pub(crate) mod commons { declare_tags! { $($name;)* } } #[cfg(feature = "with-parser")] /// These are the comonly used html tags such as div, input, buttons,.. etc pub const HTML_TAGS: [&'static str; 98] = [$(stringify!($name),)*]; }; } macro_rules! declare_tags_and_macro { ($($(#[$attr:meta])* $name:ident;)*) => { declare_tags! { $($name;)* } }; } macro_rules! declare_tags_non_common{ ( $( $(#[$attr:meta])* $name:ident; )* ) => { declare_tags!{ $($name;)*} #[cfg(feature = "with-parser")] /// These are html tags which are non commonly used. /// Put together in this collection to avoid import conflicts with the commonly used /// ones. pub const HTML_TAGS_NON_COMMON:[&'static str;1] = [$(stringify!($name),)*]; } } macro_rules! declare_tags_and_macro_non_common{ ( $( $(#[$attr:meta])* $name:ident; )* ) => { declare_tags_and_macro!{ $($name;)*} #[cfg(feature = "with-parser")] /// These are html tags with macro which are non commonly used. /// Put together in this collection to avoid import conflicts with the commonly used /// ones. pub const HTML_TAGS_WITH_MACRO_NON_COMMON:[&'static str;2] = [$(stringify!($name),)*]; } } // Organized in the same order as // https://developer.mozilla.org/en-US/docs/Web/HTML/Element // // Does not include obsolete elements. declare_common_tags_and_macro! { head; body; address; article; aside; footer; header; h1; h2; h3; h4; h5; h6; hgroup; main; nav; section; blockquote; dd; div; dl; dt; figcaption; figure; html; li; ol; p; pre; ul; a; abbr; b; bdi; bdo; cite; code; data; dfn; em; i; kbd; mark; q; rb; rp; rt; rtc; ruby; s; samp; small; span; strong; sub; sup; time; u; var; audio; map; video; iframe; object; picture; canvas; noscript; script; del; ins; caption; colgroup; table; tbody; td; tfoot; th; thead; tr; button; datalist; fieldset; form; label; legend; meter; optgroup; option; output; progress; select; textarea; details; dialog; menu; menuitem; summary; template; } declare_tags_non_common! { style; // conflicts with html::attributes::style, attribute::style > tags::style } // These are non-common tags // which the users need to explicitly import using // html::tags::style, html::tags::html, etc // declare_tags_and_macro_non_common! { title; // conflicts with html::attributes::title , attributes::title > tags::title slot; // conflicts with html::attributes::slot , attrributes::slot > tags::slot } // self closing tags such as `<input/>, `<br/>` declare_sc_tags! { area; base; br; col; command; embed; hr; img; input; keygen; link; meta; param; source; track; wbr; }
20.536
160
0.51305
e25f7619badecd91267baf9868aa8eda8fc2b172
1,064
#![forbid(unsafe_code)] #![deny(clippy::all)] pub type Map<K, V> = schemars::Map<K, V>; pub type MapEntry<'a, K, V> = schemars::MapEntry<'a, K, V>; pub mod merge; pub mod openapi3; /// Re-export the current version of `Schemars` used by `Okapi`. pub use schemars; /// Macro to crate an `okapi::Map` with a number of key-value pairs in it. /// /// # Examples /// /// ```rust /// use okapi::Map; /// use okapi::map; /// /// let my_map = map!{ /// "user:read".to_owned() => "Ability to read user data".to_owned(), /// "user:write".to_owned() => "Ability to write user data".to_owned(), /// }; /// /// let mut control = Map::new(); /// control.insert("user:read".to_owned(),"Ability to read user data".to_owned()); /// control.insert("user:write".to_owned(),"Ability to write user data".to_owned()); /// /// assert_eq!(my_map, control); /// ``` #[macro_export] macro_rules! map { ($($key:expr => $val:expr),* $(,)*) => ({ #[allow(unused_mut)] let mut map = okapi::Map::new(); $( map.insert($key, $val); )* map }); }
25.95122
84
0.581767
33d9fc8f4001f3f71cf5b6cc877500e16e11211a
4,662
//! A crate containing types useful for working with Wasm modules on the //! Internet Computer. mod errors; pub use errors::{ParityWasmError, WasmEngineError, WasmInstrumentationError, WasmValidationError}; use ic_utils::byte_slice_fmt::truncate_and_format; use std::{ fmt, path::{Path, PathBuf}, sync::Arc, }; /// A newtype for /// [BinaryEncoded](https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md) /// Wasm modules used for execution. #[derive(Clone)] pub struct BinaryEncodedWasm(Arc<Vec<u8>>); impl BinaryEncodedWasm { pub fn new(wasm: Vec<u8>) -> Self { Self::new_shared(Arc::new(wasm)) } pub fn new_shared(wasm: Arc<Vec<u8>>) -> Self { debug_assert!(wasm.starts_with(b"\x00asm"), "Invalid binary encoded wasm"); Self(wasm) } pub fn as_slice(&self) -> &[u8] { self.0.as_slice() } } /// Canister module stored by the replica. /// Currently, we support two kinds of modules: /// * Raw Wasm modules (magic number \0asm) /// * Gzip-compressed Wasm modules (magic number \1f\8b\08) // We don't derive `Serialize` and `Deserialize` because this is a binary that is serialized by // writing it to a file when creating checkpoints. #[derive(Clone)] pub struct CanisterModule { // The Wasm binary. module: ModuleStorage, // The Sha256 hash of the binary. module_hash: [u8; 32], } impl CanisterModule { pub fn new(bytes: Vec<u8>) -> Self { let module = ModuleStorage::Memory(Arc::new(bytes)); let module_hash = ic_crypto_sha::Sha256::hash(module.as_slice()); Self { module, module_hash, } } pub fn new_from_file(path: PathBuf) -> std::io::Result<Self> { let module = ModuleStorage::mmap_file(path)?; let module_hash = ic_crypto_sha::Sha256::hash(module.as_slice()); Ok(Self { module, module_hash, }) } /// If this module is backed by a file, return the path to that file. pub fn file(&self) -> Option<&Path> { match &self.module { ModuleStorage::Memory(_) => None, ModuleStorage::File(path, _) => Some(path), } } pub fn as_slice(&self) -> &[u8] { self.module.as_slice() } pub fn len(&self) -> usize { self.module.len() } pub fn is_empty(&self) -> bool { self.module.len() == 0 } pub fn to_shared_vec(&self) -> Arc<Vec<u8>> { match &self.module { ModuleStorage::Memory(shared) => Arc::clone(shared), ModuleStorage::File(_, _) => Arc::new(self.as_slice().to_vec()), } } /// Returns the Sha256 hash of this Wasm module. pub fn module_hash(&self) -> [u8; 32] { self.module_hash } } impl fmt::Debug for CanisterModule { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_fmt(format_args!( "CanisterModule{{{}}}", truncate_and_format(self.as_slice(), 40_usize) )) } } impl PartialEq for CanisterModule { fn eq(&self, other: &Self) -> bool { self.module_hash() == other.module_hash() } } impl Eq for CanisterModule {} impl std::hash::Hash for CanisterModule { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.as_slice().hash(state) } } // We introduce another enum instead of making `BinaryEncodedWasm` an enum to // keep constructors private. We want `BinaryEncodedWasm` to be visible, but not // its structure. #[derive(Clone)] enum ModuleStorage { Memory(Arc<Vec<u8>>), File(PathBuf, Arc<ic_sys::mmap::ScopedMmap>), } impl ModuleStorage { fn mmap_file(path: PathBuf) -> std::io::Result<Self> { use std::io; let f = std::fs::File::open(&path)?; let len = f.metadata()?.len(); if len == 0 { return Err(io::Error::new( io::ErrorKind::InvalidData, format!("{}: Wasm file must not be empty", path.display()), )); } match ic_sys::mmap::ScopedMmap::from_readonly_file(&f, len as usize) { Ok(mmap) => Ok(Self::File(path, Arc::new(mmap))), Err(_) => Err(io::Error::last_os_error()), } } fn as_slice(&self) -> &[u8] { match &self { Self::Memory(arc) => arc.as_slice(), // This is safe because the file is read-only. Self::File(_, mmap) => mmap.as_slice(), } } fn len(&self) -> usize { match &self { ModuleStorage::Memory(arc) => arc.len(), ModuleStorage::File(_, mmap) => mmap.len(), } } }
28.254545
98
0.584084
76f2253d1a2810eeab4f36d3b1f638ca8cb26278
7,432
#![cfg_attr(not(feature = "std"), no_std)] #![allow(dead_code)] #![allow(unused_variables)] use crate as pallet_deip_dao; use super::{*, Event as RawEvent, Call as RawCall}; use sp_std::prelude::*; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<TestRuntime>; type Block = frame_system::mocking::MockBlock<TestRuntime>; frame_support::construct_runtime!( pub enum TestRuntime where Block = Block, NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event<T>}, DeipDao: pallet_deip_dao::{Module, Call, Storage, Event<T>, Config}, } ); frame_support::parameter_types! { pub const BlockHashCount: u64 = 250; pub BlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights::simple_max(1024); } impl frame_system::Config for TestRuntime { type BaseCallFilter = (); type BlockWeights = (); type BlockLength = (); type Origin = Origin; type Call = Call; type Index = u64; type BlockNumber = u64; type Hash = sp_core::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = sp_runtime::traits::IdentityLookup<Self::AccountId>; type Header = sp_runtime::testing::Header; type Event = Event; type BlockHashCount = BlockHashCount; type DbWeight = (); type Version = (); type PalletInfo = PalletInfo; type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); } impl crate::Config for TestRuntime { type Event = Event; type Call = Call; } pub struct ExtBuilder; impl ExtBuilder { pub fn build() -> sp_io::TestExternalities { let storage = frame_system::GenesisConfig::default().build_storage::<TestRuntime>().unwrap(); sp_io::TestExternalities::from(storage) } } fn with_test_ext<R>(t: impl FnOnce() -> R) -> R { ExtBuilder::build().execute_with(t) } use frame_support::{assert_noop, assert_ok}; use crate::dao::*; use sp_std::str::FromStr; use frame_system::RawOrigin; fn last_event() -> Event { frame_system::Module::<TestRuntime>::events().pop().map(|e| e.event).expect("Event expected") } fn expect_event<E: Into<Event>>(e: E) { assert_eq!(last_event(), e.into()); } fn plain_key_source(who: u64) -> InputAuthority<u64> { InputAuthority { signatories: vec![who], threshold: 0 } } #[test] #[ignore] fn fake_test_example() { with_test_ext(|| { // ...test conditions... }) } #[test] fn dao_create() { with_test_ext(|| { System::set_block_number(1); let who = 1; let id = DaoId::from_slice("test_dao\0\0\0\0\0\0\0\0\0\0\0\0".as_bytes()); assert_ok!(DeipDao::create(Origin::signed(who), id, plain_key_source(who))); assert!(matches!( last_event(), Event::pallet_deip_dao(RawEvent::DaoCreate(dao)) if dao.dao_key() == &who && dao.id() == &id )); }) } #[test] fn dao_create_exists() { with_test_ext(|| { let who = 1; let name = DaoId::from_slice("test_dao\0\0\0\0\0\0\0\0\0\0\0\0".as_bytes()); DeipDao::create(Origin::signed(who), name, plain_key_source(who)).expect("create OK"); assert_noop!( DeipDao::create(Origin::signed(who), name, plain_key_source(who)), Error::<TestRuntime>::Exists, ); }) } #[test] fn dao_transfer_ownership() { with_test_ext(|| { System::set_block_number(1); let who = 1; let id = DaoId::from_slice("test_dao\0\0\0\0\0\0\0\0\0\0\0\0".as_bytes()); DeipDao::create(Origin::signed(who), id, plain_key_source(who)).expect("create OK"); let transfer_to = 2; assert_ok!(DeipDao::transfer_ownership(Origin::signed(who), id, transfer_to, plain_key_source(transfer_to))); assert!(matches!( last_event(), Event::pallet_deip_dao(RawEvent::DaoTransferOwnership(dao)) if dao.dao_key() == &transfer_to && dao.id() == &id )); }) } #[test] fn dao_transfer_ownership_not_found() { with_test_ext(|| { System::set_block_number(1); let who = 1; let id = DaoId::from_slice("test_dao\0\0\0\0\0\0\0\0\0\0\0\0".as_bytes()); let transfer_to = 2; assert_noop!( DeipDao::transfer_ownership(Origin::signed(who), id, transfer_to, plain_key_source(who)), Error::<TestRuntime>::NotFound, ); }) } #[test] fn dao_transfer_ownership_forbidden() { with_test_ext(|| { System::set_block_number(1); let owner = 1; let id = DaoId::from_slice("test_dao\0\0\0\0\0\0\0\0\0\0\0\0".as_bytes()); DeipDao::create(Origin::signed(owner), id, plain_key_source(owner)).expect("create OK"); let transfer_to = 2; let other = 3; assert_noop!( DeipDao::transfer_ownership(Origin::signed(transfer_to), id, transfer_to, plain_key_source(transfer_to)), Error::<TestRuntime>::Forbidden, ); assert_noop!( DeipDao::transfer_ownership(Origin::signed(other), id, transfer_to, plain_key_source(transfer_to)), Error::<TestRuntime>::Forbidden, ); }) } #[test] fn dao_on_behalf() { with_test_ext(|| { System::set_block_number(1); let who = 1; let id = DaoId::from_slice("test_dao\0\0\0\0\0\0\0\0\0\0\0\0".as_bytes()); DeipDao::create( Origin::signed(who), id, plain_key_source(who) ).expect("create OK"); let transfer_to = 2; assert_ok!( DeipDao::on_behalf( Origin::signed(who), id, Box::new(Call::DeipDao(RawCall::transfer_ownership( id, transfer_to, plain_key_source(transfer_to) ))) ) ); }) } #[test] fn dao_on_behalf_not_found() { with_test_ext(|| { System::set_block_number(1); let who = 1; let id = DaoId::from_slice("test_dao\0\0\0\0\0\0\0\0\0\0\0\0".as_bytes()); let transfer_to = 2; assert_noop!( DeipDao::on_behalf( Origin::signed(who), id, Box::new(Call::DeipDao(RawCall::transfer_ownership( id, transfer_to, plain_key_source(transfer_to) ))) ), Error::<TestRuntime>::NotFound, ); }) } #[test] fn dao_on_behalf_forbidden() { with_test_ext(|| { System::set_block_number(1); let who = 1; let name = DaoId::from_slice("test_dao\0\0\0\0\0\0\0\0\0\0\0\0".as_bytes()); DeipDao::create( Origin::signed(who), name, plain_key_source(who) ).expect("create OK"); let transfer_to = 2; assert_noop!( DeipDao::on_behalf( Origin::signed(transfer_to), name, Box::new(Call::DeipDao(RawCall::transfer_ownership( name, transfer_to, plain_key_source(transfer_to) ))) ), Error::<TestRuntime>::Forbidden, ); }) }
29.609562
117
0.578445
5dd28a0cb6766c15894ca2a091eb6a3546cbd881
1,055
use frame::Frame; use option_setter::OptionSetter; use session::{OutstandingReceipt, ReceiptRequest, Session}; pub struct MessageBuilder<'a> { pub session: &'a mut Session, pub frame: Frame, pub receipt_request: Option<ReceiptRequest>, } impl<'a> MessageBuilder<'a> { pub fn new(session: &'a mut Session, frame: Frame) -> Self { MessageBuilder { session: session, frame: frame, receipt_request: None, } } #[allow(dead_code)] pub fn send(self) { if self.receipt_request.is_some() { let request = self.receipt_request.unwrap(); self.session .state .outstanding_receipts .insert(request.id, OutstandingReceipt::new(self.frame.clone())); } self.session.send_frame(self.frame) } #[allow(dead_code)] pub fn with<T>(self, option_setter: T) -> MessageBuilder<'a> where T: OptionSetter<MessageBuilder<'a>>, { option_setter.set_option(self) } }
26.375
81
0.593365
33ed31cfe21d898fcb8d5f389d87fad0cc73a64b
4,091
// Functionality that is shared between the cxxbridge macro and the cmd. pub mod atom; mod attrs; pub mod check; mod derive; mod discriminant; mod doc; pub mod error; pub mod file; pub mod ident; mod impls; mod improper; pub mod mangle; mod names; pub mod namespace; mod parse; pub mod qualified; pub mod report; pub mod set; pub mod symbol; mod tokens; mod toposort; pub mod types; use self::discriminant::Discriminant; use self::namespace::Namespace; use self::parse::kw; use self::symbol::Symbol; use proc_macro2::{Ident, Span}; use syn::punctuated::Punctuated; use syn::token::{Brace, Bracket, Paren}; use syn::{Expr, Lifetime, Token, Type as RustType}; pub use self::atom::Atom; pub use self::derive::Derive; pub use self::doc::Doc; pub use self::parse::parse_items; pub use self::types::Types; pub enum Api { Include(Include), Struct(Struct), Enum(Enum), CxxType(ExternType), CxxFunction(ExternFn), RustType(ExternType), RustFunction(ExternFn), TypeAlias(TypeAlias), Impl(Impl), } pub struct Include { pub path: String, pub kind: IncludeKind, pub begin_span: Span, pub end_span: Span, } /// Whether to emit `#include "path"` or `#include <path>`. #[derive(Copy, Clone, PartialEq, Debug)] pub enum IncludeKind { /// `#include "quoted/path/to"` Quoted, /// `#include <bracketed/path/to>` Bracketed, } pub struct ExternType { pub doc: Doc, pub type_token: Token![type], pub name: Pair, pub semi_token: Token![;], pub trusted: bool, } pub struct Struct { pub doc: Doc, pub derives: Vec<Derive>, pub struct_token: Token![struct], pub name: Pair, pub brace_token: Brace, pub fields: Vec<Var>, } pub struct Enum { pub doc: Doc, pub enum_token: Token![enum], pub name: Pair, pub brace_token: Brace, pub variants: Vec<Variant>, pub repr: Atom, } pub struct ExternFn { pub lang: Lang, pub doc: Doc, pub name: Pair, pub sig: Signature, pub semi_token: Token![;], } pub struct TypeAlias { pub doc: Doc, pub type_token: Token![type], pub name: Pair, pub eq_token: Token![=], pub ty: RustType, pub semi_token: Token![;], } pub struct Impl { pub impl_token: Token![impl], pub ty: Type, pub brace_token: Brace, } pub struct Signature { pub unsafety: Option<Token![unsafe]>, pub fn_token: Token![fn], pub receiver: Option<Receiver>, pub args: Punctuated<Var, Token![,]>, pub ret: Option<Type>, pub throws: bool, pub paren_token: Paren, pub throws_tokens: Option<(kw::Result, Token![<], Token![>])>, } #[derive(Eq, PartialEq, Hash)] pub struct Var { pub ident: Ident, pub ty: Type, } pub struct Receiver { pub ampersand: Token![&], pub lifetime: Option<Lifetime>, pub mutability: Option<Token![mut]>, pub var: Token![self], pub ty: ResolvableName, pub shorthand: bool, } pub struct Variant { pub ident: Ident, pub discriminant: Discriminant, pub expr: Option<Expr>, } pub enum Type { Ident(ResolvableName), RustBox(Box<Ty1>), RustVec(Box<Ty1>), UniquePtr(Box<Ty1>), Ref(Box<Ref>), Str(Box<Ref>), CxxVector(Box<Ty1>), Fn(Box<Signature>), Void(Span), Slice(Box<Slice>), SliceRefU8(Box<Ref>), } pub struct Ty1 { pub name: Ident, pub langle: Token![<], pub inner: Type, pub rangle: Token![>], } pub struct Ref { pub ampersand: Token![&], pub lifetime: Option<Lifetime>, pub mutability: Option<Token![mut]>, pub inner: Type, } pub struct Slice { pub bracket: Bracket, pub inner: Type, } #[derive(Copy, Clone, PartialEq)] pub enum Lang { Cxx, Rust, } // An association of a defined Rust name with a fully resolved, namespace // qualified C++ name. #[derive(Clone)] pub struct Pair { pub namespace: Namespace, pub cxx: Ident, pub rust: Ident, } // Wrapper for a type which needs to be resolved before it can be printed in // C++. #[derive(Clone, PartialEq, Hash)] pub struct ResolvableName { pub rust: Ident, }
20.053922
76
0.646297
1caa993cb957ffa805d64b538f271b99d1fb6486
7,207
mod utils; use crate::utils::{ clone_out_test, copy_workspace_test, execute_command, execute_command_for_pkg, get_toml, }; use assert_cmd::Command; #[test] fn remove_existing_dependency() { let (_tmpdir, manifest) = clone_out_test("tests/fixtures/rm/Cargo.toml.sample"); let toml = get_toml(&manifest); assert!(!toml["dependencies"]["docopt"].is_none()); execute_command(&["rm", "docopt"], &manifest); let toml = get_toml(&manifest); assert!(toml["dependencies"]["docopt"].is_none()); } #[test] fn remove_multiple_existing_dependencies() { let (_tmpdir, manifest) = clone_out_test("tests/fixtures/rm/Cargo.toml.sample"); let toml = get_toml(&manifest); assert!(!toml["dependencies"]["docopt"].is_none()); assert!(!toml["dependencies"]["semver"].is_none()); execute_command(&["rm", "docopt", "semver"], &manifest); let toml = get_toml(&manifest); assert!(toml["dependencies"]["docopt"].is_none()); assert!(toml["dependencies"]["semver"].is_none()); } #[test] fn remove_existing_dependency_from_specific_section() { let (_tmpdir, manifest) = clone_out_test("tests/fixtures/rm/Cargo.toml.sample"); // Test removing dev dependency. let toml = get_toml(&manifest); assert!(!toml["dev-dependencies"]["regex"].is_none()); execute_command(&["rm", "--dev", "regex"], &manifest); let toml = get_toml(&manifest); assert!(toml["dev-dependencies"]["regex"].is_none()); // Test removing build dependency. let toml = get_toml(&manifest); assert!(!toml["build-dependencies"]["semver"].is_none()); execute_command(&["rm", "--build", "semver"], &manifest); let toml = get_toml(&manifest); assert!(toml["build-dependencies"].is_none()); } #[test] fn remove_multiple_existing_dependencies_from_specific_section() { let (_tmpdir, manifest) = clone_out_test("tests/fixtures/rm/Cargo.toml.sample"); // Test removing dev dependency. let toml = get_toml(&manifest); assert!(!toml["dev-dependencies"]["regex"].is_none()); assert!(!toml["dev-dependencies"]["serde"].is_none()); execute_command(&["rm", "--dev", "regex", "serde"], &manifest); let toml = get_toml(&manifest); assert!(toml["dev-dependencies"].is_none()); } #[test] fn remove_section_after_removed_last_dependency() { let (_tmpdir, manifest) = clone_out_test("tests/fixtures/rm/Cargo.toml.sample"); let toml = get_toml(&manifest); assert!(!toml["dev-dependencies"]["regex"].is_none()); assert_eq!(toml["dev-dependencies"].as_table().unwrap().len(), 2); execute_command(&["rm", "--dev", "regex", "serde"], &manifest); let toml = get_toml(&manifest); assert!(toml["dev-dependencies"].is_none()); } // https://github.com/killercup/cargo-edit/issues/32 #[test] fn issue_32() { let (_tmpdir, manifest) = clone_out_test("tests/fixtures/rm/Cargo.toml.sample"); let toml = get_toml(&manifest); assert!(toml["dependencies"]["foo"].is_none()); execute_command(&["add", "[email protected]"], &manifest); execute_command(&["add", "[email protected]"], &manifest); let toml = get_toml(&manifest); assert!(!toml["dependencies"]["foo"].is_none()); assert!(!toml["dependencies"]["bar"].is_none()); execute_command(&["rm", "foo"], &manifest); execute_command(&["rm", "bar"], &manifest); let toml = get_toml(&manifest); assert!(toml["dependencies"]["foo"].is_none()); assert!(toml["dependencies"]["bar"].is_none()); } #[test] fn invalid_dependency() { let (_tmpdir, manifest) = clone_out_test("tests/fixtures/rm/Cargo.toml.sample"); Command::cargo_bin("cargo-rm") .expect("can find bin") .args(&[ "rm", "invalid_dependency_name", &format!("--manifest-path={}", manifest), ]) .assert() .code(1) .stderr(predicates::str::contains( "Command failed due to unhandled error: The dependency `invalid_dependency_name` could \ not be found in `dependencies`.", )); } #[test] fn invalid_section() { let (_tmpdir, manifest) = clone_out_test("tests/fixtures/rm/Cargo.toml.sample"); execute_command(&["rm", "semver", "--build"], &manifest); Command::cargo_bin("cargo-rm") .expect("can find bin") .args(&[ "rm", "semver", "--build", &format!("--manifest-path={}", manifest), ]) .assert() .code(1) .stderr(predicates::str::contains( "The table `build-dependencies` could not be found.", )); } #[test] fn invalid_dependency_in_section() { let (_tmpdir, manifest) = clone_out_test("tests/fixtures/rm/Cargo.toml.sample"); Command::cargo_bin("cargo-rm") .expect("can find bin") .args(&[ "rm", "semver", "regex", "--dev", &format!("--manifest-path={}", manifest), ]) .assert() .code(1) .stderr(predicates::str::contains( "Command failed due to unhandled error: The dependency `semver` could not be found in \ `dev-dependencies`.", )); } #[test] fn no_argument() { Command::cargo_bin("cargo-rm") .expect("can find bin") .args(&["rm"]) .assert() .code(1) .stderr( r"error: The following required arguments were not provided: <crates>... USAGE: cargo rm [FLAGS] [OPTIONS] <crates>... For more information try --help ", ); } #[test] fn unknown_flags() { Command::cargo_bin("cargo-rm") .expect("can find bin") .args(&["rm", "foo", "--flag"]) .assert() .code(1) .stderr( r"error: Found argument '--flag' which wasn't expected, or isn't valid in this context USAGE: cargo rm [FLAGS] [OPTIONS] <crates>... For more information try --help ", ); } #[test] fn rm_prints_message() { let (_tmpdir, manifest) = clone_out_test("tests/fixtures/rm/Cargo.toml.sample"); Command::cargo_bin("cargo-rm") .expect("can find bin") .args(&["rm", "semver", &format!("--manifest-path={}", manifest)]) .assert() .success() .stdout(" Removing semver from dependencies\n"); } #[test] fn rm_prints_messages_for_multiple() { let (_tmpdir, manifest) = clone_out_test("tests/fixtures/rm/Cargo.toml.sample"); Command::cargo_bin("cargo-rm") .expect("can find bin") .args(&[ "rm", "semver", "docopt", &format!("--manifest-path={}", manifest), ]) .assert() .success() .stdout(" Removing semver from dependencies\n Removing docopt from dependencies\n"); } #[test] fn rm_dependency_from_workspace_member() { let (tmpdir, _root_manifest, workspace_manifests) = copy_workspace_test(); execute_command_for_pkg(&["rm", "libc"], "one", &tmpdir); let one = workspace_manifests .iter() .map(|manifest| get_toml(manifest)) .find(|manifest| manifest["package"]["name"].as_str() == Some("one")) .expect("Couldn't find workspace member `one'"); assert!(one["dependencies"]["libc"].as_str().is_none()); }
30.029167
99
0.6058
bb8b1f80c4702342c3328c390a7315530b0200a4
34,976
use super::texture::Texture; use crate::{ colorspace::*, impl_render_resource_bytes, renderer::{RenderResource, RenderResourceType}, }; use bevy_asset::Handle; use bevy_core::Bytes; use bevy_math::{Vec3, Vec4}; use bevy_reflect::{Reflect, ReflectDeserialize}; use serde::{Deserialize, Serialize}; use std::ops::{Add, AddAssign, Mul, MulAssign}; #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Reflect)] #[reflect(PartialEq, Serialize, Deserialize)] pub enum Color { /// sRGBA color Rgba { /// Red component. [0.0, 1.0] red: f32, /// Green component. [0.0, 1.0] green: f32, /// Blue component. [0.0, 1.0] blue: f32, /// Alpha component. [0.0, 1.0] alpha: f32, }, /// RGBA color in the Linear sRGB colorspace (often colloquially referred to as "linear", /// "RGB", or "linear RGB"). RgbaLinear { /// Red component. [0.0, 1.0] red: f32, /// Green component. [0.0, 1.0] green: f32, /// Blue component. [0.0, 1.0] blue: f32, /// Alpha component. [0.0, 1.0] alpha: f32, }, /// HSL (hue, saturation, lightness) color with an alpha channel Hsla { /// Hue component. [0.0, 360.0] hue: f32, /// Saturation component. [0.0, 1.0] saturation: f32, /// Lightness component. [0.0, 1.0] lightness: f32, /// Alpha component. [0.0, 1.0] alpha: f32, }, } impl Color { pub const ALICE_BLUE: Color = Color::rgb(0.94, 0.97, 1.0); pub const ANTIQUE_WHITE: Color = Color::rgb(0.98, 0.92, 0.84); pub const AQUAMARINE: Color = Color::rgb(0.49, 1.0, 0.83); pub const AZURE: Color = Color::rgb(0.94, 1.0, 1.0); pub const BEIGE: Color = Color::rgb(0.96, 0.96, 0.86); pub const BISQUE: Color = Color::rgb(1.0, 0.89, 0.77); pub const BLACK: Color = Color::rgb(0.0, 0.0, 0.0); pub const BLUE: Color = Color::rgb(0.0, 0.0, 1.0); pub const CRIMSON: Color = Color::rgb(0.86, 0.08, 0.24); pub const CYAN: Color = Color::rgb(0.0, 1.0, 1.0); pub const DARK_GRAY: Color = Color::rgb(0.25, 0.25, 0.25); pub const DARK_GREEN: Color = Color::rgb(0.0, 0.5, 0.0); pub const FUCHSIA: Color = Color::rgb(1.0, 0.0, 1.0); pub const GOLD: Color = Color::rgb(1.0, 0.84, 0.0); pub const GRAY: Color = Color::rgb(0.5, 0.5, 0.5); pub const GREEN: Color = Color::rgb(0.0, 1.0, 0.0); pub const INDIGO: Color = Color::rgb(0.29, 0.0, 0.51); pub const LIME_GREEN: Color = Color::rgb(0.2, 0.8, 0.2); pub const MAROON: Color = Color::rgb(0.5, 0.0, 0.0); pub const MIDNIGHT_BLUE: Color = Color::rgb(0.1, 0.1, 0.44); pub const NAVY: Color = Color::rgb(0.0, 0.0, 0.5); pub const NONE: Color = Color::rgba(0.0, 0.0, 0.0, 0.0); pub const OLIVE: Color = Color::rgb(0.5, 0.5, 0.0); pub const ORANGE: Color = Color::rgb(1.0, 0.65, 0.0); pub const ORANGE_RED: Color = Color::rgb(1.0, 0.27, 0.0); pub const PINK: Color = Color::rgb(1.0, 0.08, 0.58); pub const PURPLE: Color = Color::rgb(0.5, 0.0, 0.5); pub const RED: Color = Color::rgb(1.0, 0.0, 0.0); pub const SALMON: Color = Color::rgb(0.98, 0.5, 0.45); pub const SEA_GREEN: Color = Color::rgb(0.18, 0.55, 0.34); pub const SILVER: Color = Color::rgb(0.75, 0.75, 0.75); pub const TEAL: Color = Color::rgb(0.0, 0.5, 0.5); pub const TOMATO: Color = Color::rgb(1.0, 0.39, 0.28); pub const TURQUOISE: Color = Color::rgb(0.25, 0.88, 0.82); pub const VIOLET: Color = Color::rgb(0.93, 0.51, 0.93); pub const WHITE: Color = Color::rgb(1.0, 1.0, 1.0); pub const YELLOW: Color = Color::rgb(1.0, 1.0, 0.0); pub const YELLOW_GREEN: Color = Color::rgb(0.6, 0.8, 0.2); /// New `Color` from sRGB colorspace. pub const fn rgb(r: f32, g: f32, b: f32) -> Color { Color::Rgba { red: r, green: g, blue: b, alpha: 1.0, } } /// New `Color` from sRGB colorspace. pub const fn rgba(r: f32, g: f32, b: f32, a: f32) -> Color { Color::Rgba { red: r, green: g, blue: b, alpha: a, } } /// New `Color` from linear RGB colorspace. pub const fn rgb_linear(r: f32, g: f32, b: f32) -> Color { Color::RgbaLinear { red: r, green: g, blue: b, alpha: 1.0, } } /// New `Color` from linear RGB colorspace. pub const fn rgba_linear(r: f32, g: f32, b: f32, a: f32) -> Color { Color::RgbaLinear { red: r, green: g, blue: b, alpha: a, } } /// New `Color` with HSL representation in sRGB colorspace. pub const fn hsl(hue: f32, saturation: f32, lightness: f32) -> Color { Color::Hsla { hue, saturation, lightness, alpha: 1.0, } } /// New `Color` with HSL representation in sRGB colorspace. pub const fn hsla(hue: f32, saturation: f32, lightness: f32, alpha: f32) -> Color { Color::Hsla { hue, saturation, lightness, alpha, } } /// New `Color` from sRGB colorspace. pub fn hex<T: AsRef<str>>(hex: T) -> Result<Color, HexColorError> { let hex = hex.as_ref(); // RGB if hex.len() == 3 { let mut data = [0; 6]; for (i, ch) in hex.chars().enumerate() { data[i * 2] = ch as u8; data[i * 2 + 1] = ch as u8; } return decode_rgb(&data); } // RGBA if hex.len() == 4 { let mut data = [0; 8]; for (i, ch) in hex.chars().enumerate() { data[i * 2] = ch as u8; data[i * 2 + 1] = ch as u8; } return decode_rgba(&data); } // RRGGBB if hex.len() == 6 { return decode_rgb(hex.as_bytes()); } // RRGGBBAA if hex.len() == 8 { return decode_rgba(hex.as_bytes()); } Err(HexColorError::Length) } /// New `Color` from sRGB colorspace. pub fn rgb_u8(r: u8, g: u8, b: u8) -> Color { Color::rgba_u8(r, g, b, u8::MAX) } // Float operations in const fn are not stable yet // see https://github.com/rust-lang/rust/issues/57241 /// New `Color` from sRGB colorspace. pub fn rgba_u8(r: u8, g: u8, b: u8, a: u8) -> Color { Color::rgba( r as f32 / u8::MAX as f32, g as f32 / u8::MAX as f32, b as f32 / u8::MAX as f32, a as f32 / u8::MAX as f32, ) } /// Get red in sRGB colorspace. pub fn r(&self) -> f32 { match self.as_rgba() { Color::Rgba { red, .. } => red, _ => unreachable!(), } } /// Get green in sRGB colorspace. pub fn g(&self) -> f32 { match self.as_rgba() { Color::Rgba { green, .. } => green, _ => unreachable!(), } } /// Get blue in sRGB colorspace. pub fn b(&self) -> f32 { match self.as_rgba() { Color::Rgba { blue, .. } => blue, _ => unreachable!(), } } /// Set red in sRGB colorspace. pub fn set_r(&mut self, r: f32) -> &mut Self { *self = self.as_rgba(); match self { Color::Rgba { red, .. } => *red = r, _ => unreachable!(), } self } /// Set green in sRGB colorspace. pub fn set_g(&mut self, g: f32) -> &mut Self { *self = self.as_rgba(); match self { Color::Rgba { green, .. } => *green = g, _ => unreachable!(), } self } /// Set blue in sRGB colorspace. pub fn set_b(&mut self, b: f32) -> &mut Self { *self = self.as_rgba(); match self { Color::Rgba { blue, .. } => *blue = b, _ => unreachable!(), } self } /// Get alpha. pub fn a(&self) -> f32 { match self { Color::Rgba { alpha, .. } | Color::RgbaLinear { alpha, .. } | Color::Hsla { alpha, .. } => *alpha, } } /// Set alpha. pub fn set_a(&mut self, a: f32) -> &mut Self { match self { Color::Rgba { alpha, .. } | Color::RgbaLinear { alpha, .. } | Color::Hsla { alpha, .. } => { *alpha = a; } } self } /// Converts a `Color` to variant `Color::Rgba` pub fn as_rgba(self: &Color) -> Color { match self { Color::Rgba { .. } => *self, Color::RgbaLinear { red, green, blue, alpha, } => Color::Rgba { red: red.linear_to_nonlinear_srgb(), green: green.linear_to_nonlinear_srgb(), blue: blue.linear_to_nonlinear_srgb(), alpha: *alpha, }, Color::Hsla { hue, saturation, lightness, alpha, } => { let [red, green, blue] = HslRepresentation::hsl_to_nonlinear_srgb(*hue, *saturation, *lightness); Color::Rgba { red, green, blue, alpha: *alpha, } } } } /// Converts a `Color` to variant `Color::RgbaLinear` pub fn as_rgba_linear(self: &Color) -> Color { match self { Color::Rgba { red, green, blue, alpha, } => Color::Rgba { red: red.nonlinear_to_linear_srgb(), green: green.nonlinear_to_linear_srgb(), blue: blue.nonlinear_to_linear_srgb(), alpha: *alpha, }, Color::RgbaLinear { .. } => *self, Color::Hsla { hue, saturation, lightness, alpha, } => { let [red, green, blue] = HslRepresentation::hsl_to_nonlinear_srgb(*hue, *saturation, *lightness); Color::RgbaLinear { red: red.nonlinear_to_linear_srgb(), green: green.nonlinear_to_linear_srgb(), blue: blue.nonlinear_to_linear_srgb(), alpha: *alpha, } } } } /// Converts a `Color` to variant `Color::Hsla` pub fn as_hsla(self: &Color) -> Color { match self { Color::Rgba { red, green, blue, alpha, } => { let (hue, saturation, lightness) = HslRepresentation::nonlinear_srgb_to_hsl([*red, *green, *blue]); Color::Hsla { hue, saturation, lightness, alpha: *alpha, } } Color::RgbaLinear { red, green, blue, alpha, } => { let (hue, saturation, lightness) = HslRepresentation::nonlinear_srgb_to_hsl([ red.linear_to_nonlinear_srgb(), green.linear_to_nonlinear_srgb(), blue.linear_to_nonlinear_srgb(), ]); Color::Hsla { hue, saturation, lightness, alpha: *alpha, } } Color::Hsla { .. } => *self, } } /// Converts a `Color` to a `[f32; 4]` from sRBG colorspace pub fn as_rgba_f32(self: Color) -> [f32; 4] { match self { Color::Rgba { red, green, blue, alpha, } => [red, green, blue, alpha], Color::RgbaLinear { red, green, blue, alpha, } => [ red.linear_to_nonlinear_srgb(), green.linear_to_nonlinear_srgb(), blue.linear_to_nonlinear_srgb(), alpha, ], Color::Hsla { hue, saturation, lightness, alpha, } => { let [red, green, blue] = HslRepresentation::hsl_to_nonlinear_srgb(hue, saturation, lightness); [red, green, blue, alpha] } } } /// Converts a `Color` to a `[f32; 4]` from linear RBG colorspace pub fn as_linear_rgba_f32(self: Color) -> [f32; 4] { match self { Color::Rgba { red, green, blue, alpha, } => [ red.nonlinear_to_linear_srgb(), green.nonlinear_to_linear_srgb(), blue.nonlinear_to_linear_srgb(), alpha, ], Color::RgbaLinear { red, green, blue, alpha, } => [red, green, blue, alpha], Color::Hsla { hue, saturation, lightness, alpha, } => { let [red, green, blue] = HslRepresentation::hsl_to_nonlinear_srgb(hue, saturation, lightness); [ red.nonlinear_to_linear_srgb(), green.nonlinear_to_linear_srgb(), blue.nonlinear_to_linear_srgb(), alpha, ] } } } /// Converts a `Color` to a `[f32; 4]` from HLS colorspace pub fn as_hlsa_f32(self: Color) -> [f32; 4] { match self { Color::Rgba { red, green, blue, alpha, } => { let (hue, saturation, lightness) = HslRepresentation::nonlinear_srgb_to_hsl([red, green, blue]); [hue, saturation, lightness, alpha] } Color::RgbaLinear { red, green, blue, alpha, } => { let (hue, saturation, lightness) = HslRepresentation::nonlinear_srgb_to_hsl([ red.linear_to_nonlinear_srgb(), green.linear_to_nonlinear_srgb(), blue.linear_to_nonlinear_srgb(), ]); [hue, saturation, lightness, alpha] } Color::Hsla { hue, saturation, lightness, alpha, } => [hue, saturation, lightness, alpha], } } } impl Default for Color { fn default() -> Self { Color::WHITE } } impl AddAssign<Color> for Color { fn add_assign(&mut self, rhs: Color) { match self { Color::Rgba { red, green, blue, alpha, } => { let rhs = rhs.as_rgba_f32(); *red += rhs[0]; *green += rhs[1]; *blue += rhs[2]; *alpha += rhs[3]; } Color::RgbaLinear { red, green, blue, alpha, } => { let rhs = rhs.as_linear_rgba_f32(); *red += rhs[0]; *green += rhs[1]; *blue += rhs[2]; *alpha += rhs[3]; } Color::Hsla { hue, saturation, lightness, alpha, } => { let rhs = rhs.as_linear_rgba_f32(); *hue += rhs[0]; *saturation += rhs[1]; *lightness += rhs[2]; *alpha += rhs[3]; } } } } impl Add<Color> for Color { type Output = Color; fn add(self, rhs: Color) -> Self::Output { match self { Color::Rgba { red, green, blue, alpha, } => { let rhs = rhs.as_rgba_f32(); Color::Rgba { red: red + rhs[0], green: green + rhs[1], blue: blue + rhs[2], alpha: alpha + rhs[3], } } Color::RgbaLinear { red, green, blue, alpha, } => { let rhs = rhs.as_linear_rgba_f32(); Color::RgbaLinear { red: red + rhs[0], green: green + rhs[1], blue: blue + rhs[2], alpha: alpha + rhs[3], } } Color::Hsla { hue, saturation, lightness, alpha, } => { let rhs = rhs.as_linear_rgba_f32(); Color::Hsla { hue: hue + rhs[0], saturation: saturation + rhs[1], lightness: lightness + rhs[2], alpha: alpha + rhs[3], } } } } } impl AddAssign<Vec4> for Color { fn add_assign(&mut self, rhs: Vec4) { let rhs: Color = rhs.into(); *self += rhs } } impl Add<Vec4> for Color { type Output = Color; fn add(self, rhs: Vec4) -> Self::Output { let rhs: Color = rhs.into(); self + rhs } } impl From<Color> for [f32; 4] { fn from(color: Color) -> Self { color.as_rgba_f32() } } impl From<[f32; 4]> for Color { fn from([r, g, b, a]: [f32; 4]) -> Self { Color::rgba(r, g, b, a) } } impl From<Color> for Vec4 { fn from(color: Color) -> Self { let color: [f32; 4] = color.into(); Vec4::new(color[0], color[1], color[2], color[3]) } } impl From<Vec4> for Color { fn from(vec4: Vec4) -> Self { Color::rgba(vec4.x, vec4.y, vec4.z, vec4.w) } } impl Mul<f32> for Color { type Output = Color; fn mul(self, rhs: f32) -> Self::Output { match self { Color::Rgba { red, green, blue, alpha, } => Color::Rgba { red: red * rhs, green: green * rhs, blue: blue * rhs, alpha, }, Color::RgbaLinear { red, green, blue, alpha, } => Color::RgbaLinear { red: red * rhs, green: green * rhs, blue: blue * rhs, alpha, }, Color::Hsla { hue, saturation, lightness, alpha, } => Color::Hsla { hue: hue * rhs, saturation: saturation * rhs, lightness: lightness * rhs, alpha, }, } } } impl MulAssign<f32> for Color { fn mul_assign(&mut self, rhs: f32) { match self { Color::Rgba { red, green, blue, .. } => { *red *= rhs; *green *= rhs; *blue *= rhs; } Color::RgbaLinear { red, green, blue, .. } => { *red *= rhs; *green *= rhs; *blue *= rhs; } Color::Hsla { hue, saturation, lightness, .. } => { *hue *= rhs; *saturation *= rhs; *lightness *= rhs; } } } } impl Mul<Vec4> for Color { type Output = Color; fn mul(self, rhs: Vec4) -> Self::Output { match self { Color::Rgba { red, green, blue, alpha, } => Color::Rgba { red: red * rhs.x, green: green * rhs.y, blue: blue * rhs.z, alpha: alpha * rhs.w, }, Color::RgbaLinear { red, green, blue, alpha, } => Color::RgbaLinear { red: red * rhs.x, green: green * rhs.y, blue: blue * rhs.z, alpha: alpha * rhs.w, }, Color::Hsla { hue, saturation, lightness, alpha, } => Color::Hsla { hue: hue * rhs.x, saturation: saturation * rhs.y, lightness: lightness * rhs.z, alpha: alpha * rhs.w, }, } } } impl MulAssign<Vec4> for Color { fn mul_assign(&mut self, rhs: Vec4) { match self { Color::Rgba { red, green, blue, alpha, } => { *red *= rhs.x; *green *= rhs.y; *blue *= rhs.z; *alpha *= rhs.w; } Color::RgbaLinear { red, green, blue, alpha, } => { *red *= rhs.x; *green *= rhs.y; *blue *= rhs.z; *alpha *= rhs.w; } Color::Hsla { hue, saturation, lightness, alpha, } => { *hue *= rhs.x; *saturation *= rhs.y; *lightness *= rhs.z; *alpha *= rhs.w; } } } } impl Mul<Vec3> for Color { type Output = Color; fn mul(self, rhs: Vec3) -> Self::Output { match self { Color::Rgba { red, green, blue, alpha, } => Color::Rgba { red: red * rhs.x, green: green * rhs.y, blue: blue * rhs.z, alpha, }, Color::RgbaLinear { red, green, blue, alpha, } => Color::RgbaLinear { red: red * rhs.x, green: green * rhs.y, blue: blue * rhs.z, alpha, }, Color::Hsla { hue, saturation, lightness, alpha, } => Color::Hsla { hue: hue * rhs.x, saturation: saturation * rhs.y, lightness: lightness * rhs.z, alpha, }, } } } impl MulAssign<Vec3> for Color { fn mul_assign(&mut self, rhs: Vec3) { match self { Color::Rgba { red, green, blue, .. } => { *red *= rhs.x; *green *= rhs.y; *blue *= rhs.z; } Color::RgbaLinear { red, green, blue, .. } => { *red *= rhs.x; *green *= rhs.y; *blue *= rhs.z; } Color::Hsla { hue, saturation, lightness, .. } => { *hue *= rhs.x; *saturation *= rhs.y; *lightness *= rhs.z; } } } } impl Mul<[f32; 4]> for Color { type Output = Color; fn mul(self, rhs: [f32; 4]) -> Self::Output { match self { Color::Rgba { red, green, blue, alpha, } => Color::Rgba { red: red * rhs[0], green: green * rhs[1], blue: blue * rhs[2], alpha: alpha * rhs[3], }, Color::RgbaLinear { red, green, blue, alpha, } => Color::RgbaLinear { red: red * rhs[0], green: green * rhs[1], blue: blue * rhs[2], alpha: alpha * rhs[3], }, Color::Hsla { hue, saturation, lightness, alpha, } => Color::Hsla { hue: hue * rhs[0], saturation: saturation * rhs[1], lightness: lightness * rhs[2], alpha: alpha * rhs[3], }, } } } impl MulAssign<[f32; 4]> for Color { fn mul_assign(&mut self, rhs: [f32; 4]) { match self { Color::Rgba { red, green, blue, alpha, } => { *red *= rhs[0]; *green *= rhs[1]; *blue *= rhs[2]; *alpha *= rhs[3]; } Color::RgbaLinear { red, green, blue, alpha, } => { *red *= rhs[0]; *green *= rhs[1]; *blue *= rhs[2]; *alpha *= rhs[3]; } Color::Hsla { hue, saturation, lightness, alpha, } => { *hue *= rhs[0]; *saturation *= rhs[1]; *lightness *= rhs[2]; *alpha *= rhs[3]; } } } } impl Mul<[f32; 3]> for Color { type Output = Color; fn mul(self, rhs: [f32; 3]) -> Self::Output { match self { Color::Rgba { red, green, blue, alpha, } => Color::Rgba { red: red * rhs[0], green: green * rhs[1], blue: blue * rhs[2], alpha, }, Color::RgbaLinear { red, green, blue, alpha, } => Color::RgbaLinear { red: red * rhs[0], green: green * rhs[1], blue: blue * rhs[2], alpha, }, Color::Hsla { hue, saturation, lightness, alpha, } => Color::Hsla { hue: hue * rhs[0], saturation: saturation * rhs[1], lightness: lightness * rhs[2], alpha, }, } } } impl MulAssign<[f32; 3]> for Color { fn mul_assign(&mut self, rhs: [f32; 3]) { match self { Color::Rgba { red, green, blue, .. } => { *red *= rhs[0]; *green *= rhs[1]; *blue *= rhs[2]; } Color::RgbaLinear { red, green, blue, .. } => { *red *= rhs[0]; *green *= rhs[1]; *blue *= rhs[2]; } Color::Hsla { hue, saturation, lightness, .. } => { *hue *= rhs[0]; *saturation *= rhs[1]; *lightness *= rhs[2]; } } } } impl Bytes for Color { fn write_bytes(&self, buffer: &mut [u8]) { match *self { Color::Rgba { red, green, blue, alpha, } => { red.nonlinear_to_linear_srgb().write_bytes(buffer); green .nonlinear_to_linear_srgb() .write_bytes(&mut buffer[std::mem::size_of::<f32>()..]); blue.nonlinear_to_linear_srgb() .write_bytes(&mut buffer[2 * std::mem::size_of::<f32>()..]); alpha.write_bytes(&mut buffer[3 * std::mem::size_of::<f32>()..]); } Color::RgbaLinear { red, green, blue, alpha, } => { red.write_bytes(buffer); green.write_bytes(&mut buffer[std::mem::size_of::<f32>()..]); blue.write_bytes(&mut buffer[2 * std::mem::size_of::<f32>()..]); alpha.write_bytes(&mut buffer[3 * std::mem::size_of::<f32>()..]); } Color::Hsla { hue, saturation, lightness, alpha, } => { let [red, green, blue] = HslRepresentation::hsl_to_nonlinear_srgb(hue, saturation, lightness); red.nonlinear_to_linear_srgb().write_bytes(buffer); green .nonlinear_to_linear_srgb() .write_bytes(&mut buffer[std::mem::size_of::<f32>()..]); blue.nonlinear_to_linear_srgb() .write_bytes(&mut buffer[std::mem::size_of::<f32>() * 2..]); alpha.write_bytes(&mut buffer[std::mem::size_of::<f32>() * 3..]); } } } fn byte_len(&self) -> usize { std::mem::size_of::<f32>() * 4 } } impl_render_resource_bytes!(Color); #[derive(Debug)] pub enum HexColorError { Length, Hex(hex::FromHexError), } fn decode_rgb(data: &[u8]) -> Result<Color, HexColorError> { let mut buf = [0; 3]; match hex::decode_to_slice(data, &mut buf) { Ok(_) => { let r = buf[0] as f32 / 255.0; let g = buf[1] as f32 / 255.0; let b = buf[2] as f32 / 255.0; Ok(Color::rgb(r, g, b)) } Err(err) => Err(HexColorError::Hex(err)), } } fn decode_rgba(data: &[u8]) -> Result<Color, HexColorError> { let mut buf = [0; 4]; match hex::decode_to_slice(data, &mut buf) { Ok(_) => { let r = buf[0] as f32 / 255.0; let g = buf[1] as f32 / 255.0; let b = buf[2] as f32 / 255.0; let a = buf[3] as f32 / 255.0; Ok(Color::rgba(r, g, b, a)) } Err(err) => Err(HexColorError::Hex(err)), } } #[cfg(test)] mod tests { use super::*; #[test] fn hex_color() { assert_eq!(Color::hex("FFF").unwrap(), Color::rgb(1.0, 1.0, 1.0)); assert_eq!(Color::hex("000").unwrap(), Color::rgb(0.0, 0.0, 0.0)); assert!(Color::hex("---").is_err()); assert_eq!(Color::hex("FFFF").unwrap(), Color::rgba(1.0, 1.0, 1.0, 1.0)); assert_eq!(Color::hex("0000").unwrap(), Color::rgba(0.0, 0.0, 0.0, 0.0)); assert!(Color::hex("----").is_err()); assert_eq!(Color::hex("FFFFFF").unwrap(), Color::rgb(1.0, 1.0, 1.0)); assert_eq!(Color::hex("000000").unwrap(), Color::rgb(0.0, 0.0, 0.0)); assert!(Color::hex("------").is_err()); assert_eq!( Color::hex("FFFFFFFF").unwrap(), Color::rgba(1.0, 1.0, 1.0, 1.0) ); assert_eq!( Color::hex("00000000").unwrap(), Color::rgba(0.0, 0.0, 0.0, 0.0) ); assert!(Color::hex("--------").is_err()); assert!(Color::hex("1234567890").is_err()); } #[test] fn conversions_vec4() { let starting_vec4 = Vec4::new(0.4, 0.5, 0.6, 1.0); let starting_color = Color::from(starting_vec4); assert_eq!(starting_vec4, Vec4::from(starting_color),); let transformation = Vec4::new(0.5, 0.5, 0.5, 1.0); assert_eq!( starting_color * transformation, Color::from(starting_vec4 * transformation), ); } #[test] fn mul_and_mulassign_f32() { let transformation = 0.5; let starting_color = Color::rgba(0.4, 0.5, 0.6, 1.0); assert_eq!( starting_color * transformation, Color::rgba(0.4 * 0.5, 0.5 * 0.5, 0.6 * 0.5, 1.0), ); let mut mutated_color = starting_color; mutated_color *= transformation; assert_eq!(starting_color * transformation, mutated_color,); } #[test] fn mul_and_mulassign_f32by3() { let transformation = [0.4, 0.5, 0.6]; let starting_color = Color::rgba(0.4, 0.5, 0.6, 1.0); assert_eq!( starting_color * transformation, Color::rgba(0.4 * 0.4, 0.5 * 0.5, 0.6 * 0.6, 1.0), ); let mut mutated_color = starting_color; mutated_color *= transformation; assert_eq!(starting_color * transformation, mutated_color,); } #[test] fn mul_and_mulassign_f32by4() { let transformation = [0.4, 0.5, 0.6, 0.9]; let starting_color = Color::rgba(0.4, 0.5, 0.6, 1.0); assert_eq!( starting_color * transformation, Color::rgba(0.4 * 0.4, 0.5 * 0.5, 0.6 * 0.6, 1.0 * 0.9), ); let mut mutated_color = starting_color; mutated_color *= transformation; assert_eq!(starting_color * transformation, mutated_color,); } #[test] fn mul_and_mulassign_vec3() { let transformation = Vec3::new(0.2, 0.3, 0.4); let starting_color = Color::rgba(0.4, 0.5, 0.6, 1.0); assert_eq!( starting_color * transformation, Color::rgba(0.4 * 0.2, 0.5 * 0.3, 0.6 * 0.4, 1.0), ); let mut mutated_color = starting_color; mutated_color *= transformation; assert_eq!(starting_color * transformation, mutated_color,); } #[test] fn mul_and_mulassign_vec4() { let transformation = Vec4::new(0.2, 0.3, 0.4, 0.5); let starting_color = Color::rgba(0.4, 0.5, 0.6, 1.0); assert_eq!( starting_color * transformation, Color::rgba(0.4 * 0.2, 0.5 * 0.3, 0.6 * 0.4, 1.0 * 0.5), ); let mut mutated_color = starting_color; mutated_color *= transformation; assert_eq!(starting_color * transformation, mutated_color,); } }
28.38961
93
0.410024
ddc39e67e21f2aa51dfbdc4db714994b4953bcb9
3,432
#[doc = "Reader of register PUBLISH_SLEEPENTER"] pub type R = crate::R<u32, super::PUBLISH_SLEEPENTER>; #[doc = "Writer for register PUBLISH_SLEEPENTER"] pub type W = crate::W<u32, super::PUBLISH_SLEEPENTER>; #[doc = "Register PUBLISH_SLEEPENTER `reset()`'s with value 0"] impl crate::ResetValue for super::PUBLISH_SLEEPENTER { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `CHIDX`"] pub type CHIDX_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CHIDX`"] pub struct CHIDX_W<'a> { w: &'a mut W, } impl<'a> CHIDX_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) | ((value as u32) & 0x0f); self.w } } #[doc = "\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EN_A { #[doc = "0: Disable publishing"] DISABLED = 0, #[doc = "1: Enable publishing"] ENABLED = 1, } impl From<EN_A> for bool { #[inline(always)] fn from(variant: EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `EN`"] pub type EN_R = crate::R<bool, EN_A>; impl EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> EN_A { match self.bits { false => EN_A::DISABLED, true => EN_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == EN_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == EN_A::ENABLED } } #[doc = "Write proxy for field `EN`"] pub struct EN_W<'a> { w: &'a mut W, } impl<'a> EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Disable publishing"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(EN_A::DISABLED) } #[doc = "Enable publishing"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(EN_A::ENABLED) } #[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:3 - Channel that event SLEEPENTER will publish to."] #[inline(always)] pub fn chidx(&self) -> CHIDX_R { CHIDX_R::new((self.bits & 0x0f) as u8) } #[doc = "Bit 31"] #[inline(always)] pub fn en(&self) -> EN_R { EN_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bits 0:3 - Channel that event SLEEPENTER will publish to."] #[inline(always)] pub fn chidx(&mut self) -> CHIDX_W { CHIDX_W { w: self } } #[doc = "Bit 31"] #[inline(always)] pub fn en(&mut self) -> EN_W { EN_W { w: self } } }
27.238095
86
0.54662
2224cd84bba779ca2bce5e9ed0d816b98487a6c3
2,293
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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. //! Tokenizer states. //! //! This is public for use by the tokenizer tests. Other library //! users should not have to care about this. use core::prelude::*; #[deriving(PartialEq, Eq, PartialOrd, Ord, Clone, Hash)] pub enum ScriptEscapeKind { Escaped, DoubleEscaped, } #[deriving(PartialEq, Eq, PartialOrd, Ord, Clone, Hash)] pub enum DoctypeIdKind { Public, System, } #[deriving(PartialEq, Eq, PartialOrd, Ord, Clone, Hash)] pub enum RawKind { Rcdata, Rawtext, ScriptData, ScriptDataEscaped(ScriptEscapeKind), } #[deriving(PartialEq, Eq, PartialOrd, Ord, Clone, Hash)] pub enum AttrValueKind { Unquoted, SingleQuoted, DoubleQuoted, } #[deriving(PartialEq, Eq, PartialOrd, Ord, Clone, Hash)] pub enum State { Data, Plaintext, TagOpen, EndTagOpen, TagName, RawData(RawKind), RawLessThanSign(RawKind), RawEndTagOpen(RawKind), RawEndTagName(RawKind), ScriptDataEscapeStart(ScriptEscapeKind), ScriptDataEscapeStartDash, ScriptDataEscapedDash(ScriptEscapeKind), ScriptDataEscapedDashDash(ScriptEscapeKind), ScriptDataDoubleEscapeEnd, BeforeAttributeName, AttributeName, AfterAttributeName, BeforeAttributeValue, AttributeValue(AttrValueKind), AfterAttributeValueQuoted, SelfClosingStartTag, BogusComment, MarkupDeclarationOpen, CommentStart, CommentStartDash, Comment, CommentEndDash, CommentEnd, CommentEndBang, Doctype, BeforeDoctypeName, DoctypeName, AfterDoctypeName, AfterDoctypeKeyword(DoctypeIdKind), BeforeDoctypeIdentifier(DoctypeIdKind), DoctypeIdentifierDoubleQuoted(DoctypeIdKind), DoctypeIdentifierSingleQuoted(DoctypeIdKind), AfterDoctypeIdentifier(DoctypeIdKind), BetweenDoctypePublicAndSystemIdentifiers, BogusDoctype, CdataSection, }
26.056818
68
0.73092
90f596a9b68dad9ca6807391415d67ae8d859e2a
1,410
#[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::EGR { #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } } #[doc = r" Proxy"] pub struct _UGW<'a> { w: &'a mut W, } impl<'a> _UGW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 0 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - Update generation"] #[inline] pub fn ug(&mut self) -> _UGW { _UGW { w: self } } }
24.310345
60
0.47305
90e315ef52dde15f1e9bb7cf9da9166a67d3fc96
34,210
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ImportImageParameters { pub source: ImportSource, #[serde(rename = "targetTags", default, skip_serializing_if = "Vec::is_empty")] pub target_tags: Vec<String>, #[serde(rename = "untaggedTargetRepositories", default, skip_serializing_if = "Vec::is_empty")] pub untagged_target_repositories: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub mode: Option<import_image_parameters::Mode>, } pub mod import_image_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Mode { NoForce, Force, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ImportSource { #[serde(rename = "resourceId", default, skip_serializing_if = "Option::is_none")] pub resource_id: Option<String>, #[serde(rename = "registryUri", default, skip_serializing_if = "Option::is_none")] pub registry_uri: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub credentials: Option<ImportSourceCredentials>, #[serde(rename = "sourceImage")] pub source_image: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ImportSourceCredentials { #[serde(default, skip_serializing_if = "Option::is_none")] pub username: Option<String>, pub password: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistryNameCheckRequest { pub name: String, #[serde(rename = "type")] pub type_: registry_name_check_request::Type, } pub mod registry_name_check_request { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { #[serde(rename = "Microsoft.ContainerRegistry/registries")] MicrosoftContainerRegistryRegistries, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistryNameStatus { #[serde(rename = "nameAvailable", default, skip_serializing_if = "Option::is_none")] pub name_available: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub reason: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<OperationDefinition>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationDefinition { #[serde(default, skip_serializing_if = "Option::is_none")] pub origin: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub display: Option<OperationDisplayDefinition>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<OperationPropertiesDefinition>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationDisplayDefinition { #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub resource: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub operation: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationPropertiesDefinition { #[serde(rename = "serviceSpecification", default, skip_serializing_if = "Option::is_none")] pub service_specification: Option<OperationServiceSpecificationDefinition>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationServiceSpecificationDefinition { #[serde(rename = "metricSpecifications", default, skip_serializing_if = "Vec::is_empty")] pub metric_specifications: Vec<OperationMetricSpecificationDefinition>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationMetricSpecificationDefinition { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(rename = "displayDescription", default, skip_serializing_if = "Option::is_none")] pub display_description: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub unit: Option<String>, #[serde(rename = "aggregationType", default, skip_serializing_if = "Option::is_none")] pub aggregation_type: Option<String>, #[serde(rename = "internalMetricName", default, skip_serializing_if = "Option::is_none")] pub internal_metric_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Registry { #[serde(flatten)] pub resource: Resource, pub sku: Sku, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<RegistryProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Sku { pub name: sku::Name, #[serde(skip_serializing)] pub tier: Option<sku::Tier>, } pub mod sku { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Name { Classic, Basic, Standard, Premium, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Tier { Classic, Basic, Standard, Premium, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistryProperties { #[serde(rename = "loginServer", skip_serializing)] pub login_server: Option<String>, #[serde(rename = "creationDate", skip_serializing)] pub creation_date: Option<String>, #[serde(rename = "provisioningState", skip_serializing)] pub provisioning_state: Option<registry_properties::ProvisioningState>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<Status>, #[serde(rename = "adminUserEnabled", default, skip_serializing_if = "Option::is_none")] pub admin_user_enabled: Option<bool>, #[serde(rename = "storageAccount", default, skip_serializing_if = "Option::is_none")] pub storage_account: Option<StorageAccountProperties>, #[serde(rename = "networkRuleSet", default, skip_serializing_if = "Option::is_none")] pub network_rule_set: Option<NetworkRuleSet>, } pub mod registry_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Creating, Updating, Deleting, Succeeded, Failed, Canceled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Status { #[serde(rename = "displayStatus", skip_serializing)] pub display_status: Option<String>, #[serde(skip_serializing)] pub message: Option<String>, #[serde(skip_serializing)] pub timestamp: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StorageAccountProperties { pub id: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct NetworkRuleSet { #[serde(rename = "defaultAction")] pub default_action: network_rule_set::DefaultAction, #[serde(rename = "virtualNetworkRules", default, skip_serializing_if = "Vec::is_empty")] pub virtual_network_rules: Vec<VirtualNetworkRule>, #[serde(rename = "ipRules", default, skip_serializing_if = "Vec::is_empty")] pub ip_rules: Vec<IpRule>, } pub mod network_rule_set { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum DefaultAction { Allow, Deny, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct VirtualNetworkRule { #[serde(default, skip_serializing_if = "Option::is_none")] pub action: Option<virtual_network_rule::Action>, pub id: String, } pub mod virtual_network_rule { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Action { Allow, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IpRule { #[serde(default, skip_serializing_if = "Option::is_none")] pub action: Option<ip_rule::Action>, pub value: String, } pub mod ip_rule { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Action { Allow, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistryUpdateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub sku: Option<Sku>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<RegistryPropertiesUpdateParameters>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistryPropertiesUpdateParameters { #[serde(rename = "adminUserEnabled", default, skip_serializing_if = "Option::is_none")] pub admin_user_enabled: Option<bool>, #[serde(rename = "storageAccount", default, skip_serializing_if = "Option::is_none")] pub storage_account: Option<StorageAccountProperties>, #[serde(rename = "networkRuleSet", default, skip_serializing_if = "Option::is_none")] pub network_rule_set: Option<NetworkRuleSet>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistryListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Registry>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistryListCredentialsResult { #[serde(default, skip_serializing_if = "Option::is_none")] pub username: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub passwords: Vec<RegistryPassword>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistryPassword { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<registry_password::Name>, #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option<String>, } pub mod registry_password { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Name { #[serde(rename = "password")] Password, #[serde(rename = "password2")] Password2, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegenerateCredentialParameters { pub name: regenerate_credential_parameters::Name, } pub mod regenerate_credential_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Name { #[serde(rename = "password")] Password, #[serde(rename = "password2")] Password2, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistryUsageListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<RegistryUsage>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistryUsage { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub limit: Option<i64>, #[serde(rename = "currentValue", default, skip_serializing_if = "Option::is_none")] pub current_value: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub unit: Option<registry_usage::Unit>, } pub mod registry_usage { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Unit { Count, Bytes, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistryPolicies { #[serde(rename = "quarantinePolicy", default, skip_serializing_if = "Option::is_none")] pub quarantine_policy: Option<QuarantinePolicy>, #[serde(rename = "trustPolicy", default, skip_serializing_if = "Option::is_none")] pub trust_policy: Option<TrustPolicy>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QuarantinePolicy { #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<quarantine_policy::Status>, } pub mod quarantine_policy { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { #[serde(rename = "enabled")] Enabled, #[serde(rename = "disabled")] Disabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TrustPolicy { #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<trust_policy::Type>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<trust_policy::Status>, } pub mod trust_policy { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { Notary, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { #[serde(rename = "enabled")] Enabled, #[serde(rename = "disabled")] Disabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Replication { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ReplicationProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReplicationProperties { #[serde(rename = "provisioningState", skip_serializing)] pub provisioning_state: Option<replication_properties::ProvisioningState>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<Status>, } pub mod replication_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Creating, Updating, Deleting, Succeeded, Failed, Canceled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReplicationUpdateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReplicationListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Replication>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Webhook { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<WebhookProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WebhookProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<webhook_properties::Status>, #[serde(default, skip_serializing_if = "Option::is_none")] pub scope: Option<String>, pub actions: Vec<String>, #[serde(rename = "provisioningState", skip_serializing)] pub provisioning_state: Option<webhook_properties::ProvisioningState>, } pub mod webhook_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { #[serde(rename = "enabled")] Enabled, #[serde(rename = "disabled")] Disabled, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Creating, Updating, Deleting, Succeeded, Failed, Canceled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WebhookCreateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, pub location: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<WebhookPropertiesCreateParameters>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WebhookPropertiesCreateParameters { #[serde(rename = "serviceUri")] pub service_uri: String, #[serde(rename = "customHeaders", default, skip_serializing_if = "Option::is_none")] pub custom_headers: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<webhook_properties_create_parameters::Status>, #[serde(default, skip_serializing_if = "Option::is_none")] pub scope: Option<String>, pub actions: Vec<String>, } pub mod webhook_properties_create_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { #[serde(rename = "enabled")] Enabled, #[serde(rename = "disabled")] Disabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WebhookUpdateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<WebhookPropertiesUpdateParameters>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WebhookPropertiesUpdateParameters { #[serde(rename = "serviceUri", default, skip_serializing_if = "Option::is_none")] pub service_uri: Option<String>, #[serde(rename = "customHeaders", default, skip_serializing_if = "Option::is_none")] pub custom_headers: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<webhook_properties_update_parameters::Status>, #[serde(default, skip_serializing_if = "Option::is_none")] pub scope: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub actions: Vec<String>, } pub mod webhook_properties_update_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { #[serde(rename = "enabled")] Enabled, #[serde(rename = "disabled")] Disabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WebhookListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Webhook>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventInfo { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CallbackConfig { #[serde(rename = "serviceUri")] pub service_uri: String, #[serde(rename = "customHeaders", default, skip_serializing_if = "Option::is_none")] pub custom_headers: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Event>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Event { #[serde(flatten)] pub event_info: EventInfo, #[serde(rename = "eventRequestMessage", default, skip_serializing_if = "Option::is_none")] pub event_request_message: Option<EventRequestMessage>, #[serde(rename = "eventResponseMessage", default, skip_serializing_if = "Option::is_none")] pub event_response_message: Option<EventResponseMessage>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventRequestMessage { #[serde(default, skip_serializing_if = "Option::is_none")] pub content: Option<EventContent>, #[serde(default, skip_serializing_if = "Option::is_none")] pub headers: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub method: Option<String>, #[serde(rename = "requestUri", default, skip_serializing_if = "Option::is_none")] pub request_uri: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub version: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventResponseMessage { #[serde(default, skip_serializing_if = "Option::is_none")] pub content: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub headers: Option<serde_json::Value>, #[serde(rename = "reasonPhrase", default, skip_serializing_if = "Option::is_none")] pub reason_phrase: Option<String>, #[serde(rename = "statusCode", default, skip_serializing_if = "Option::is_none")] pub status_code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub version: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventContent { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub timestamp: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub action: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub target: Option<Target>, #[serde(default, skip_serializing_if = "Option::is_none")] pub request: Option<Request>, #[serde(default, skip_serializing_if = "Option::is_none")] pub actor: Option<Actor>, #[serde(default, skip_serializing_if = "Option::is_none")] pub source: Option<Source>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Target { #[serde(rename = "mediaType", default, skip_serializing_if = "Option::is_none")] pub media_type: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub size: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub digest: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub length: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub repository: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tag: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub version: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Request { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub addr: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub host: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub method: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub useragent: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Actor { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Source { #[serde(default, skip_serializing_if = "Option::is_none")] pub addr: Option<String>, #[serde(rename = "instanceID", default, skip_serializing_if = "Option::is_none")] pub instance_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Resource { #[serde(skip_serializing)] pub id: Option<String>, #[serde(skip_serializing)] pub name: Option<String>, #[serde(rename = "type", skip_serializing)] pub type_: Option<String>, pub location: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ScopeMap { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ScopeMapProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ProxyResource { #[serde(skip_serializing)] pub id: Option<String>, #[serde(skip_serializing)] pub name: Option<String>, #[serde(rename = "type", skip_serializing)] pub type_: Option<String>, #[serde(rename = "systemData", skip_serializing)] pub system_data: Option<SystemData>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ScopeMapProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "type", skip_serializing)] pub type_: Option<String>, #[serde(rename = "creationDate", skip_serializing)] pub creation_date: Option<String>, #[serde(rename = "provisioningState", skip_serializing)] pub provisioning_state: Option<scope_map_properties::ProvisioningState>, pub actions: Vec<String>, } pub mod scope_map_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Creating, Updating, Deleting, Succeeded, Failed, Canceled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ScopeMapUpdateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ScopeMapPropertiesUpdateParameters>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ScopeMapPropertiesUpdateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub actions: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ScopeMapListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<ScopeMap>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Token { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<TokenProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TokenProperties { #[serde(rename = "creationDate", skip_serializing)] pub creation_date: Option<String>, #[serde(rename = "provisioningState", skip_serializing)] pub provisioning_state: Option<token_properties::ProvisioningState>, #[serde(rename = "scopeMapId", default, skip_serializing_if = "Option::is_none")] pub scope_map_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub credentials: Option<TokenCredentialsProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<token_properties::Status>, } pub mod token_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Creating, Updating, Deleting, Succeeded, Failed, Canceled, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { #[serde(rename = "enabled")] Enabled, #[serde(rename = "disabled")] Disabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TokenCredentialsProperties { #[serde(rename = "activeDirectoryObject", default, skip_serializing_if = "Option::is_none")] pub active_directory_object: Option<ActiveDirectoryObject>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub certificates: Vec<TokenCertificate>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub passwords: Vec<TokenPassword>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ActiveDirectoryObject { #[serde(rename = "objectId", default, skip_serializing_if = "Option::is_none")] pub object_id: Option<String>, #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TokenCertificate { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<token_certificate::Name>, #[serde(default, skip_serializing_if = "Option::is_none")] pub expiry: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub thumbprint: Option<String>, #[serde(rename = "encodedPemCertificate", default, skip_serializing_if = "Option::is_none")] pub encoded_pem_certificate: Option<String>, } pub mod token_certificate { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Name { #[serde(rename = "certificate1")] Certificate1, #[serde(rename = "certificate2")] Certificate2, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TokenPassword { #[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")] pub creation_time: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub expiry: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<token_password::Name>, #[serde(skip_serializing)] pub value: Option<String>, } pub mod token_password { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Name { #[serde(rename = "password1")] Password1, #[serde(rename = "password2")] Password2, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TokenUpdateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<TokenUpdateProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TokenUpdateProperties { #[serde(rename = "scopeMapId", default, skip_serializing_if = "Option::is_none")] pub scope_map_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<token_update_properties::Status>, #[serde(default, skip_serializing_if = "Option::is_none")] pub credentials: Option<TokenCredentialsProperties>, } pub mod token_update_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { #[serde(rename = "enabled")] Enabled, #[serde(rename = "disabled")] Disabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TokenListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Token>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GenerateCredentialsParameters { #[serde(rename = "tokenId", default, skip_serializing_if = "Option::is_none")] pub token_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub expiry: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<generate_credentials_parameters::Name>, } pub mod generate_credentials_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Name { #[serde(rename = "password1")] Password1, #[serde(rename = "password2")] Password2, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GenerateCredentialsResult { #[serde(default, skip_serializing_if = "Option::is_none")] pub username: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub passwords: Vec<TokenPassword>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SystemData { #[serde(rename = "createdBy", default, skip_serializing_if = "Option::is_none")] pub created_by: Option<String>, #[serde(rename = "createdByType", default, skip_serializing_if = "Option::is_none")] pub created_by_type: Option<system_data::CreatedByType>, #[serde(rename = "createdAt", default, skip_serializing_if = "Option::is_none")] pub created_at: Option<String>, #[serde(rename = "lastModifiedBy", default, skip_serializing_if = "Option::is_none")] pub last_modified_by: Option<String>, #[serde(rename = "lastModifiedByType", default, skip_serializing_if = "Option::is_none")] pub last_modified_by_type: Option<system_data::LastModifiedByType>, #[serde(rename = "lastModifiedAt", default, skip_serializing_if = "Option::is_none")] pub last_modified_at: Option<String>, } pub mod system_data { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum CreatedByType { User, Application, ManagedIdentity, Key, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum LastModifiedByType { User, Application, ManagedIdentity, Key, } }
38.875
99
0.696931
7a41ca7d0f2f54bb58a15976dab2d3aa7027b808
14,488
//! Holds a stream that ensures chunks have the same (uniform) schema use std::sync::Arc; use snafu::Snafu; use std::task::{Context, Poll}; use arrow_deps::{ arrow::{ array::new_null_array, datatypes::{DataType, SchemaRef}, error::Result as ArrowResult, record_batch::RecordBatch, }, datafusion::physical_plan::{RecordBatchStream, SendableRecordBatchStream}, }; use futures::Stream; /// Database schema creation / validation errors. #[derive(Debug, Snafu)] pub enum Error { #[snafu(display("Internal error creating SchemaAdapterStream: field '{}' does not appear in the output schema", field_name,))] InternalLostInputField { field_name: String }, #[snafu(display("Internal error creating SchemaAdapterStream: input field '{}' had type '{:?}' which is different than output field '{}' which had type '{:?}'", input_field_name, input_field_type, output_field_name, output_field_type,))] InternalDataTypeMismatch { input_field_name: String, input_field_type: DataType, output_field_name: String, output_field_type: DataType, }, #[snafu(display("Internal error creating SchemaAdapterStream: creating null of type '{:?}' which is different than output field '{}' which had type '{:?}'", field_type, output_field_name, output_field_type,))] InternalDataTypeMismatchForNull { field_type: DataType, output_field_name: String, output_field_type: DataType, }, } pub type Result<T, E = Error> = std::result::Result<T, E>; /// This stream wraps another underlying stream to ensure it produces /// the specified schema. If the underlying stream produces a subset /// of the columns specified in desired schema, this stream creates /// arrays with NULLs to pad out the missing columns /// /// For example: /// /// If a table had schema with Cols A, B, and C, but the chunk (input) /// stream only produced record batches with columns A and C, this /// stream would append a column of B / nulls to each record batch /// that flowed through it /// /// ```text /// /// ┌────────────────┐ ┌─────────────────────────┐ /// │ ┌─────┐┌─────┐ │ │ ┌─────┐┌──────┐┌─────┐ │ /// │ │ A ││ C │ │ │ │ A ││ B ││ C │ │ /// │ │ - ││ - │ │ │ │ - ││ - ││ - │ │ /// ┌──────────────┐ │ │ 1 ││ 10 │ │ ┌──────────────┐ │ │ 1 ││ NULL ││ 10 │ │ /// │ Input │ │ │ 2 ││ 20 │ │ │ Adapter │ │ │ 2 ││ NULL ││ 20 │ │ /// │ Stream ├────▶ │ │ 3 ││ 30 │ │────▶│ Stream ├───▶│ │ 3 ││ NULL ││ 30 │ │ /// └──────────────┘ │ │ 4 ││ 40 │ │ └──────────────┘ │ │ 4 ││ NULL ││ 40 │ │ /// │ └─────┘└─────┘ │ │ └─────┘└──────┘└─────┘ │ /// │ │ │ │ /// │ Record Batch │ │ Record Batch │ /// └────────────────┘ └─────────────────────────┘ /// ``` pub(crate) struct SchemaAdapterStream { input: SendableRecordBatchStream, /// Output schema of this stream /// The schema of `input` is always a subset of output_schema output_schema: SchemaRef, mappings: Vec<ColumnMapping>, } impl std::fmt::Debug for SchemaAdapterStream { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("SchemaAdapterStream") .field("input", &"(OPAQUE STREAM)") .field("output_schema", &self.output_schema) .field("mappings", &self.mappings) .finish() } } impl SchemaAdapterStream { /// Try to create a new adapter stream that produces batches with /// the specified output_schema /// /// If the underlying stream produces columns that DO NOT appear /// in the output schema, or are different types than the output /// schema, an error will be produced. pub(crate) fn try_new( input: SendableRecordBatchStream, output_schema: SchemaRef, ) -> Result<Self> { let input_schema = input.schema(); // Figure out how to compute each column in the output let mappings = output_schema .fields() .iter() .map(|output_field| { let input_field_index = input_schema .fields() .iter() .enumerate() .find(|(_, input_field)| output_field.name() == input_field.name()) .map(|(idx, _)| idx); if let Some(input_field_index) = input_field_index { ColumnMapping::FromInput(input_field_index) } else { ColumnMapping::MakeNull(output_field.data_type().clone()) } }) .collect::<Vec<_>>(); // sanity logic checks for input_field in input_schema.fields().iter() { // that there are no fields in the input schema that are // not present in the desired output schema (otherwise we // are dropping fields -- theys should have been selected // out with projection push down) if output_schema .fields() .iter() .find(|output_field| input_field.name() == output_field.name()) .is_none() { return InternalLostInputField { field_name: input_field.name(), } .fail(); } } // Verify the mappings match the output type for (output_index, mapping) in mappings.iter().enumerate() { match mapping { ColumnMapping::FromInput(input_index) => { let input_field = input_schema.field(*input_index); let output_field = output_schema.field(output_index); if input_field.data_type() != output_field.data_type() { return InternalDataTypeMismatch { input_field_name: input_field.name(), input_field_type: input_field.data_type().clone(), output_field_name: output_field.name(), output_field_type: output_field.data_type().clone(), } .fail(); } } ColumnMapping::MakeNull(data_type) => { let output_field = output_schema.field(output_index); if data_type != output_field.data_type() { return InternalDataTypeMismatchForNull { field_type: data_type.clone(), output_field_name: output_field.name(), output_field_type: output_field.data_type().clone(), } .fail(); } } } } Ok(Self { input, output_schema, mappings, }) } /// Extends the record batch, if needed, so that it matches the schema fn extend_batch(&self, batch: RecordBatch) -> ArrowResult<RecordBatch> { let output_columns = self .mappings .iter() .map(|mapping| match mapping { ColumnMapping::FromInput(input_index) => Arc::clone(&batch.column(*input_index)), ColumnMapping::MakeNull(data_type) => new_null_array(data_type, batch.num_rows()), }) .collect::<Vec<_>>(); RecordBatch::try_new(Arc::clone(&self.output_schema), output_columns) } } impl RecordBatchStream for SchemaAdapterStream { fn schema(&self) -> SchemaRef { Arc::clone(&self.output_schema) } } impl Stream for SchemaAdapterStream { type Item = ArrowResult<RecordBatch>; fn poll_next( mut self: std::pin::Pin<&mut Self>, ctx: &mut Context<'_>, ) -> Poll<Option<Self::Item>> { // the Poll result is an Opton<Result<Batch>> so we need a few // layers of maps to get at the actual batch, if any self.input.as_mut().poll_next(ctx).map(|maybe_result| { maybe_result.map(|batch| batch.and_then(|batch| self.extend_batch(batch))) }) } // TODO is there a useful size_hint to pass? } /// Describes how to create column in the output. #[derive(Debug)] enum ColumnMapping { /// Output column is found at <index> column of the input schema FromInput(usize), /// Output colum should be synthesized with nulls of the specified type MakeNull(DataType), } #[cfg(test)] mod tests { use std::sync::Arc; use super::*; use arrow_deps::{ arrow::{ array::{Array, Int32Array, StringArray}, datatypes::{Field, Schema}, record_batch::RecordBatch, }, assert_table_eq, datafusion::physical_plan::common::{collect, SizedRecordBatchStream}, }; use test_helpers::assert_contains; #[tokio::test] async fn same_input_and_output() { let batch = make_batch(); let output_schema = batch.schema(); let input_stream = SizedRecordBatchStream::new(batch.schema(), vec![Arc::new(batch)]); let adapter_stream = SchemaAdapterStream::try_new(Box::pin(input_stream), output_schema).unwrap(); let output = collect(Box::pin(adapter_stream)) .await .expect("Running plan"); let expected = vec![ "+---+---+-----+", "| a | b | c |", "+---+---+-----+", "| 1 | 4 | foo |", "| 2 | 5 | bar |", "| 3 | 6 | baz |", "+---+---+-----+", ]; assert_table_eq!(&expected, &output); } #[tokio::test] async fn input_different_order_than_output() { let batch = make_batch(); // input has columns in different order than desired output let output_schema = Arc::new(Schema::new(vec![ Field::new("b", DataType::Int32, false), Field::new("c", DataType::Utf8, false), Field::new("a", DataType::Int32, false), ])); let input_stream = SizedRecordBatchStream::new(batch.schema(), vec![Arc::new(batch)]); let adapter_stream = SchemaAdapterStream::try_new(Box::pin(input_stream), output_schema).unwrap(); let output = collect(Box::pin(adapter_stream)) .await .expect("Running plan"); let expected = vec![ "+---+-----+---+", "| b | c | a |", "+---+-----+---+", "| 4 | foo | 1 |", "| 5 | bar | 2 |", "| 6 | baz | 3 |", "+---+-----+---+", ]; assert_table_eq!(&expected, &output); } #[tokio::test] async fn input_subset_of_output() { let batch = make_batch(); // input has subset of columns of the desired otuput. d and e are not present let output_schema = Arc::new(Schema::new(vec![ Field::new("c", DataType::Utf8, false), Field::new("e", DataType::Float64, false), Field::new("b", DataType::Int32, false), Field::new("d", DataType::Float32, false), Field::new("a", DataType::Int32, false), ])); let input_stream = SizedRecordBatchStream::new(batch.schema(), vec![Arc::new(batch)]); let adapter_stream = SchemaAdapterStream::try_new(Box::pin(input_stream), output_schema).unwrap(); let output = collect(Box::pin(adapter_stream)) .await .expect("Running plan"); let expected = vec![ "+-----+---+---+---+---+", "| c | e | b | d | a |", "+-----+---+---+---+---+", "| foo | | 4 | | 1 |", "| bar | | 5 | | 2 |", "| baz | | 6 | | 3 |", "+-----+---+---+---+---+", ]; assert_table_eq!(&expected, &output); } #[tokio::test] async fn input_superset_of_columns() { let batch = make_batch(); // No such column "b" in output -- column would be lost let output_schema = Arc::new(Schema::new(vec![ Field::new("c", DataType::Utf8, false), Field::new("a", DataType::Int32, false), ])); let input_stream = SizedRecordBatchStream::new(batch.schema(), vec![Arc::new(batch)]); let res = SchemaAdapterStream::try_new(Box::pin(input_stream), output_schema); assert_contains!( res.unwrap_err().to_string(), "field 'b' does not appear in the output schema" ); } #[tokio::test] async fn input_has_different_type() { let batch = make_batch(); // column c has string type in input, output asks float32 let output_schema = Arc::new(Schema::new(vec![ Field::new("c", DataType::Float32, false), Field::new("b", DataType::Int32, false), Field::new("a", DataType::Int32, false), ])); let input_stream = SizedRecordBatchStream::new(batch.schema(), vec![Arc::new(batch)]); let res = SchemaAdapterStream::try_new(Box::pin(input_stream), output_schema); assert_contains!(res.unwrap_err().to_string(), "input field 'c' had type 'Utf8' which is different than output field 'c' which had type 'Float32'"); } // input has different column types than desired output fn make_batch() -> RecordBatch { let col_a = Arc::new(Int32Array::from(vec![1, 2, 3])); let col_b = Arc::new(Int32Array::from(vec![4, 5, 6])); let col_c = Arc::new(StringArray::from(vec!["foo", "bar", "baz"])); let schema = Schema::new(vec![ Field::new("a", col_a.data_type().clone(), false), Field::new("b", col_b.data_type().clone(), false), Field::new("c", col_c.data_type().clone(), false), ]); RecordBatch::try_new(Arc::new(schema), vec![col_a, col_b, col_c]).unwrap() } }
38.737968
164
0.516289
efe7c9697c4e5628ccf686b8da993d1ceff73e90
16,534
use crate::cache::Cache; use crate::datastore; use crate::domain::PublicKeyApiResponse; use crate::types::GrpcResult; use crate::pb::{PublicKeyRequest, PublicKeyResponse}; use crate::pb::public_key_service_server::PublicKeyService; use crate::pb::public_key_request::Impl::HeaderAuth as HeaderAuthEnumRequest; use std::convert::TryInto; use std::sync::{Arc, Mutex}; use sqlx::postgres::PgPool; use tonic::{Request, Response, Status}; use url::Url; // TODO background process that updates cache on occasion #[derive(Debug)] pub struct PublicKeyGrpc { // This cache is using a std::sync::Mutex because the tokio docs mention that this is often // preferrable to the tokio Mutex when you are strictly locking data. In cases where you // are locking over a database connection, or io resource, the tokio Mutex is required. cache: Arc<Mutex<Cache>>, db_pool: Arc<PgPool>, } impl PublicKeyGrpc { pub fn new(cache: Arc<Mutex<Cache>>, db_pool: Arc<PgPool>) -> Self { Self { cache, db_pool } } } #[tonic::async_trait] impl PublicKeyService for PublicKeyGrpc { async fn add( &self, request: Request<PublicKeyRequest>, ) -> GrpcResult<Response<PublicKeyResponse>> { let request = request.into_inner(); // validate public_key if let Some(ref public_key) = request.public_key { if public_key.key.is_none() { return Err(Status::invalid_argument("must specify key type")) } } else { return Err(Status::invalid_argument("must specify public key")) } // validate auth methods match request.r#impl { Some(HeaderAuthEnumRequest(ref auth)) => { if auth.header.trim().is_empty() { return Err(Status::invalid_argument("must specify non empty auth header")) } if auth.value.trim().is_empty() { return Err(Status::invalid_argument("must specify non empty auth value")) } }, _ => (), }; // validate url if it is not empty if !request.url.is_empty() { Url::parse(&request.url) .map_err(|e| Status::invalid_argument(format!("Unable to parse url {} - {:?}", &request.url, e)))?; } let key = datastore::add_public_key(&self.db_pool, request.try_into()?).await?; let response = key.clone().to_response()?; { let mut cache = self.cache.lock().unwrap(); cache.add_public_key(key); } Ok(Response::new(response)) } } #[cfg(test)] mod tests { use crate::*; use crate::public_key::*; use crate::pb::{public_key::Key, HeaderAuth, PublicKey}; use crate::pb::public_key_response::Impl::HeaderAuth as HeaderAuthEnumResponse; use testcontainers::*; use testcontainers::images::postgres::Postgres; use testcontainers::clients::Cli; async fn setup_postgres(container: &Container<'_, Cli, Postgres>) -> PgPool { let connection_string = &format!( "postgres://postgres:postgres@localhost:{}/postgres", container.get_host_port(5432).unwrap(), ); let pool = PgPoolOptions::new() .max_connections(5) .connect(&connection_string) .await .unwrap(); MIGRATOR.run(&pool).await.unwrap(); pool } #[tokio::test] async fn invalid_url() { let docker = clients::Cli::default(); let image = images::postgres::Postgres::default().with_version(9); let container = docker.run(image); let cache = Mutex::new(Cache::default()); let pool = setup_postgres(&container).await; let public_key_service = PublicKeyGrpc { cache: Arc::new(cache), db_pool: Arc::new(pool) }; let request = PublicKeyRequest { public_key: Some(PublicKey { key: Some(Key::Secp256k1(vec![])), }), r#impl: None, url: "invalidurl.com".to_owned(), metadata: None, }; let response = public_key_service.add(Request::new(request)).await; match response { Err(err) => { assert_eq!(err.code(), tonic::Code::InvalidArgument); assert_eq!(err.message(), "Unable to parse url invalidurl.com - RelativeUrlWithoutBase".to_owned()); }, _ => assert_eq!(format!("{:?}", response), ""), } } #[tokio::test] async fn empty_url() { let docker = clients::Cli::default(); let image = images::postgres::Postgres::default().with_version(9); let container = docker.run(image); let cache = Mutex::new(Cache::default()); let pool = setup_postgres(&container).await; let public_key_service = PublicKeyGrpc { cache: Arc::new(cache), db_pool: Arc::new(pool) }; let request = PublicKeyRequest { public_key: Some(PublicKey { key: Some(Key::Secp256k1(vec![1u8, 2u8, 3u8])), }), r#impl: None, url: String::default(), metadata: None, }; let response = public_key_service.add(Request::new(request)).await; match response { Ok(result) => { let result = result.into_inner(); assert!(!result.uuid.is_none()); assert_eq!(result.public_key.unwrap().key.unwrap(), Key::Secp256k1(vec![1u8, 2u8, 3u8])); assert!(result.url.is_empty()); assert!(result.metadata.is_none()); assert!(!result.created_at.is_none()); assert!(!result.updated_at.is_none()); }, _ => { assert_eq!(format!("{:?}", response), ""); } } } #[tokio::test] async fn empty_auth_header_header() { let docker = clients::Cli::default(); let image = images::postgres::Postgres::default().with_version(9); let container = docker.run(image); let cache = Mutex::new(Cache::default()); let pool = setup_postgres(&container).await; let public_key_service = PublicKeyGrpc { cache: Arc::new(cache), db_pool: Arc::new(pool) }; let request = PublicKeyRequest { public_key: Some(PublicKey { key: Some(Key::Secp256k1(vec![1u8, 2u8, 3u8])), }), r#impl: Some(HeaderAuthEnumRequest(HeaderAuth { header: String::from(""), value: String::from("custom_value"), })), url: String::default(), metadata: None, }; let response = public_key_service.add(Request::new(request)).await; match response { Err(err) => { assert_eq!(err.code(), tonic::Code::InvalidArgument); assert_eq!(err.message(), "must specify non empty auth header".to_owned()); }, _ => assert_eq!(format!("{:?}", response), ""), } } #[tokio::test] async fn empty_auth_header_value() { let docker = clients::Cli::default(); let image = images::postgres::Postgres::default().with_version(9); let container = docker.run(image); let cache = Mutex::new(Cache::default()); let pool = setup_postgres(&container).await; let public_key_service = PublicKeyGrpc { cache: Arc::new(cache), db_pool: Arc::new(pool) }; let request = PublicKeyRequest { public_key: Some(PublicKey { key: Some(Key::Secp256k1(vec![1u8, 2u8, 3u8])), }), r#impl: Some(HeaderAuthEnumRequest(HeaderAuth { header: String::from("X-Custom-Header"), value: String::from(""), })), url: String::default(), metadata: None, }; let response = public_key_service.add(Request::new(request)).await; match response { Err(err) => { assert_eq!(err.code(), tonic::Code::InvalidArgument); assert_eq!(err.message(), "must specify non empty auth value".to_owned()); }, _ => assert_eq!(format!("{:?}", response), ""), } } #[tokio::test] async fn missing_public_key() { let docker = clients::Cli::default(); let image = images::postgres::Postgres::default().with_version(9); let container = docker.run(image); let cache = Mutex::new(Cache::default()); let pool = setup_postgres(&container).await; let public_key_service = PublicKeyGrpc { cache: Arc::new(cache), db_pool: Arc::new(pool) }; let request = PublicKeyRequest { public_key: None, r#impl: None, url: "http://test.com".to_owned(), metadata: None, }; let response = public_key_service.add(Request::new(request)).await; match response { Err(err) => { assert_eq!(err.code(), tonic::Code::InvalidArgument); assert_eq!(err.message(), "must specify public key".to_owned()); }, _ => assert_eq!(format!("{:?}", response), ""), } } #[tokio::test] async fn missing_key() { let docker = clients::Cli::default(); let image = images::postgres::Postgres::default().with_version(9); let container = docker.run(image); let cache = Mutex::new(Cache::default()); let pool = setup_postgres(&container).await; let public_key_service = PublicKeyGrpc { cache: Arc::new(cache), db_pool: Arc::new(pool) }; let request = PublicKeyRequest { public_key: Some(PublicKey { key: None }), r#impl: None, url: "http://test.com".to_owned(), metadata: None, }; let response = public_key_service.add(Request::new(request)).await; match response { Err(err) => { assert_eq!(err.code(), tonic::Code::InvalidArgument); assert_eq!(err.message(), "must specify key type".to_owned()); }, _ => assert_eq!(format!("{:?}", response), ""), } } #[tokio::test] async fn duplicate_key() { let docker = clients::Cli::default(); let image = images::postgres::Postgres::default().with_version(9); let container = docker.run(image); let cache = Mutex::new(Cache::default()); let pool = setup_postgres(&container).await; let public_key_service = PublicKeyGrpc { cache: Arc::new(cache), db_pool: Arc::new(pool) }; let request1 = PublicKeyRequest { public_key: Some(PublicKey { key: Some(Key::Secp256k1(vec![1u8, 2u8, 3u8])), }), r#impl: None, url: "http://test.com".to_owned(), metadata: None, }; let request2 = PublicKeyRequest { public_key: Some(PublicKey { key: Some(Key::Secp256k1(vec![1u8, 2u8, 3u8])), }), r#impl: None, url: "http://test2.com".to_owned(), metadata: None, }; let response = public_key_service.add(Request::new(request1)).await; let (uuid, url) = match response { Ok(result) => { let result = result.into_inner(); assert!(!result.uuid.is_none()); (result.uuid, result.url) }, _ => { assert_eq!(format!("{:?}", response), ""); unreachable!(); }, }; let response = public_key_service.add(Request::new(request2)).await; match response { Ok(result) => { let result = result.into_inner(); assert!(!result.uuid.is_none()); assert_eq!(uuid, result.uuid); assert_ne!(url, result.url); assert_eq!("http://test2.com", result.url); } _ => assert_eq!(format!("{:?}", response), ""), }; } #[tokio::test] async fn returns_full_proto() { let docker = clients::Cli::default(); let image = images::postgres::Postgres::default().with_version(9); let container = docker.run(image); let cache = Mutex::new(Cache::default()); let pool = setup_postgres(&container).await; let public_key_service = PublicKeyGrpc { cache: Arc::new(cache), db_pool: Arc::new(pool) }; // TODO add metadata to this request let request = PublicKeyRequest { public_key: Some(PublicKey { key: Some(Key::Secp256k1(vec![1u8, 2u8, 3u8])), }), r#impl: Some(HeaderAuthEnumRequest(HeaderAuth { header: String::from("X-Custom-Header"), value: String::from("custom_value"), })), url: "http://test.com".to_owned(), metadata: None, }; let response = public_key_service.add(Request::new(request)).await; match response { Ok(result) => { let result = result.into_inner(); assert!(!result.uuid.is_none()); assert_eq!(result.public_key.unwrap().key.unwrap(), Key::Secp256k1(vec![1u8, 2u8, 3u8])); assert_eq!( result.r#impl.unwrap(), HeaderAuthEnumResponse(HeaderAuth { header: String::from("x-custom-header"), value: String::from("custom_value"), }), ); assert_eq!(result.url, String::from("http://test.com")); assert!(result.metadata.is_none()); assert!(!result.created_at.is_none()); assert!(!result.updated_at.is_none()); }, _ => assert_eq!(format!("{:?}", response), ""), } } #[tokio::test] async fn adds_empty_urls_to_local_cache() { let docker = clients::Cli::default(); let image = images::postgres::Postgres::default().with_version(9); let container = docker.run(image); let cache = Arc::new(Mutex::new(Cache::default())); let pool = setup_postgres(&container).await; let public_key_service = PublicKeyGrpc { cache: Arc::clone(&cache), db_pool: Arc::new(pool) }; let request = PublicKeyRequest { public_key: Some(PublicKey { key: Some(Key::Secp256k1(vec![1u8, 2u8, 3u8])), }), r#impl: None, url: String::default(), metadata: None, }; let response = public_key_service.add(Request::new(request)).await; match response { Ok(_) => (), _ => assert_eq!(format!("{:?}", response), ""), } let cache = Arc::clone(&cache); let cache = cache.lock().unwrap(); assert_eq!(cache.public_keys.len(), 1); assert!(cache.public_keys.contains_key(&base64::encode(&vec![1u8, 2u8, 3u8]))); assert_eq!(cache.public_keys.get(&base64::encode(&vec![1u8, 2u8, 3u8])).unwrap().url, String::from("")); } #[tokio::test] async fn adds_nonempty_urls_to_remote_cache() { let docker = clients::Cli::default(); let image = images::postgres::Postgres::default().with_version(9); let container = docker.run(image); let cache = Arc::new(Mutex::new(Cache::default())); let pool = setup_postgres(&container).await; let public_key_service = PublicKeyGrpc { cache: Arc::clone(&cache), db_pool: Arc::new(pool) }; let request = PublicKeyRequest { public_key: Some(PublicKey { key: Some(Key::Secp256k1(vec![1u8, 2u8, 3u8])), }), r#impl: None, url: "http://test.com".to_owned(), metadata: None, }; let response = public_key_service.add(Request::new(request)).await; match response { Ok(_) => (), _ => assert_eq!(format!("{:?}", response), ""), } let cache = Arc::clone(&cache); let cache = cache.lock().unwrap(); assert_eq!(cache.public_keys.len(), 1); assert!(cache.public_keys.contains_key(&base64::encode(&vec![1u8, 2u8, 3u8]))); assert_ne!(cache.public_keys.get(&base64::encode(&vec![1u8, 2u8, 3u8])).unwrap().url, String::from("")); } }
37.922018
116
0.547659
f562b28221512a5c19f5785a0729e0599d1f19c2
385
pub use crate::range::RangeAddrParseError; pub use crate::network::{NetworkAddrParseError, InvalidNetmaskError, InvalidNetmaskPrefixError}; #[derive(Clone, Debug, PartialEq, Eq)] pub enum NetAddsError { RangeAddrParse(RangeAddrParseError), NetworkAddrParse(NetworkAddrParseError), InvalidNetmask(InvalidNetmaskError), InvalidNetmaskPrefix(InvalidNetmaskPrefixError) }
35
96
0.81039
dd488a13c29e36d8dc9716baf2ad0dc83b770e54
7,342
use ic_types::Height; use serde::{Deserialize, Serialize}; use std::path::PathBuf; /// Default capacity, in number of messages, for validated and unvalidated pools const MAX_INGRESS_POOL_VALIDATED_CAPACITY: usize = 1024; const MAX_INGRESS_POOL_UNVALIDATED_CAPACITY_PER_PEER: usize = 100_000_000; const MAX_CONSENSUS_POOL_VALIDATED_CAPACITY: usize = 2048; const MAX_CONSENSUS_POOL_UNVALIDATED_CAPACITY_PER_PEER: usize = 2048; const PERSISTENT_POOL_VALIDATED_PURGE_INTERVAL: u64 = 5000; /// The number of height folders we store grouped inside a single "shard" folder /// (to avoid running into inode limits on potentially misconfigured file /// systems). pub const BACKUP_GROUP_SIZE: u64 = 10000; /// External configuration for artifact pools meant to be used by replica's /// config file. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct ArtifactPoolTomlConfig { /// The path in which to store the validated section of the consensus pool. pub consensus_pool_path: PathBuf, /// If the total entries in validated + unvalidated ingress pool exceeds /// this threshold, reject the user HTTP request. If this field is not /// specified, throttling would be disabled. pub ingress_pool_size_threshold: Option<usize>, /// Choice of persistent pool backend database. None means default choice, /// which at the moment is "lmdb". #[serde(skip_serializing_if = "Option::is_none")] pub consensus_pool_backend: Option<String>, /// Path to a folder with write permissions, for consensus artifact backup. /// If no path was provided, no backup will be saved. #[serde(skip_serializing_if = "Option::is_none")] pub backup: Option<BackupConfig>, } impl ArtifactPoolTomlConfig { /// Create a ArtifactPoolTomlConfig from a given path to the consensus pool. pub fn new(consensus_pool_path: PathBuf, backup: Option<BackupConfig>) -> Self { Self { consensus_pool_path, ingress_pool_size_threshold: None, consensus_pool_backend: Some("lmdb".to_string()), backup, } } } /// Configuration of the consensus artifact backup. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct BackupConfig { /// Path to a folder with write permissions, for consensus artifact backup. /// If no path was provided, no backup will be saved. pub spool_path: PathBuf, /// The maximum age backup artifacts can reach before purging. pub retention_time_secs: u64, /// Time interval between purges. pub purging_interval_secs: u64, } /// The configuration for the ingress and consensus artifact pools, both the /// validated and unvalidated portions. #[derive(Clone, Debug)] pub struct ArtifactPoolConfig { /// The maximum size, in number of messages, of the validated section /// of the ingress pool. pub ingress_pool_validated_capacity: usize, /// The maximum size, in number of messages, of the unvalidated section /// of the ingress pool, per peer. pub ingress_pool_unvalidated_capacity_per_peer: usize, /// Threshold for ingress rate limiting. If this field is not /// specified, throttling would be disabled. pub ingress_pool_size_threshold: Option<usize>, /// The maximum size, in number of messages, of the unvalidated section /// of the artifact pool, per peer. pub consensus_pool_unvalidated_capacity_per_peer: usize, /// The maximum size, in number of messages, of the validated section /// of the artifact pool. pub consensus_pool_validated_capacity: usize, /// Choice of persistent pool backend pub persistent_pool_backend: PersistentPoolBackend, /// Whether the persistent pool should be opened as read-only pub persistent_pool_read_only: bool, /// Contains all parameters for the consensus artifact backup. pub backup_config: Option<BackupConfig>, } /// Choice of persistent pool database is either LMDB or RocksDB. #[derive(Clone, Debug)] pub enum PersistentPoolBackend { Lmdb(LMDBConfig), RocksDB(RocksDBConfig), } /// LMDB specific configuration #[derive(Clone, Debug)] pub struct LMDBConfig { /// The path at which the validated section of the persistent pool is /// stored. pub persistent_pool_validated_persistent_db_path: PathBuf, } /// RocksDB specific configuration #[derive(Clone, Debug)] pub struct RocksDBConfig { /// Whether the validated section on the artifact pool, which is persistent /// should skips fsync calls, for tests. /// /// NOTE: This nullifies all durability guarantees and thus should /// only be used in tests. pub persistent_pool_validated_skip_fsync_for_tests: bool, /// The path at which the validated section of the persistent pool is /// stored. pub persistent_pool_validated_persistent_db_path: PathBuf, /// Consensus pool is purged at a fixed interval. pub persistent_pool_validated_purge_interval: Height, } impl From<ArtifactPoolTomlConfig> for ArtifactPoolConfig { fn from(toml_config: ArtifactPoolTomlConfig) -> ArtifactPoolConfig { let backend = toml_config .consensus_pool_backend .unwrap_or_else(|| "lmdb".to_string()); let persistent_pool_backend = match backend.as_str() { "lmdb" => PersistentPoolBackend::Lmdb(LMDBConfig { persistent_pool_validated_persistent_db_path: toml_config.consensus_pool_path, }), "rocksdb" => PersistentPoolBackend::RocksDB(RocksDBConfig { persistent_pool_validated_skip_fsync_for_tests: false, persistent_pool_validated_persistent_db_path: toml_config.consensus_pool_path, persistent_pool_validated_purge_interval: Height::from( PERSISTENT_POOL_VALIDATED_PURGE_INTERVAL, ), }), _ => { panic!("Unsupported persistent_pool_backend: {}, must be either \"lmdb\" or \"rocksdb\".", backend); } }; ArtifactPoolConfig { ingress_pool_validated_capacity: MAX_INGRESS_POOL_VALIDATED_CAPACITY, ingress_pool_unvalidated_capacity_per_peer: MAX_INGRESS_POOL_UNVALIDATED_CAPACITY_PER_PEER, ingress_pool_size_threshold: toml_config.ingress_pool_size_threshold, consensus_pool_unvalidated_capacity_per_peer: MAX_CONSENSUS_POOL_VALIDATED_CAPACITY, consensus_pool_validated_capacity: MAX_CONSENSUS_POOL_UNVALIDATED_CAPACITY_PER_PEER, persistent_pool_backend, persistent_pool_read_only: false, backup_config: toml_config.backup, } } } impl ArtifactPoolConfig { pub fn new(consensus_pool_path: PathBuf) -> ArtifactPoolConfig { Self::from(ArtifactPoolTomlConfig::new(consensus_pool_path, None)) } /// Return the directory path to the persistent pool database. pub fn persistent_pool_db_path(&self) -> PathBuf { match &self.persistent_pool_backend { PersistentPoolBackend::Lmdb(config) => { config.persistent_pool_validated_persistent_db_path.clone() } PersistentPoolBackend::RocksDB(config) => { config.persistent_pool_validated_persistent_db_path.clone() } } } }
42.439306
116
0.713293
5d74ffadbe54f42ee695e9b369e5d89b6c4e885a
599
use std::{fmt, str::FromStr}; use serde::de::{self, Visitor}; use crate::config::AssetSlug; /// Visitor to deserialize an `AssetSlug` from a string. #[derive(Debug)] pub struct AssetSlugVisitor; impl<'de> Visitor<'de> for AssetSlugVisitor { type Value = AssetSlug; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("an asset slug such as `default/fireball`") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { AssetSlug::from_str(value).map_err(de::Error::custom) } }
23.96
72
0.644407
de5958a9795bfd5449c6f542618baddffbc9ecf4
2,307
//! Additional SRP types. use crate::tools::powm; use digest::Digest; use num_bigint::BigUint; use std::{error, fmt}; /// SRP authentication error. #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct SrpAuthError { pub(crate) description: &'static str, } impl fmt::Display for SrpAuthError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "SRP authentication error") } } impl error::Error for SrpAuthError { fn description(&self) -> &str { self.description } } /// Group used for SRP computations #[derive(Debug, Clone, Eq, PartialEq)] pub struct SrpGroup { /// A large safe prime (N = 2q+1, where q is prime) pub n: BigUint, /// A generator modulo N pub g: BigUint, } impl SrpGroup { pub(crate) fn powm(&self, v: &BigUint) -> BigUint { powm(&self.g, v, &self.n) } /// Compute `k` with given hash function and return SRP parameters pub(crate) fn compute_k<D: Digest>(&self) -> BigUint { let n = self.n.to_bytes_be(); let g_bytes = self.g.to_bytes_be(); let mut buf = vec![0u8; n.len()]; let l = n.len() - g_bytes.len(); buf[l..].copy_from_slice(&g_bytes); let mut d = D::new(); d.update(&n); d.update(&buf); BigUint::from_bytes_be(&d.finalize().as_slice()) } /// Compute `Hash(N) xor Hash(g)` with given hash function and return SRP parameters pub(crate) fn compute_hash_n_xor_hash_g<D: Digest>(&self) -> Vec<u8> { let n = self.n.to_bytes_be(); let g_bytes = self.g.to_bytes_be(); let mut buf = vec![0u8; n.len()]; let l = n.len() - g_bytes.len(); buf[l..].copy_from_slice(&g_bytes); let mut d = D::new(); d.update(&n); let h = d.finalize_reset(); let h_n: &[u8] = h.as_slice(); d.update(&buf); let h = d.finalize_reset(); let h_g: &[u8] = h.as_slice(); h_n.iter() .zip(h_g.iter()) .map(|(&x1, &x2)| x1 ^ x2) .collect() } } #[cfg(test)] mod tests { use crate::groups::G_1024; use sha1::Sha1; #[test] fn test_k_1024_sha1() { let k = G_1024.compute_k::<Sha1>().to_bytes_be(); assert_eq!(&k, include_bytes!("k_sha1_1024.bin")); } }
26.517241
88
0.56567
8faf3a3d50c191b175038152b32970790818feb5
1,401
use std::cell::UnsafeCell; use std::fs::File; use std::io::{BufRead, BufReader, Read}; pub struct ReadsReader { reader: UnsafeCell<Box<dyn Read>>, } unsafe impl Send for ReadsReader {} unsafe impl Sync for ReadsReader {} trait UnsafeCellGetMutable { type Output; #[allow(clippy::mut_from_ref)] fn uget(&self) -> &mut Self::Output; } impl<T> UnsafeCellGetMutable for UnsafeCell<T> { type Output = T; fn uget(&self) -> &mut Self::Output { unsafe { &mut *self.get() } } } struct RefThreadWrapper<'a, T: ?Sized>(&'a mut T); unsafe impl<'a, T: ?Sized> Sync for RefThreadWrapper<'a, T> {} unsafe impl<'a, T: ?Sized> Send for RefThreadWrapper<'a, T> {} impl ReadsReader { pub fn from_file(name: String) -> ReadsReader { let is_compressed = name.ends_with(".lz4"); let file = File::open(name).unwrap(); let reader: Box<dyn Read> = if is_compressed { let decoder = lz4::Decoder::new(file).unwrap(); Box::new(decoder) } else { Box::new(file) }; ReadsReader { reader: UnsafeCell::new(reader), } } pub fn for_each<F: FnMut(&[u8])>(&self, mut func: F) { let mut reader_cell = self.reader.uget(); let reader = BufReader::new(reader_cell); for line in reader.lines() { func(line.unwrap().as_bytes()); } } }
25.944444
62
0.588865
f7e7cf63d4c76dd593508ef387c55d79cc02cdcc
6,753
// Copyright 2019 The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use std::{sync::Arc, time::Duration}; use tari_comms::peer_manager::NodeId; use tari_service_framework::reply_channel::SenderService; use tokio::sync::broadcast; use tower::Service; use super::{error::LivenessError, state::Metadata}; use crate::proto::liveness::MetadataKey; /// Request types made through the `LivenessHandle` and are handled by the `LivenessService` #[derive(Debug, Clone)] pub enum LivenessRequest { /// Send a ping to the given node ID SendPing(NodeId), /// Retrieve the total number of pings received GetPingCount, /// Retrieve the total number of pongs received GetPongCount, /// Get average latency for node ID GetAvgLatency(NodeId), /// Get average latency for all connected nodes GetNetworkAvgLatency, /// Set the metadata attached to each ping/pong message SetMetadataEntry(MetadataKey, Vec<u8>), } /// Response type for `LivenessService` #[derive(Debug)] pub enum LivenessResponse { /// Indicates that the request succeeded Ok, /// Used to return a counter value from `GetPingCount` and `GetPongCount` Count(usize), /// Response for GetAvgLatency and GetNetworkAvgLatency AvgLatency(Option<Duration>), /// The number of active neighbouring peers NumActiveNeighbours(usize), } #[derive(Clone, Debug, PartialEq, Eq)] pub enum LivenessEvent { /// A ping was received ReceivedPing(Box<PingPongEvent>), /// A pong was received. The latency to the peer (if available) and the metadata contained /// within the received pong message are included as part of the event ReceivedPong(Box<PingPongEvent>), /// A round of pings was broadcast to random and monitored peers PingRoundBroadcast(usize), } /// Represents a ping or pong event #[derive(Clone, Debug, PartialEq, Eq)] pub struct PingPongEvent { /// The node id of the node which sent this ping or pong pub node_id: NodeId, /// Latency if available (i.e. a corresponding event was sent within the Liveness state inflight ping TTL) pub latency: Option<Duration>, /// Metadata of the corresponding node pub metadata: Metadata, } impl PingPongEvent { pub fn new(node_id: NodeId, latency: Option<Duration>, metadata: Metadata) -> Self { Self { node_id, latency, metadata, } } } pub type LivenessEventSender = broadcast::Sender<Arc<LivenessEvent>>; pub type LivenessEventReceiver = broadcast::Receiver<Arc<LivenessEvent>>; #[derive(Clone)] pub struct LivenessHandle { handle: SenderService<LivenessRequest, Result<LivenessResponse, LivenessError>>, event_stream_sender: LivenessEventSender, } impl LivenessHandle { pub fn new( handle: SenderService<LivenessRequest, Result<LivenessResponse, LivenessError>>, event_stream_sender: LivenessEventSender, ) -> Self { Self { handle, event_stream_sender, } } /// Returns an event stream for the liveness service pub fn get_event_stream(&self) -> LivenessEventReceiver { self.event_stream_sender.subscribe() } /// Send a ping to a given node ID pub async fn send_ping(&mut self, node_id: NodeId) -> Result<(), LivenessError> { match self.handle.call(LivenessRequest::SendPing(node_id)).await?? { LivenessResponse::Ok => Ok(()), _ => Err(LivenessError::UnexpectedApiResponse), } } /// Retrieve the global ping count pub async fn get_ping_count(&mut self) -> Result<usize, LivenessError> { match self.handle.call(LivenessRequest::GetPingCount).await?? { LivenessResponse::Count(c) => Ok(c), _ => Err(LivenessError::UnexpectedApiResponse), } } /// Retrieve the global pong count pub async fn get_pong_count(&mut self) -> Result<usize, LivenessError> { match self.handle.call(LivenessRequest::GetPongCount).await?? { LivenessResponse::Count(c) => Ok(c), _ => Err(LivenessError::UnexpectedApiResponse), } } /// Set metadata entry for the pong message pub async fn set_metadata_entry(&mut self, key: MetadataKey, value: Vec<u8>) -> Result<(), LivenessError> { match self .handle .call(LivenessRequest::SetMetadataEntry(key, value)) .await?? { LivenessResponse::Ok => Ok(()), _ => Err(LivenessError::UnexpectedApiResponse), } } /// Retrieve the average latency for a given node pub async fn get_avg_latency(&mut self, node_id: NodeId) -> Result<Option<Duration>, LivenessError> { match self.handle.call(LivenessRequest::GetAvgLatency(node_id)).await?? { LivenessResponse::AvgLatency(v) => Ok(v), _ => Err(LivenessError::UnexpectedApiResponse), } } /// Retrieve the mean average latency for all connected nodes pub async fn get_network_avg_latency(&mut self) -> Result<Option<Duration>, LivenessError> { match self.handle.call(LivenessRequest::GetNetworkAvgLatency).await?? { LivenessResponse::AvgLatency(v) => Ok(v), _ => Err(LivenessError::UnexpectedApiResponse), } } }
39.261628
118
0.694358
3a0cb75ed152ddd7bad1444ebf066ae122ae1e64
2,476
// run-pass // run-rustfix fn main() { let small = [1, 2]; let big = [0u8; 33]; // Expressions that should trigger the lint small.into_iter(); //~^ WARNING this method call currently resolves to `<&[T; N] as IntoIterator>::into_iter` //~| WARNING this changes meaning [1, 2].into_iter(); //~^ WARNING this method call currently resolves to `<&[T; N] as IntoIterator>::into_iter` //~| WARNING this changes meaning big.into_iter(); //~^ WARNING this method call currently resolves to `<&[T; N] as IntoIterator>::into_iter` //~| WARNING this changes meaning [0u8; 33].into_iter(); //~^ WARNING this method call currently resolves to `<&[T; N] as IntoIterator>::into_iter` //~| WARNING this changes meaning Box::new(small).into_iter(); //~^ WARNING this method call currently resolves to `<&[T; N] as IntoIterator>::into_iter` //~| WARNING this changes meaning Box::new([1, 2]).into_iter(); //~^ WARNING this method call currently resolves to `<&[T; N] as IntoIterator>::into_iter` //~| WARNING this changes meaning Box::new(big).into_iter(); //~^ WARNING this method call currently resolves to `<&[T; N] as IntoIterator>::into_iter` //~| WARNING this changes meaning Box::new([0u8; 33]).into_iter(); //~^ WARNING this method call currently resolves to `<&[T; N] as IntoIterator>::into_iter` //~| WARNING this changes meaning Box::new(Box::new(small)).into_iter(); //~^ WARNING this method call currently resolves to `<&[T; N] as IntoIterator>::into_iter` //~| WARNING this changes meaning Box::new(Box::new([1, 2])).into_iter(); //~^ WARNING this method call currently resolves to `<&[T; N] as IntoIterator>::into_iter` //~| WARNING this changes meaning Box::new(Box::new(big)).into_iter(); //~^ WARNING this method call currently resolves to `<&[T; N] as IntoIterator>::into_iter` //~| WARNING this changes meaning Box::new(Box::new([0u8; 33])).into_iter(); //~^ WARNING this method call currently resolves to `<&[T; N] as IntoIterator>::into_iter` //~| WARNING this changes meaning // Expressions that should not (&[1, 2]).into_iter(); (&small).into_iter(); (&[0u8; 33]).into_iter(); (&big).into_iter(); for _ in &[1, 2] {} (&small as &[_]).into_iter(); small[..].into_iter(); std::iter::IntoIterator::into_iter(&[1, 2]); #[allow(array_into_iter)] [0, 1].into_iter(); }
39.935484
94
0.629645
7a1516654fbc0fb496fe75f54b48349e4a8c74fd
2,478
#![cfg_attr(not(feature = "std"), no_std)] use codec::{Encode, Decode}; use frame_support::{ decl_module, decl_storage, decl_event, decl_error, StorageValue, StorageDoubleMap, traits::Randomness, RuntimeDebug, dispatch::{DispatchResult }, }; use sp_io::hashing::blake2_128; use frame_system::ensure_signed; #[cfg(test)] mod tests; #[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq)] pub struct Kitty(pub [u8; 16]); #[derive(Encode, Decode, Clone, Copy, RuntimeDebug, PartialEq, Eq)] pub enum KittyGender { Male, Female, } impl Kitty { pub fn gender(&self) -> KittyGender { if self.0[0] % 2 == 0 { KittyGender::Male } else { KittyGender::Female } } } pub trait Trait: frame_system::Trait { type Event: From<Event<Self>> + Into<<Self as frame_system::Trait>::Event>; } decl_storage! { trait Store for Module<T: Trait> as Kitties { /// Stores all the kitties, key is the kitty id pub Kitties get(fn kitties): double_map hasher(blake2_128_concat) T::AccountId, hasher(blake2_128_concat) u32 => Option<Kitty>; /// Stores the next kitty ID pub NextKittyId get(fn next_kitty_id): u32; } } decl_event! { pub enum Event<T> where <T as frame_system::Trait>::AccountId, { /// A kitty is created. \[owner, kitty_id, kitty\] KittyCreated(AccountId, u32, Kitty), /// A new kitten is bred. \[owner, kitty_id, kitty\] KittyBred(AccountId, u32, Kitty), } } decl_error! { pub enum Error for Module<T: Trait> { KittiesIdOverflow, InvalidKittyId, SameGender, } } decl_module! { pub struct Module<T: Trait> for enum Call where origin: T::Origin { type Error = Error<T>; fn deposit_event() = default; /// Create a new kitty #[weight = 1000] pub fn create(origin) { let sender = ensure_signed(origin)?; NextKittyId::try_mutate(|next_id| -> DispatchResult { let current_id = *next_id; *next_id = next_id.checked_add(1).ok_or(Error::<T>::KittiesIdOverflow)?; let payload = ( <pallet_randomness_collective_flip::Module<T> as Randomness<T::Hash>>::random_seed(), &sender, <frame_system::Module<T>>::extrinsic_index(), ); let dna = payload.using_encoded(blake2_128); // Create and store kitty let kitty = Kitty(dna); Kitties::<T>::insert(&sender, current_id, kitty.clone()); // Emit event Self::deposit_event(RawEvent::KittyCreated(sender, current_id, kitty)); Ok(()) })?; } } } pub fn combine_dna(dna1: u8, dna2: u8, selector: u8) -> u8 { 0 }
24.058252
129
0.677563
267c0381ccf1472e0b592ca2c7b67ad1d6d6b4aa
8,089
// Copyright (c) 2017 The vulkano developers // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or https://opensource.org/licenses/MIT>, // at your option. All files in the project carrying such // notice may not be copied, modified, or distributed except // according to those terms. use crate::descriptor_set::layout::DescriptorSetLayout; use crate::descriptor_set::pool::{ DescriptorPoolAlloc, DescriptorPoolAllocError, DescriptorSetAllocateInfo, UnsafeDescriptorPool, }; use crate::descriptor_set::update::WriteDescriptorSet; use crate::descriptor_set::{ DescriptorSet, DescriptorSetCreationError, DescriptorSetInner, DescriptorSetResources, UnsafeDescriptorSet, }; use crate::device::{Device, DeviceOwned}; use crate::OomError; use crate::VulkanObject; use crossbeam_queue::SegQueue; use std::hash::{Hash, Hasher}; use std::sync::Arc; /// `SingleLayoutDescSetPool` is a convenience wrapper provided by Vulkano not to be confused with /// `VkDescriptorPool`. Its function is to provide access to pool(s) to allocate `DescriptorSet`'s /// from and optimizes for a specific layout. For a more general purpose pool see `descriptor_set::pool::StdDescriptorPool`. pub struct SingleLayoutDescSetPool { // The `SingleLayoutPool` struct contains an actual Vulkan pool. Every time it is full we create // a new pool and replace the current one with the new one. inner: Option<Arc<SingleLayoutPool>>, // The Vulkan device. device: Arc<Device>, // The amount of sets available to use when we create a new Vulkan pool. set_count: usize, // The descriptor layout that this pool is for. layout: Arc<DescriptorSetLayout>, } impl SingleLayoutDescSetPool { /// Initializes a new pool. The pool is configured to allocate sets that corresponds to the /// parameters passed to this function. /// /// # Panics /// /// - Panics if the provided `layout` is for push descriptors rather than regular descriptor /// sets. /// - Panics if the provided `layout` has a binding with a variable descriptor count. pub fn new(layout: Arc<DescriptorSetLayout>) -> Self { assert!( !layout.desc().is_push_descriptor(), "the provided descriptor set layout is for push descriptors, and cannot be used to build a descriptor set object" ); assert!( layout.variable_descriptor_count() == 0, "the provided descriptor set layout has a binding with a variable descriptor count, which cannot be used with SingleLayoutDescSetPool" ); Self { inner: None, device: layout.device().clone(), set_count: 4, layout, } } /// Returns a new descriptor set, either by creating a new one or returning an existing one /// from the internal reserve. #[inline] pub fn next( &mut self, descriptor_writes: impl IntoIterator<Item = WriteDescriptorSet>, ) -> Result<Arc<SingleLayoutDescSet>, DescriptorSetCreationError> { let alloc = self.next_alloc()?; let inner = DescriptorSetInner::new( alloc.inner().internal_object(), self.layout.clone(), 0, descriptor_writes, )?; Ok(Arc::new(SingleLayoutDescSet { alloc, inner })) } fn next_alloc(&mut self) -> Result<SingleLayoutPoolAlloc, OomError> { loop { let mut not_enough_sets = false; if let Some(ref mut p_inner) = self.inner { if let Some(existing) = p_inner.reserve.pop() { return Ok(SingleLayoutPoolAlloc { pool: p_inner.clone(), inner: Some(existing), }); } else { not_enough_sets = true; } } if not_enough_sets { self.set_count *= 2; } let count = *self.layout.descriptors_count() * self.set_count as u32; let mut unsafe_pool = UnsafeDescriptorPool::new( self.device.clone(), &count, self.set_count as u32, false, )?; let reserve = unsafe { match unsafe_pool.alloc((0..self.set_count).map(|_| DescriptorSetAllocateInfo { layout: self.layout.as_ref(), variable_descriptor_count: 0, })) { Ok(alloc_iter) => { let reserve = SegQueue::new(); for alloc in alloc_iter { reserve.push(alloc); } reserve } Err(DescriptorPoolAllocError::OutOfHostMemory) => { return Err(OomError::OutOfHostMemory); } Err(DescriptorPoolAllocError::OutOfDeviceMemory) => { return Err(OomError::OutOfDeviceMemory); } Err(DescriptorPoolAllocError::FragmentedPool) => { // This can't happen as we don't free individual sets. unreachable!() } Err(DescriptorPoolAllocError::OutOfPoolMemory) => unreachable!(), } }; self.inner = Some(Arc::new(SingleLayoutPool { inner: unsafe_pool, reserve, })); } } } struct SingleLayoutPool { // The actual Vulkan descriptor pool. This field isn't actually used anywhere, but we need to // keep the pool alive in order to keep the descriptor sets valid. inner: UnsafeDescriptorPool, // List of descriptor sets. When `alloc` is called, a descriptor will be extracted from this // list. When a `SingleLayoutPoolAlloc` is dropped, its descriptor set is put back in this list. reserve: SegQueue<UnsafeDescriptorSet>, } struct SingleLayoutPoolAlloc { // The `SingleLayoutPool` were we allocated from. We need to keep a copy of it in each allocation // so that we can put back the allocation in the list in our `Drop` impl. pool: Arc<SingleLayoutPool>, // The actual descriptor set, wrapped inside an `Option` so that we can extract it in our // `Drop` impl. inner: Option<UnsafeDescriptorSet>, } impl DescriptorPoolAlloc for SingleLayoutPoolAlloc { #[inline] fn inner(&self) -> &UnsafeDescriptorSet { self.inner.as_ref().unwrap() } #[inline] fn inner_mut(&mut self) -> &mut UnsafeDescriptorSet { self.inner.as_mut().unwrap() } } impl Drop for SingleLayoutPoolAlloc { fn drop(&mut self) { let inner = self.inner.take().unwrap(); self.pool.reserve.push(inner); } } /// A descriptor set created from a `SingleLayoutDescSetPool`. pub struct SingleLayoutDescSet { alloc: SingleLayoutPoolAlloc, inner: DescriptorSetInner, } unsafe impl DescriptorSet for SingleLayoutDescSet { #[inline] fn inner(&self) -> &UnsafeDescriptorSet { self.alloc.inner() } #[inline] fn layout(&self) -> &Arc<DescriptorSetLayout> { self.inner.layout() } #[inline] fn resources(&self) -> &DescriptorSetResources { self.inner.resources() } } unsafe impl DeviceOwned for SingleLayoutDescSet { #[inline] fn device(&self) -> &Arc<Device> { self.inner.layout().device() } } impl PartialEq for SingleLayoutDescSet { #[inline] fn eq(&self, other: &Self) -> bool { self.inner().internal_object() == other.inner().internal_object() && self.device() == other.device() } } impl Eq for SingleLayoutDescSet {} impl Hash for SingleLayoutDescSet { #[inline] fn hash<H: Hasher>(&self, state: &mut H) { self.inner().internal_object().hash(state); self.device().hash(state); } }
34.421277
146
0.607863
09f1bf8d46a5d672e53144df784f440edcae1b8a
7,241
use crate::common::IteratorJoin; use std::{borrow::Cow, fmt::Display, todo}; #[derive(Debug, Default)] pub struct AlterTable<'a> { pub table_name: PostgresIdentifier<'a>, pub clauses: Vec<AlterTableClause<'a>>, } impl Display for AlterTable<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("ALTER TABLE ")?; self.table_name.fmt(f)?; if self.clauses.len() <= 1 { f.write_str(" ")?; self.clauses[0].fmt(f)?; } else { todo!("multiline ALTER TABLE") } Ok(()) } } #[derive(Debug)] pub enum AlterTableClause<'a> { AddForeignKey(ForeignKey<'a>), } impl Display for AlterTableClause<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { AlterTableClause::AddForeignKey(fk) => { f.write_str("ADD ")?; fk.fmt(f) } } } } #[derive(Debug)] pub struct ForeignKey<'a> { pub constraint_name: Option<Cow<'a, str>>, pub constrained_columns: Vec<Cow<'a, str>>, pub referenced_table: Cow<'a, str>, pub referenced_columns: Vec<Cow<'a, str>>, pub on_delete: Option<ForeignKeyAction>, pub on_update: Option<ForeignKeyAction>, } impl Display for ForeignKey<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if let Some(constraint_name) = &self.constraint_name { write!( f, "CONSTRAINT \"{constraint_name}\" ", constraint_name = constraint_name, )?; } f.write_str("FOREIGN KEY (")?; self.constrained_columns.iter().map(|s| Ident(s)).join(", ", f)?; write!(f, ") REFERENCES \"{}\"(", self.referenced_table)?; self.referenced_columns.iter().map(|s| Ident(s)).join(", ", f)?; f.write_str(")")?; if let Some(on_delete) = &self.on_delete { f.write_str(" ON DELETE ")?; on_delete.fmt(f)?; } if let Some(on_update) = &self.on_update { f.write_str(" ON UPDATE ")?; on_update.fmt(f)?; } Ok(()) } } #[derive(Debug)] pub enum ForeignKeyAction { Cascade, DoNothing, Restrict, SetDefault, SetNull, } impl Display for ForeignKeyAction { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let s = match self { ForeignKeyAction::Cascade => "CASCADE", ForeignKeyAction::Restrict => "RESTRICT", ForeignKeyAction::DoNothing => "DO NOTHING", ForeignKeyAction::SetNull => "SET NULL", ForeignKeyAction::SetDefault => "SET DEFAULT", }; f.write_str(s) } } #[derive(Debug)] pub enum PostgresIdentifier<'a> { Simple(Cow<'a, str>), WithSchema(Cow<'a, str>, Cow<'a, str>), } impl Default for PostgresIdentifier<'_> { fn default() -> Self { PostgresIdentifier::Simple(Cow::Borrowed("")) } } impl<'a> From<&'a str> for PostgresIdentifier<'a> { fn from(s: &'a str) -> Self { PostgresIdentifier::Simple(Cow::Borrowed(s)) } } struct StrLit<'a>(&'a str); impl Display for StrLit<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "'{}'", self.0)?; Ok(()) } } struct Ident<'a>(&'a str); impl Display for Ident<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "\"{}\"", self.0)?; Ok(()) } } impl<'a> From<(&'a str, &'a str)> for PostgresIdentifier<'a> { fn from((schema, item): (&'a str, &'a str)) -> Self { PostgresIdentifier::WithSchema(Cow::Borrowed(schema), Cow::Borrowed(item)) } } impl<'a> Display for PostgresIdentifier<'a> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { PostgresIdentifier::Simple(ident) => write!(f, "\"{}\"", ident), PostgresIdentifier::WithSchema(schema_name, ident) => write!(f, "\"{}\".\"{}\"", schema_name, ident), } } } pub struct CreateEnum<'a> { pub enum_name: PostgresIdentifier<'a>, pub variants: Vec<Cow<'a, str>>, } impl<'a> Display for CreateEnum<'a> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "CREATE TYPE {enum_name} AS ENUM (", enum_name = self.enum_name)?; self.variants.iter().map(|s| StrLit(s)).join(", ", f)?; f.write_str(")") } } pub struct CreateIndex<'a> { pub index_name: PostgresIdentifier<'a>, pub is_unique: bool, pub table_reference: PostgresIdentifier<'a>, pub columns: Vec<Cow<'a, str>>, } impl<'a> Display for CreateIndex<'a> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "CREATE {uniqueness}INDEX {index_name} ON {table_reference}(", uniqueness = if self.is_unique { "UNIQUE " } else { "" }, index_name = self.index_name, table_reference = self.table_reference, )?; self.columns.iter().map(|s| Ident(s)).join(", ", f)?; f.write_str(")") } } #[cfg(test)] mod tests { use super::*; #[test] fn create_enum_without_variants() { let create_enum = CreateEnum { enum_name: "myEnum".into(), variants: Vec::new(), }; assert_eq!(create_enum.to_string(), r#"CREATE TYPE "myEnum" AS ENUM ()"#); } #[test] fn create_enum_with_variants() { let variants = vec!["One".into(), "Two".into(), "Three".into()]; let create_enum = CreateEnum { enum_name: "myEnum".into(), variants, }; assert_eq!( create_enum.to_string(), r#"CREATE TYPE "myEnum" AS ENUM ('One', 'Two', 'Three')"# ); } #[test] fn create_unique_index() { let columns = vec!["name".into(), "age".into()]; let create_index = CreateIndex { is_unique: true, index_name: "meow_idx".into(), table_reference: "Cat".into(), columns, }; assert_eq!( create_index.to_string(), "CREATE UNIQUE INDEX \"meow_idx\" ON \"Cat\"(\"name\", \"age\")" ) } #[test] fn full_alter_table_add_foreign_key() { let alter_table = AlterTable { table_name: PostgresIdentifier::WithSchema("public".into(), "Cat".into()), clauses: vec![AlterTableClause::AddForeignKey(ForeignKey { constrained_columns: vec!["friendName".into(), "friendTemperament".into()], constraint_name: Some("cat_friend".into()), on_delete: None, on_update: None, referenced_columns: vec!["name".into(), "temperament".into()], referenced_table: "Dog".into(), })], }; let expected = "ALTER TABLE \"public\".\"Cat\" ADD CONSTRAINT \"cat_friend\" FOREIGN KEY (\"friendName\", \"friendTemperament\") REFERENCES \"Dog\"(\"name\", \"temperament\")"; assert_eq!(alter_table.to_string(), expected); } }
27.743295
173
0.543295
91b3ffc35a6df07f5d403fdbc24ac05ef5dedd72
5,186
/* * Copyright (c) 2017-2020 Boucher, Antoni <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use gtk::{ Button, ButtonExt, ContainerExt, Inhibit, Label, LabelExt, WidgetExt, Window, WindowType, }; use gtk::Orientation::Vertical; use relm_derive::Msg; use relm::{connect, Relm, Update, Widget, WidgetTest}; struct Model { counter: i32, } #[derive(Msg)] enum Msg { Decrement, Increment, Quit, } // Create the structure that holds the widgets used in the view. #[derive(Clone)] struct Widgets { counter_label: Label, minus_button: Button, plus_button: Button, window: Window, } struct Win { model: Model, widgets: Widgets, } impl Update for Win { // Specify the model used for this widget. type Model = Model; // Specify the model parameter used to init the model. type ModelParam = (); // Specify the type of the messages sent to the update function. type Msg = Msg; fn model(_: &Relm<Self>, _: ()) -> Model { Model { counter: 0, } } fn update(&mut self, event: Msg) { let label = &self.widgets.counter_label; match event { Msg::Decrement => { self.model.counter -= 1; // Manually update the view. label.set_text(&self.model.counter.to_string()); }, Msg::Increment => { self.model.counter += 1; label.set_text(&self.model.counter.to_string()); }, Msg::Quit => gtk::main_quit(), } } } impl Widget for Win { // Specify the type of the root widget. type Root = Window; // Return the root widget. fn root(&self) -> Self::Root { self.widgets.window.clone() } fn view(relm: &Relm<Self>, model: Self::Model) -> Self { // Create the view using the normal GTK+ method calls. let vbox = gtk::Box::new(Vertical, 0); let plus_button = Button::with_label("+"); vbox.add(&plus_button); let counter_label = Label::new(Some("0")); vbox.add(&counter_label); let minus_button = Button::with_label("-"); vbox.add(&minus_button); let window = Window::new(WindowType::Toplevel); window.add(&vbox); window.show_all(); // Send the message Increment when the button is clicked. connect!(relm, plus_button, connect_clicked(_), Msg::Increment); connect!(relm, minus_button, connect_clicked(_), Msg::Decrement); connect!(relm, window, connect_delete_event(_, _), return (Some(Msg::Quit), Inhibit(false))); Win { model, widgets: Widgets { counter_label, minus_button, plus_button, window: window, }, } } } impl WidgetTest for Win { type Streams = (); fn get_streams(&self) -> Self::Streams { } type Widgets = Widgets; fn get_widgets(&self) -> Self::Widgets { self.widgets.clone() } } fn main() { Win::run(()).expect("Win::run failed"); } #[cfg(test)] mod tests { use gtk::LabelExt; use gtk_test::assert_text; use relm_test::click; use crate::Win; #[test] fn label_change() { let (_component, _, widgets) = relm::init_test::<Win>(()).expect("init_test failed"); let plus_button = &widgets.plus_button; let minus_button = &widgets.minus_button; let label = &widgets.counter_label; assert_text!(label, 0); click(plus_button); assert_text!(label, 1); click(plus_button); assert_text!(label, 2); click(plus_button); assert_text!(label, 3); click(plus_button); assert_text!(label, 4); click(minus_button); assert_text!(label, 3); click(minus_button); assert_text!(label, 2); click(minus_button); assert_text!(label, 1); click(minus_button); assert_text!(label, 0); click(minus_button); assert_text!(label, -1); } }
26.731959
101
0.606826
8a7e3f6992c5cfc6b9dc076b057d0cb325b9e1d5
6,015
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. // // @generated SignedSource<<98b3e35b22e84d28cc8cf37654b89e24>> // // To regenerate this file, run: // hphp/hack/src/oxidized_regen.sh #![allow(unused_variables)] use super::node::Node; use crate::{ aast_defs::*, ast_defs::*, direct_decl_parser::*, shallow_decl_defs::*, t_shape_map::*, typing_defs::*, typing_defs_core::*, typing_reason::*, }; pub trait Visitor<'a> { fn object(&mut self) -> &mut dyn Visitor<'a>; fn visit_arg_position(&mut self, p: &'a ArgPosition) { p.recurse(self.object()) } fn visit_blame(&mut self, p: &'a Blame<'a>) { p.recurse(self.object()) } fn visit_blame_source(&mut self, p: &'a BlameSource) { p.recurse(self.object()) } fn visit_capability(&mut self, p: &'a Capability<'a>) { p.recurse(self.object()) } fn visit_class_const_from(&mut self, p: &'a ClassConstFrom<'a>) { p.recurse(self.object()) } fn visit_class_const_ref(&mut self, p: &'a ClassConstRef<'a>) { p.recurse(self.object()) } fn visit_class_kind(&mut self, p: &'a ClassKind) { p.recurse(self.object()) } fn visit_collection_style(&mut self, p: &'a CollectionStyle) { p.recurse(self.object()) } fn visit_const_decl(&mut self, p: &'a ConstDecl<'a>) { p.recurse(self.object()) } fn visit_constraint_kind(&mut self, p: &'a ConstraintKind) { p.recurse(self.object()) } fn visit_decl(&mut self, p: &'a Decl<'a>) { p.recurse(self.object()) } fn visit_decls(&mut self, p: &'a Decls<'a>) { p.recurse(self.object()) } fn visit_dependent_type(&mut self, p: &'a DependentType) { p.recurse(self.object()) } fn visit_enforcement(&mut self, p: &'a Enforcement<'a>) { p.recurse(self.object()) } fn visit_enum_type(&mut self, p: &'a EnumType<'a>) { p.recurse(self.object()) } fn visit_exact(&mut self, p: &'a Exact) { p.recurse(self.object()) } fn visit_expr_dep_type_reason(&mut self, p: &'a ExprDepTypeReason<'a>) { p.recurse(self.object()) } fn visit_fun_arity(&mut self, p: &'a FunArity<'a>) { p.recurse(self.object()) } fn visit_fun_elt(&mut self, p: &'a FunElt<'a>) { p.recurse(self.object()) } fn visit_fun_implicit_params(&mut self, p: &'a FunImplicitParams<'a>) { p.recurse(self.object()) } fn visit_fun_kind(&mut self, p: &'a FunKind) { p.recurse(self.object()) } fn visit_fun_param(&mut self, p: &'a FunParam<'a>) { p.recurse(self.object()) } fn visit_fun_type(&mut self, p: &'a FunType<'a>) { p.recurse(self.object()) } fn visit_ifc_fun_decl(&mut self, p: &'a IfcFunDecl<'a>) { p.recurse(self.object()) } fn visit_pos_byte_string(&mut self, p: &'a PosByteString<'a>) { p.recurse(self.object()) } fn visit_pos_string(&mut self, p: &'a PosString<'a>) { p.recurse(self.object()) } fn visit_possibly_enforced_ty(&mut self, p: &'a PossiblyEnforcedTy<'a>) { p.recurse(self.object()) } fn visit_record_def_type(&mut self, p: &'a RecordDefType<'a>) { p.recurse(self.object()) } fn visit_record_field_req(&mut self, p: &'a RecordFieldReq) { p.recurse(self.object()) } fn visit_reify_kind(&mut self, p: &'a ReifyKind) { p.recurse(self.object()) } fn visit_shallow_class(&mut self, p: &'a ShallowClass<'a>) { p.recurse(self.object()) } fn visit_shallow_class_const(&mut self, p: &'a ShallowClassConst<'a>) { p.recurse(self.object()) } fn visit_shallow_method(&mut self, p: &'a ShallowMethod<'a>) { p.recurse(self.object()) } fn visit_shallow_prop(&mut self, p: &'a ShallowProp<'a>) { p.recurse(self.object()) } fn visit_shallow_typeconst(&mut self, p: &'a ShallowTypeconst<'a>) { p.recurse(self.object()) } fn visit_shape_field_type(&mut self, p: &'a ShapeFieldType<'a>) { p.recurse(self.object()) } fn visit_shape_kind(&mut self, p: &'a ShapeKind) { p.recurse(self.object()) } fn visit_tshape_field(&mut self, p: &'a TShapeField<'a>) { p.recurse(self.object()) } fn visit_t_(&mut self, p: &'a T_<'a>) { p.recurse(self.object()) } fn visit_taccess_type(&mut self, p: &'a TaccessType<'a>) { p.recurse(self.object()) } fn visit_tparam(&mut self, p: &'a Tparam<'a>) { p.recurse(self.object()) } fn visit_tprim(&mut self, p: &'a Tprim) { p.recurse(self.object()) } fn visit_tshape_field_name(&mut self, p: &'a TshapeFieldName<'a>) { p.recurse(self.object()) } fn visit_ty(&mut self, p: &'a Ty<'a>) { p.recurse(self.object()) } fn visit_ty_(&mut self, p: &'a Ty_<'a>) { p.recurse(self.object()) } fn visit_typeconst_abstract_kind(&mut self, p: &'a TypeconstAbstractKind<'a>) { p.recurse(self.object()) } fn visit_typedef_type(&mut self, p: &'a TypedefType<'a>) { p.recurse(self.object()) } fn visit_typedef_visibility(&mut self, p: &'a TypedefVisibility) { p.recurse(self.object()) } fn visit_user_attribute(&mut self, p: &'a UserAttribute<'a>) { p.recurse(self.object()) } fn visit_variance(&mut self, p: &'a Variance) { p.recurse(self.object()) } fn visit_visibility(&mut self, p: &'a Visibility) { p.recurse(self.object()) } fn visit_where_constraint(&mut self, p: &'a WhereConstraint<'a>) { p.recurse(self.object()) } fn visit_xhp_attr(&mut self, p: &'a XhpAttr) { p.recurse(self.object()) } fn visit_xhp_attr_tag(&mut self, p: &'a XhpAttrTag) { p.recurse(self.object()) } }
33.049451
91
0.591355
11365a284b2ad964e813ae4f2b12931b18a07d40
68,786
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(clippy::unnecessary_wraps)] pub fn parse_add_tags_to_certificate_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::AddTagsToCertificateOutput, crate::error::AddTagsToCertificateError, > { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::AddTagsToCertificateError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => return Err(crate::error::AddTagsToCertificateError::unhandled(generic)), }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "InvalidArnException" => crate::error::AddTagsToCertificateError { meta: generic, kind: crate::error::AddTagsToCertificateErrorKind::InvalidArnException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::invalid_arn_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_invalid_arn_exception_json_err(response.body().as_ref(), output).map_err(crate::error::AddTagsToCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "InvalidParameterException" => crate::error::AddTagsToCertificateError { meta: generic, kind: crate::error::AddTagsToCertificateErrorKind::InvalidParameterException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::invalid_parameter_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_invalid_parameter_exception_json_err(response.body().as_ref(), output).map_err(crate::error::AddTagsToCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "InvalidTagException" => crate::error::AddTagsToCertificateError { meta: generic, kind: crate::error::AddTagsToCertificateErrorKind::InvalidTagException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::invalid_tag_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_invalid_tag_exception_json_err(response.body().as_ref(), output).map_err(crate::error::AddTagsToCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ResourceNotFoundException" => crate::error::AddTagsToCertificateError { meta: generic, kind: crate::error::AddTagsToCertificateErrorKind::ResourceNotFoundException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::resource_not_found_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::AddTagsToCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "TagPolicyException" => crate::error::AddTagsToCertificateError { meta: generic, kind: crate::error::AddTagsToCertificateErrorKind::TagPolicyException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::tag_policy_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_tag_policy_exception_json_err(response.body().as_ref(), output).map_err(crate::error::AddTagsToCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ThrottlingException" => crate::error::AddTagsToCertificateError { meta: generic, kind: crate::error::AddTagsToCertificateErrorKind::ThrottlingException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::throttling_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_throttling_exception_json_err(response.body().as_ref(), output).map_err(crate::error::AddTagsToCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "TooManyTagsException" => crate::error::AddTagsToCertificateError { meta: generic, kind: crate::error::AddTagsToCertificateErrorKind::TooManyTagsException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::too_many_tags_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_too_many_tags_exception_json_err(response.body().as_ref(), output).map_err(crate::error::AddTagsToCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::AddTagsToCertificateError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_add_tags_to_certificate_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::AddTagsToCertificateOutput, crate::error::AddTagsToCertificateError, > { Ok({ #[allow(unused_mut)] let mut output = crate::output::add_tags_to_certificate_output::Builder::default(); let _ = response; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_delete_certificate_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::DeleteCertificateOutput, crate::error::DeleteCertificateError> { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::DeleteCertificateError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => return Err(crate::error::DeleteCertificateError::unhandled(generic)), }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "InvalidArnException" => crate::error::DeleteCertificateError { meta: generic, kind: crate::error::DeleteCertificateErrorKind::InvalidArnException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::invalid_arn_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_invalid_arn_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DeleteCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ResourceInUseException" => crate::error::DeleteCertificateError { meta: generic, kind: crate::error::DeleteCertificateErrorKind::ResourceInUseException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::resource_in_use_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_resource_in_use_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DeleteCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ResourceNotFoundException" => crate::error::DeleteCertificateError { meta: generic, kind: crate::error::DeleteCertificateErrorKind::ResourceNotFoundException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::resource_not_found_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DeleteCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::DeleteCertificateError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_delete_certificate_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::DeleteCertificateOutput, crate::error::DeleteCertificateError> { Ok({ #[allow(unused_mut)] let mut output = crate::output::delete_certificate_output::Builder::default(); let _ = response; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_describe_certificate_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::DescribeCertificateOutput, crate::error::DescribeCertificateError, > { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::DescribeCertificateError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => return Err(crate::error::DescribeCertificateError::unhandled(generic)), }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "InvalidArnException" => crate::error::DescribeCertificateError { meta: generic, kind: crate::error::DescribeCertificateErrorKind::InvalidArnException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::invalid_arn_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_invalid_arn_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DescribeCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ResourceNotFoundException" => crate::error::DescribeCertificateError { meta: generic, kind: crate::error::DescribeCertificateErrorKind::ResourceNotFoundException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::resource_not_found_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::DescribeCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::DescribeCertificateError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_describe_certificate_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::DescribeCertificateOutput, crate::error::DescribeCertificateError, > { Ok({ #[allow(unused_mut)] let mut output = crate::output::describe_certificate_output::Builder::default(); let _ = response; output = crate::json_deser::deser_operation_crate_operation_describe_certificate( response.body().as_ref(), output, ) .map_err(crate::error::DescribeCertificateError::unhandled)?; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_export_certificate_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::ExportCertificateOutput, crate::error::ExportCertificateError> { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::ExportCertificateError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => return Err(crate::error::ExportCertificateError::unhandled(generic)), }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "InvalidArnException" => crate::error::ExportCertificateError { meta: generic, kind: crate::error::ExportCertificateErrorKind::InvalidArnException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::invalid_arn_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_invalid_arn_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ExportCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "RequestInProgressException" => crate::error::ExportCertificateError { meta: generic, kind: crate::error::ExportCertificateErrorKind::RequestInProgressException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::request_in_progress_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_request_in_progress_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ExportCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ResourceNotFoundException" => crate::error::ExportCertificateError { meta: generic, kind: crate::error::ExportCertificateErrorKind::ResourceNotFoundException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::resource_not_found_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ExportCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::ExportCertificateError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_export_certificate_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::ExportCertificateOutput, crate::error::ExportCertificateError> { Ok({ #[allow(unused_mut)] let mut output = crate::output::export_certificate_output::Builder::default(); let _ = response; output = crate::json_deser::deser_operation_crate_operation_export_certificate( response.body().as_ref(), output, ) .map_err(crate::error::ExportCertificateError::unhandled)?; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_get_account_configuration_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::GetAccountConfigurationOutput, crate::error::GetAccountConfigurationError, > { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::GetAccountConfigurationError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => { return Err(crate::error::GetAccountConfigurationError::unhandled( generic, )) } }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "AccessDeniedException" => crate::error::GetAccountConfigurationError { meta: generic, kind: crate::error::GetAccountConfigurationErrorKind::AccessDeniedException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::access_denied_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_access_denied_exception_json_err(response.body().as_ref(), output).map_err(crate::error::GetAccountConfigurationError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ThrottlingException" => crate::error::GetAccountConfigurationError { meta: generic, kind: crate::error::GetAccountConfigurationErrorKind::ThrottlingException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::throttling_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_throttling_exception_json_err(response.body().as_ref(), output).map_err(crate::error::GetAccountConfigurationError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::GetAccountConfigurationError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_get_account_configuration_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::GetAccountConfigurationOutput, crate::error::GetAccountConfigurationError, > { Ok({ #[allow(unused_mut)] let mut output = crate::output::get_account_configuration_output::Builder::default(); let _ = response; output = crate::json_deser::deser_operation_crate_operation_get_account_configuration( response.body().as_ref(), output, ) .map_err(crate::error::GetAccountConfigurationError::unhandled)?; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_get_certificate_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::GetCertificateOutput, crate::error::GetCertificateError> { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::GetCertificateError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => return Err(crate::error::GetCertificateError::unhandled(generic)), }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "InvalidArnException" => crate::error::GetCertificateError { meta: generic, kind: crate::error::GetCertificateErrorKind::InvalidArnException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::invalid_arn_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_invalid_arn_exception_json_err(response.body().as_ref(), output).map_err(crate::error::GetCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "RequestInProgressException" => crate::error::GetCertificateError { meta: generic, kind: crate::error::GetCertificateErrorKind::RequestInProgressException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::request_in_progress_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_request_in_progress_exception_json_err(response.body().as_ref(), output).map_err(crate::error::GetCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ResourceNotFoundException" => crate::error::GetCertificateError { meta: generic, kind: crate::error::GetCertificateErrorKind::ResourceNotFoundException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::resource_not_found_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::GetCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::GetCertificateError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_get_certificate_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::GetCertificateOutput, crate::error::GetCertificateError> { Ok({ #[allow(unused_mut)] let mut output = crate::output::get_certificate_output::Builder::default(); let _ = response; output = crate::json_deser::deser_operation_crate_operation_get_certificate( response.body().as_ref(), output, ) .map_err(crate::error::GetCertificateError::unhandled)?; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_import_certificate_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::ImportCertificateOutput, crate::error::ImportCertificateError> { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::ImportCertificateError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => return Err(crate::error::ImportCertificateError::unhandled(generic)), }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "InvalidArnException" => crate::error::ImportCertificateError { meta: generic, kind: crate::error::ImportCertificateErrorKind::InvalidArnException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::invalid_arn_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_invalid_arn_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ImportCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "InvalidParameterException" => crate::error::ImportCertificateError { meta: generic, kind: crate::error::ImportCertificateErrorKind::InvalidParameterException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::invalid_parameter_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_invalid_parameter_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ImportCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "InvalidTagException" => crate::error::ImportCertificateError { meta: generic, kind: crate::error::ImportCertificateErrorKind::InvalidTagException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::invalid_tag_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_invalid_tag_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ImportCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "LimitExceededException" => crate::error::ImportCertificateError { meta: generic, kind: crate::error::ImportCertificateErrorKind::LimitExceededException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::limit_exceeded_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_limit_exceeded_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ImportCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ResourceNotFoundException" => crate::error::ImportCertificateError { meta: generic, kind: crate::error::ImportCertificateErrorKind::ResourceNotFoundException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::resource_not_found_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ImportCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "TagPolicyException" => crate::error::ImportCertificateError { meta: generic, kind: crate::error::ImportCertificateErrorKind::TagPolicyException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::tag_policy_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_tag_policy_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ImportCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "TooManyTagsException" => crate::error::ImportCertificateError { meta: generic, kind: crate::error::ImportCertificateErrorKind::TooManyTagsException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::too_many_tags_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_too_many_tags_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ImportCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::ImportCertificateError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_import_certificate_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::ImportCertificateOutput, crate::error::ImportCertificateError> { Ok({ #[allow(unused_mut)] let mut output = crate::output::import_certificate_output::Builder::default(); let _ = response; output = crate::json_deser::deser_operation_crate_operation_import_certificate( response.body().as_ref(), output, ) .map_err(crate::error::ImportCertificateError::unhandled)?; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_list_certificates_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::ListCertificatesOutput, crate::error::ListCertificatesError> { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::ListCertificatesError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => return Err(crate::error::ListCertificatesError::unhandled(generic)), }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "InvalidArgsException" => crate::error::ListCertificatesError { meta: generic, kind: crate::error::ListCertificatesErrorKind::InvalidArgsException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::invalid_args_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_invalid_args_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ListCertificatesError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::ListCertificatesError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_list_certificates_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::ListCertificatesOutput, crate::error::ListCertificatesError> { Ok({ #[allow(unused_mut)] let mut output = crate::output::list_certificates_output::Builder::default(); let _ = response; output = crate::json_deser::deser_operation_crate_operation_list_certificates( response.body().as_ref(), output, ) .map_err(crate::error::ListCertificatesError::unhandled)?; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_list_tags_for_certificate_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::ListTagsForCertificateOutput, crate::error::ListTagsForCertificateError, > { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::ListTagsForCertificateError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => { return Err(crate::error::ListTagsForCertificateError::unhandled( generic, )) } }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "InvalidArnException" => crate::error::ListTagsForCertificateError { meta: generic, kind: crate::error::ListTagsForCertificateErrorKind::InvalidArnException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::invalid_arn_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_invalid_arn_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ListTagsForCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ResourceNotFoundException" => crate::error::ListTagsForCertificateError { meta: generic, kind: crate::error::ListTagsForCertificateErrorKind::ResourceNotFoundException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::resource_not_found_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ListTagsForCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::ListTagsForCertificateError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_list_tags_for_certificate_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::ListTagsForCertificateOutput, crate::error::ListTagsForCertificateError, > { Ok({ #[allow(unused_mut)] let mut output = crate::output::list_tags_for_certificate_output::Builder::default(); let _ = response; output = crate::json_deser::deser_operation_crate_operation_list_tags_for_certificate( response.body().as_ref(), output, ) .map_err(crate::error::ListTagsForCertificateError::unhandled)?; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_put_account_configuration_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::PutAccountConfigurationOutput, crate::error::PutAccountConfigurationError, > { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::PutAccountConfigurationError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => { return Err(crate::error::PutAccountConfigurationError::unhandled( generic, )) } }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "AccessDeniedException" => crate::error::PutAccountConfigurationError { meta: generic, kind: crate::error::PutAccountConfigurationErrorKind::AccessDeniedException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::access_denied_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_access_denied_exception_json_err(response.body().as_ref(), output).map_err(crate::error::PutAccountConfigurationError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ConflictException" => { crate::error::PutAccountConfigurationError { meta: generic, kind: crate::error::PutAccountConfigurationErrorKind::ConflictException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::conflict_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_conflict_exception_json_err(response.body().as_ref(), output).map_err(crate::error::PutAccountConfigurationError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), } } "ThrottlingException" => crate::error::PutAccountConfigurationError { meta: generic, kind: crate::error::PutAccountConfigurationErrorKind::ThrottlingException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::throttling_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_throttling_exception_json_err(response.body().as_ref(), output).map_err(crate::error::PutAccountConfigurationError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ValidationException" => crate::error::PutAccountConfigurationError { meta: generic, kind: crate::error::PutAccountConfigurationErrorKind::ValidationException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::validation_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_validation_exception_json_err(response.body().as_ref(), output).map_err(crate::error::PutAccountConfigurationError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::PutAccountConfigurationError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_put_account_configuration_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::PutAccountConfigurationOutput, crate::error::PutAccountConfigurationError, > { Ok({ #[allow(unused_mut)] let mut output = crate::output::put_account_configuration_output::Builder::default(); let _ = response; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_remove_tags_from_certificate_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::RemoveTagsFromCertificateOutput, crate::error::RemoveTagsFromCertificateError, > { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::RemoveTagsFromCertificateError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => { return Err(crate::error::RemoveTagsFromCertificateError::unhandled( generic, )) } }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "InvalidArnException" => crate::error::RemoveTagsFromCertificateError { meta: generic, kind: crate::error::RemoveTagsFromCertificateErrorKind::InvalidArnException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::invalid_arn_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_invalid_arn_exception_json_err(response.body().as_ref(), output).map_err(crate::error::RemoveTagsFromCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "InvalidParameterException" => crate::error::RemoveTagsFromCertificateError { meta: generic, kind: crate::error::RemoveTagsFromCertificateErrorKind::InvalidParameterException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::invalid_parameter_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_invalid_parameter_exception_json_err(response.body().as_ref(), output).map_err(crate::error::RemoveTagsFromCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "InvalidTagException" => crate::error::RemoveTagsFromCertificateError { meta: generic, kind: crate::error::RemoveTagsFromCertificateErrorKind::InvalidTagException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::invalid_tag_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_invalid_tag_exception_json_err(response.body().as_ref(), output).map_err(crate::error::RemoveTagsFromCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ResourceNotFoundException" => crate::error::RemoveTagsFromCertificateError { meta: generic, kind: crate::error::RemoveTagsFromCertificateErrorKind::ResourceNotFoundException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::resource_not_found_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::RemoveTagsFromCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "TagPolicyException" => crate::error::RemoveTagsFromCertificateError { meta: generic, kind: crate::error::RemoveTagsFromCertificateErrorKind::TagPolicyException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::tag_policy_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_tag_policy_exception_json_err(response.body().as_ref(), output).map_err(crate::error::RemoveTagsFromCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ThrottlingException" => crate::error::RemoveTagsFromCertificateError { meta: generic, kind: crate::error::RemoveTagsFromCertificateErrorKind::ThrottlingException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::throttling_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_throttling_exception_json_err(response.body().as_ref(), output).map_err(crate::error::RemoveTagsFromCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::RemoveTagsFromCertificateError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_remove_tags_from_certificate_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::RemoveTagsFromCertificateOutput, crate::error::RemoveTagsFromCertificateError, > { Ok({ #[allow(unused_mut)] let mut output = crate::output::remove_tags_from_certificate_output::Builder::default(); let _ = response; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_renew_certificate_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::RenewCertificateOutput, crate::error::RenewCertificateError> { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::RenewCertificateError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => return Err(crate::error::RenewCertificateError::unhandled(generic)), }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "InvalidArnException" => crate::error::RenewCertificateError { meta: generic, kind: crate::error::RenewCertificateErrorKind::InvalidArnException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::invalid_arn_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_invalid_arn_exception_json_err(response.body().as_ref(), output).map_err(crate::error::RenewCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ResourceNotFoundException" => crate::error::RenewCertificateError { meta: generic, kind: crate::error::RenewCertificateErrorKind::ResourceNotFoundException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::resource_not_found_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::RenewCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::RenewCertificateError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_renew_certificate_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::RenewCertificateOutput, crate::error::RenewCertificateError> { Ok({ #[allow(unused_mut)] let mut output = crate::output::renew_certificate_output::Builder::default(); let _ = response; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_request_certificate_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::RequestCertificateOutput, crate::error::RequestCertificateError, > { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::RequestCertificateError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => return Err(crate::error::RequestCertificateError::unhandled(generic)), }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "InvalidArnException" => crate::error::RequestCertificateError { meta: generic, kind: crate::error::RequestCertificateErrorKind::InvalidArnException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::invalid_arn_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_invalid_arn_exception_json_err(response.body().as_ref(), output).map_err(crate::error::RequestCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "InvalidDomainValidationOptionsException" => crate::error::RequestCertificateError { meta: generic, kind: crate::error::RequestCertificateErrorKind::InvalidDomainValidationOptionsException( { #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)]let mut output = crate::error::invalid_domain_validation_options_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_invalid_domain_validation_options_exception_json_err(response.body().as_ref(), output).map_err(crate::error::RequestCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }, ), }, "InvalidParameterException" => crate::error::RequestCertificateError { meta: generic, kind: crate::error::RequestCertificateErrorKind::InvalidParameterException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::invalid_parameter_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_invalid_parameter_exception_json_err(response.body().as_ref(), output).map_err(crate::error::RequestCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "InvalidTagException" => crate::error::RequestCertificateError { meta: generic, kind: crate::error::RequestCertificateErrorKind::InvalidTagException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::invalid_tag_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_invalid_tag_exception_json_err(response.body().as_ref(), output).map_err(crate::error::RequestCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "LimitExceededException" => crate::error::RequestCertificateError { meta: generic, kind: crate::error::RequestCertificateErrorKind::LimitExceededException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::limit_exceeded_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_limit_exceeded_exception_json_err(response.body().as_ref(), output).map_err(crate::error::RequestCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "TagPolicyException" => crate::error::RequestCertificateError { meta: generic, kind: crate::error::RequestCertificateErrorKind::TagPolicyException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::tag_policy_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_tag_policy_exception_json_err(response.body().as_ref(), output).map_err(crate::error::RequestCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "TooManyTagsException" => crate::error::RequestCertificateError { meta: generic, kind: crate::error::RequestCertificateErrorKind::TooManyTagsException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::too_many_tags_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_too_many_tags_exception_json_err(response.body().as_ref(), output).map_err(crate::error::RequestCertificateError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::RequestCertificateError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_request_certificate_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::RequestCertificateOutput, crate::error::RequestCertificateError, > { Ok({ #[allow(unused_mut)] let mut output = crate::output::request_certificate_output::Builder::default(); let _ = response; output = crate::json_deser::deser_operation_crate_operation_request_certificate( response.body().as_ref(), output, ) .map_err(crate::error::RequestCertificateError::unhandled)?; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_resend_validation_email_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::ResendValidationEmailOutput, crate::error::ResendValidationEmailError, > { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::ResendValidationEmailError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => return Err(crate::error::ResendValidationEmailError::unhandled(generic)), }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "InvalidArnException" => crate::error::ResendValidationEmailError { meta: generic, kind: crate::error::ResendValidationEmailErrorKind::InvalidArnException({ #[allow(unused_mut)]let mut tmp = { #[allow(unused_mut)]let mut output = crate::error::invalid_arn_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_invalid_arn_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ResendValidationEmailError::unhandled)?; output.build() } ; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp })}, "InvalidDomainValidationOptionsException" => crate::error::ResendValidationEmailError { meta: generic, kind: crate::error::ResendValidationEmailErrorKind::InvalidDomainValidationOptionsException({ #[allow(unused_mut)]let mut tmp = { #[allow(unused_mut)]let mut output = crate::error::invalid_domain_validation_options_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_invalid_domain_validation_options_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ResendValidationEmailError::unhandled)?; output.build() } ; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp })}, "InvalidStateException" => crate::error::ResendValidationEmailError { meta: generic, kind: crate::error::ResendValidationEmailErrorKind::InvalidStateException({ #[allow(unused_mut)]let mut tmp = { #[allow(unused_mut)]let mut output = crate::error::invalid_state_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_invalid_state_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ResendValidationEmailError::unhandled)?; output.build() } ; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp })}, "ResourceNotFoundException" => crate::error::ResendValidationEmailError { meta: generic, kind: crate::error::ResendValidationEmailErrorKind::ResourceNotFoundException({ #[allow(unused_mut)]let mut tmp = { #[allow(unused_mut)]let mut output = crate::error::resource_not_found_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::ResendValidationEmailError::unhandled)?; output.build() } ; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp })}, _ => crate::error::ResendValidationEmailError::generic(generic) }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_resend_validation_email_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::ResendValidationEmailOutput, crate::error::ResendValidationEmailError, > { Ok({ #[allow(unused_mut)] let mut output = crate::output::resend_validation_email_output::Builder::default(); let _ = response; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_update_certificate_options_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::UpdateCertificateOptionsOutput, crate::error::UpdateCertificateOptionsError, > { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::UpdateCertificateOptionsError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => { return Err(crate::error::UpdateCertificateOptionsError::unhandled( generic, )) } }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "InvalidArnException" => crate::error::UpdateCertificateOptionsError { meta: generic, kind: crate::error::UpdateCertificateOptionsErrorKind::InvalidArnException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::invalid_arn_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_invalid_arn_exception_json_err(response.body().as_ref(), output).map_err(crate::error::UpdateCertificateOptionsError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "InvalidStateException" => crate::error::UpdateCertificateOptionsError { meta: generic, kind: crate::error::UpdateCertificateOptionsErrorKind::InvalidStateException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::invalid_state_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_invalid_state_exception_json_err(response.body().as_ref(), output).map_err(crate::error::UpdateCertificateOptionsError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "LimitExceededException" => crate::error::UpdateCertificateOptionsError { meta: generic, kind: crate::error::UpdateCertificateOptionsErrorKind::LimitExceededException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::limit_exceeded_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_limit_exceeded_exception_json_err(response.body().as_ref(), output).map_err(crate::error::UpdateCertificateOptionsError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ResourceNotFoundException" => crate::error::UpdateCertificateOptionsError { meta: generic, kind: crate::error::UpdateCertificateOptionsErrorKind::ResourceNotFoundException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::resource_not_found_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_crate_error_resource_not_found_exception_json_err(response.body().as_ref(), output).map_err(crate::error::UpdateCertificateOptionsError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::UpdateCertificateOptionsError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_update_certificate_options_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::UpdateCertificateOptionsOutput, crate::error::UpdateCertificateOptionsError, > { Ok({ #[allow(unused_mut)] let mut output = crate::output::update_certificate_options_output::Builder::default(); let _ = response; output.build() }) }
45.164806
230
0.571134
cc1eff1fadae2ef9b6ac925b5af06d3382f26134
364
#[allow(unused)] pub fn hash<const N: usize>(px: [u8; N]) -> u8 { let r = px[0]; let g = px[1]; let b = px[2]; let a = if N >= 4 { px[3] } else { 0xff }; let rm = r.wrapping_mul(3); let gm = g.wrapping_mul(5); let bm = b.wrapping_mul(7); let am = a.wrapping_mul(11); rm.wrapping_add(gm).wrapping_add(bm).wrapping_add(am) % 64 }
28
62
0.552198
03004371779389bf4f115bcca37b681cdd9ee16a
2,491
#[cfg(test)] mod test { #[test] fn should_convert_duration_correctly() { assert_eq!("1:00", timer_for_harvest::f32_to_duration_str(1.0)); assert_eq!("0:01", timer_for_harvest::f32_to_duration_str(1.0 / 60.0)); assert_eq!("0:05", timer_for_harvest::f32_to_duration_str(5.0 / 60.0)); assert_eq!("0:10", timer_for_harvest::f32_to_duration_str(10.0 / 60.0)); assert_eq!("1:00", timer_for_harvest::f32_to_duration_str(59.9 / 60.0)); } #[test] fn should_not_crash_duration_str_to_f32() { assert_eq!(0.0, timer_for_harvest::duration_str_to_f32("0:00")); assert_eq!(1.5, timer_for_harvest::duration_str_to_f32("1:30")); assert_eq!(1.0, timer_for_harvest::duration_str_to_f32("1")); } #[test] fn should_parse_account_id() { assert_eq!( "123", timer_for_harvest::parse_account_details("GET /?access_token=abc&scope=harvest%3A123") .1 ); assert_eq!( "123", timer_for_harvest::parse_account_details("GET /?scope=harvest%3A123&access_token=abc") .1 ); } #[test] fn should_parse_access_token() { assert_eq!( "abc", timer_for_harvest::parse_account_details("GET /?access_token=abc&scope=harvest%3A123") .0 ); assert_eq!( "abc", timer_for_harvest::parse_account_details("GET /?scope=harvest%3A123&access_token=abc") .0 ); } #[test] fn should_parse_expires_in() { assert_eq!( "123", timer_for_harvest::parse_account_details("GET /?expires_in=123&scope=harvest%3A456").2 ); assert_eq!( "123", timer_for_harvest::parse_account_details("GET /?scope=harvest%3A456&expires_in=123").2 ); } #[test] fn should_format_timeentry_notes_for_list() { assert_eq!("Lorem Ipsum - 1234567890 - 1234567890 - 1234567890 - 1234567890 - 1234567890 - 1...", timer_for_harvest::format_timeentry_notes_for_list(&"Lorem Ipsum\n\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890", None)); assert_eq!("Lorem Ipsum - 1...", timer_for_harvest::format_timeentry_notes_for_list(&"Lorem Ipsum\n\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890", Some(15))); } }
38.323077
290
0.629466
bfc3ff7bd8d38ed81793389e896e42796e8abcd6
3,685
use super::super::{response, Dispatch, DispatchError, DispatchResult, Request}; use crate::{state::KeyType, Hop}; use alloc::vec::Vec; pub struct Keys; impl Keys { fn map(hop: &Hop, key: &[u8], resp: &mut Vec<u8>) -> DispatchResult<()> { let key = hop .state() .key_ref(key) .ok_or(DispatchError::KeyNonexistent)?; let map = key.as_map_ref().ok_or(DispatchError::KeyTypeDifferent)?; let iter = map.iter().map(|r| r.key().to_vec()); response::write_list(resp, iter); Ok(()) } } impl Dispatch for Keys { fn dispatch(hop: &Hop, req: &Request, resp: &mut Vec<u8>) -> DispatchResult<()> { let key = req.key().ok_or(DispatchError::KeyUnspecified)?; let key_type = req .key_type() .or_else(|| hop.state().key_type(key)) .unwrap_or(KeyType::Map); match key_type { KeyType::Map => Self::map(hop, key, resp), _ => Err(DispatchError::KeyTypeInvalid), } } } #[cfg(test)] mod tests { use super::Keys; use crate::{ command::{request::RequestBuilder, CommandId, Dispatch, DispatchError, Response}, state::{KeyType, Value}, Hop, }; use alloc::vec::Vec; use dashmap::DashMap; #[test] fn test_map_no_key_type_two_pairs() { let mut builder = RequestBuilder::new(CommandId::Keys); assert!(builder.bytes(b"foo".as_ref()).is_ok()); let req = builder.into_request(); let mut resp = Vec::new(); let hop = Hop::new(); let map = DashMap::new(); map.insert(b"key1".to_vec(), b"value2".to_vec()); map.insert(b"key2".to_vec(), b"value2".to_vec()); hop.state().insert(b"foo".to_vec(), Value::Map(map)); assert!(Keys::dispatch(&hop, &req, &mut resp).is_ok()); let expected1 = Response::from([b"key1".to_vec(), b"key2".to_vec()].to_vec()).as_bytes(); let expected2 = Response::from([b"key2".to_vec(), b"key1".to_vec()].to_vec()).as_bytes(); assert!(resp == expected1 || resp == expected2); } #[test] fn test_map_key_type() { let mut builder = RequestBuilder::new_with_key_type(CommandId::Keys, KeyType::Map); assert!(builder.bytes(b"foo".as_ref()).is_ok()); let req = builder.into_request(); let mut resp = Vec::new(); let hop = Hop::new(); let map = DashMap::new(); map.insert(b"key".to_vec(), b"value".to_vec()); hop.state().insert(b"foo".to_vec(), Value::Map(map)); assert!(Keys::dispatch(&hop, &req, &mut resp).is_ok()); assert_eq!(resp, Response::from([b"key".to_vec()].to_vec()).as_bytes()); } #[test] fn test_key_type_invalid() { let mut builder = RequestBuilder::new_with_key_type(CommandId::Keys, KeyType::Integer); assert!(builder.bytes(b"foo".as_ref()).is_ok()); let req = builder.into_request(); let mut resp = Vec::new(); let hop = Hop::new(); assert_eq!( DispatchError::KeyTypeInvalid, Keys::dispatch(&hop, &req, &mut resp).unwrap_err() ); } #[test] fn test_key_type_different() { let mut builder = RequestBuilder::new_with_key_type(CommandId::Keys, KeyType::Map); assert!(builder.bytes(b"foo".as_ref()).is_ok()); let req = builder.into_request(); let mut resp = Vec::new(); let hop = Hop::new(); hop.state().insert(b"foo".to_vec(), Value::Integer(1)); assert_eq!( DispatchError::KeyTypeDifferent, Keys::dispatch(&hop, &req, &mut resp).unwrap_err() ); } }
32.324561
97
0.567978
64f93c01a13c0095284fce0549d4d93e1e059360
2,198
use std::fmt; use beef::lean::Cow; use proc_macro2::{Span, TokenStream}; use quote::quote; use quote::{quote_spanned, ToTokens, TokenStreamExt}; pub type Result<T> = std::result::Result<T, Error>; #[derive(Default)] pub struct Errors { collected: Vec<SpannedError>, } impl Errors { pub fn err<M>(&mut self, message: M, span: Span) -> &mut Self where M: Into<Cow<'static, str>>, { self.collected.push(SpannedError { message: message.into(), span, }); self } pub fn render(self) -> Option<TokenStream> { let errors = self.collected; match errors.len() { 0 => None, _ => Some(quote! { fn _logos_derive_compile_errors() { #(#errors)* } }), } } } pub struct Error(Cow<'static, str>); #[derive(Debug)] pub struct SpannedError { message: Cow<'static, str>, span: Span, } impl Error { pub fn new<M>(message: M) -> Self where M: Into<Cow<'static, str>>, { Error(message.into()) } pub fn span(self, span: Span) -> SpannedError { SpannedError { message: self.0, span, } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) } } impl fmt::Debug for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self, f) } } impl From<regex_syntax::Error> for Error { fn from(err: regex_syntax::Error) -> Error { Error(err.to_string().into()) } } impl From<&'static str> for Error { fn from(err: &'static str) -> Error { Error(err.into()) } } impl From<String> for Error { fn from(err: String) -> Error { Error(err.into()) } } impl From<Error> for Cow<'static, str> { fn from(err: Error) -> Self { err.0 } } impl ToTokens for SpannedError { fn to_tokens(&self, tokens: &mut TokenStream) { let message = &*self.message; tokens.append_all(quote_spanned!(self.span => { compile_error!(#message) })) } }
19.801802
65
0.536852
ef7155c6ac24fc504852600a8f4719c9fc86c689
4,050
use crate::authentication; use crate::models::{User, UserInfo, UserInput}; use actix_session::Session; use paperclip::actix::{ api_v2_operation, web::{Data, HttpResponse, Json}, }; use wither::bson::{doc, oid::ObjectId}; use wither::mongodb::Database as MongoDatabase; use wither::prelude::*; // #[post("/signup")] /// User signup /// /// Creates a new user but doesn't log in the user /// Currently like this because of future developements #[api_v2_operation] pub async fn signup( db: Data<MongoDatabase>, new_user: Json<UserInput>, ) -> Result<Json<UserInfo>, HttpResponse> { let username = &new_user.username; let clear_password = &new_user.password; let password = authentication::hash_password(clear_password); // Create a user. let mut user = User::new_user(username, &password); if let Ok(_) = user.save(&db, None).await { Ok(Json(user.to_user_info())) } else { Err(HttpResponse::BadRequest().body("Username is already registered")) } } // #[post("/login")] /// User login /// /// Logs in the user via the provided credentials, will set a cookie session #[api_v2_operation] pub async fn login( credentials: Json<UserInput>, session: Session, db: Data<MongoDatabase>, ) -> Result<Json<UserInfo>, HttpResponse> { let maybe_user: Option<ObjectId> = session.get("user_id").unwrap(); if let Some(user_id) = maybe_user { // We can be sure that the user exists if there is a session let user = User::find_by_id(&db, &user_id).await.unwrap(); session.renew(); Ok(Json(user.to_user_info())) } else { // let find_user_result: Result<Option<User>, wither::WitherError> = // User::find_one(&db, doc! { "username": &credentials.username }, None).await; // if let Ok(find_user) = find_user_result { if let Some(user) = User::find_by_username(&db, &credentials.username).await { let clear_password = &credentials.password; let hashed_password = &user.password; let password_verified = authentication::verify_hash(hashed_password, clear_password); if password_verified { let info = user.to_user_info(); // If the user exists there is a user id session.set("user_id", user.id.unwrap()).unwrap(); session.set("user_role", user.role).unwrap(); Ok(Json(info)) } else { Err(HttpResponse::BadRequest().body("Wrong password")) } } else { Err(HttpResponse::NotFound().body("User not found")) } // } else { // Err(HttpResponse::InternalServerError().body("")) // } } } // #[get("/user-info")] /// User info /// /// Gets the current user info if he is logged in #[api_v2_operation] pub async fn user_info( session: Session, db: Data<MongoDatabase>, ) -> Result<Json<UserInfo>, HttpResponse> { let maybe_id: Option<ObjectId> = session.get("user_id").unwrap(); if let Some(id) = maybe_id { let maybe_user = User::find_by_id(&db, &id).await; if let Some(user) = maybe_user { session.renew(); Ok(Json(user.to_user_info())) } else { session.clear(); Err(HttpResponse::Unauthorized().body("Error")) } } else { Err(HttpResponse::Unauthorized().body("Not logged in")) } } // #[get("/logout")] /// Logout /// /// Logs out the current user invalidating the session if he is logged in #[api_v2_operation] pub async fn logout(session: Session) -> Result<HttpResponse, HttpResponse> { let maybe_user: Option<ObjectId> = session.get("user_id").unwrap(); if let Some(_) = maybe_user { session.clear(); Ok(HttpResponse::Ok().body("Logged out")) } else { Err(HttpResponse::BadRequest().body("Already logged out")) } }
33.471074
98
0.597778
f4acfa97c138430640f70b0d0a59b3888610a488
2,794
use proconio::input; use proconio::marker::Bytes; use std::cmp; fn read() -> (Vec<u8>, Vec<u8>) { input! { seq1: Bytes, seq2: Bytes } (seq1, seq2) } fn sim(ch1: u8, ch2: u8) -> i32 { if ch1 == b'-' || ch2 == b'-' { -5 } else if ch1 == ch2 { 1 } else { -3 } } #[allow(clippy::ptr_arg)] #[allow(dead_code)] fn score(seq1_aligned: &Vec<u8>, seq2_aligned: &Vec<u8>) -> i32 { assert!(seq1_aligned.len() == seq2_aligned.len()); (0..seq1_aligned.len()) .map(|i| sim(seq1_aligned[i], seq2_aligned[i])) .sum::<i32>() } #[allow(clippy::ptr_arg)] fn solve(seq1: &Vec<u8>, seq2: &Vec<u8>) -> (Vec<u8>, Vec<u8>) { let dp_width = seq1.len() + 1; let dp_height = seq2.len() + 1; let mut dp: Vec<Vec<i32>> = vec![vec![0; dp_width]; dp_height]; // x=0の列とy=0の行を計算 #[allow(clippy::needless_range_loop)] for y in 0..dp_height { dp[y][0] = y as i32 * (-5); } for x in 0..dp_width { dp[0][x] = x as i32 * (-5); } for y in 1..dp_height { for x in 1..dp_width { let score1 = dp[y - 1][x - 1] + if seq1[x - 1] == seq2[y - 1] { 1 } else { -3 }; let score2 = dp[y - 1][x] - 5; let score3 = dp[y][x - 1] - 5; dp[y][x] = cmp::max(cmp::max(score1, score2), score3); } } // 逆走 let mut seq1_aligned: Vec<u8> = Vec::new(); let mut seq2_aligned: Vec<u8> = Vec::new(); let mut x = dp_width - 1; let mut y = dp_height - 1; while !(x == 0 && y == 0) { let score1 = if x == 0 || y == 0 { None } else { Some(dp[y - 1][x - 1] + if seq1[x - 1] == seq2[y - 1] { 1 } else { -3 }) }; let score2 = if y == 0 { None } else { Some(dp[y - 1][x] - 5) }; let score3 = if x == 0 { None } else { Some(dp[y][x - 1] - 5) }; if Some(dp[y][x]) == score1 { seq1_aligned.push(seq1[x - 1]); seq2_aligned.push(seq2[y - 1]); x -= 1; y -= 1; } else if Some(dp[y][x]) == score2 { seq1_aligned.push(b'-'); seq2_aligned.push(seq2[y - 1]); y -= 1; } else if Some(dp[y][x]) == score3 { seq1_aligned.push(seq1[x - 1]); seq2_aligned.push(b'-'); x -= 1; } } seq1_aligned.reverse(); seq2_aligned.reverse(); (seq1_aligned, seq2_aligned) } #[allow(clippy::ptr_arg)] fn output(seq1: &Vec<u8>, seq2: &Vec<u8>) { println!("{}", String::from_utf8(seq1.clone()).unwrap()); println!("{}", String::from_utf8(seq2.clone()).unwrap()); } fn main() { let (seq1, seq2) = read(); let (seq1_aligned, seq2_aligned) = solve(&seq1, &seq2); output(&seq1_aligned, &seq2_aligned); }
27.126214
92
0.479599
67e490584e8e5bdd71fdd6e049bda3ebff17180d
99,697
// error-pattern:cargo-clippy #![feature(bindings_after_at)] #![feature(box_patterns)] #![feature(box_syntax)] #![feature(concat_idents)] #![feature(crate_visibility_modifier)] #![feature(drain_filter)] #![feature(in_band_lifetimes)] #![feature(once_cell)] #![feature(or_patterns)] #![feature(rustc_private)] #![feature(stmt_expr_attributes)] #![feature(control_flow_enum)] #![recursion_limit = "512"] #![cfg_attr(feature = "deny-warnings", deny(warnings))] #![allow(clippy::missing_docs_in_private_items, clippy::must_use_candidate)] #![warn(trivial_casts, trivial_numeric_casts)] // warn on lints, that are included in `rust-lang/rust`s bootstrap #![warn(rust_2018_idioms, unused_lifetimes)] // warn on rustc internal lints #![deny(rustc::internal)] // FIXME: switch to something more ergonomic here, once available. // (Currently there is no way to opt into sysroot crates without `extern crate`.) extern crate rustc_ast; extern crate rustc_ast_pretty; extern crate rustc_attr; extern crate rustc_data_structures; extern crate rustc_driver; extern crate rustc_errors; extern crate rustc_hir; extern crate rustc_hir_pretty; extern crate rustc_index; extern crate rustc_infer; extern crate rustc_lexer; extern crate rustc_lint; extern crate rustc_middle; extern crate rustc_mir; extern crate rustc_parse; extern crate rustc_parse_format; extern crate rustc_session; extern crate rustc_span; extern crate rustc_target; extern crate rustc_trait_selection; extern crate rustc_typeck; use crate::utils::parse_msrv; use rustc_data_structures::fx::FxHashSet; use rustc_lint::LintId; use rustc_session::Session; /// Macro used to declare a Clippy lint. /// /// Every lint declaration consists of 4 parts: /// /// 1. The documentation, which is used for the website /// 2. The `LINT_NAME`. See [lint naming][lint_naming] on lint naming conventions. /// 3. The `lint_level`, which is a mapping from *one* of our lint groups to `Allow`, `Warn` or /// `Deny`. The lint level here has nothing to do with what lint groups the lint is a part of. /// 4. The `description` that contains a short explanation on what's wrong with code where the /// lint is triggered. /// /// Currently the categories `style`, `correctness`, `complexity` and `perf` are enabled by default. /// As said in the README.md of this repository, if the lint level mapping changes, please update /// README.md. /// /// # Example /// /// ``` /// #![feature(rustc_private)] /// extern crate rustc_session; /// use rustc_session::declare_tool_lint; /// use clippy_lints::declare_clippy_lint; /// /// declare_clippy_lint! { /// /// **What it does:** Checks for ... (describe what the lint matches). /// /// /// /// **Why is this bad?** Supply the reason for linting the code. /// /// /// /// **Known problems:** None. (Or describe where it could go wrong.) /// /// /// /// **Example:** /// /// /// /// ```rust /// /// // Bad /// /// Insert a short example of code that triggers the lint /// /// /// /// // Good /// /// Insert a short example of improved code that doesn't trigger the lint /// /// ``` /// pub LINT_NAME, /// pedantic, /// "description" /// } /// ``` /// [lint_naming]: https://rust-lang.github.io/rfcs/0344-conventions-galore.html#lints #[macro_export] macro_rules! declare_clippy_lint { { $(#[$attr:meta])* pub $name:tt, style, $description:tt } => { declare_tool_lint! { $(#[$attr])* pub clippy::$name, Warn, $description, report_in_external_macro: true } }; { $(#[$attr:meta])* pub $name:tt, correctness, $description:tt } => { declare_tool_lint! { $(#[$attr])* pub clippy::$name, Deny, $description, report_in_external_macro: true } }; { $(#[$attr:meta])* pub $name:tt, complexity, $description:tt } => { declare_tool_lint! { $(#[$attr])* pub clippy::$name, Warn, $description, report_in_external_macro: true } }; { $(#[$attr:meta])* pub $name:tt, perf, $description:tt } => { declare_tool_lint! { $(#[$attr])* pub clippy::$name, Warn, $description, report_in_external_macro: true } }; { $(#[$attr:meta])* pub $name:tt, pedantic, $description:tt } => { declare_tool_lint! { $(#[$attr])* pub clippy::$name, Allow, $description, report_in_external_macro: true } }; { $(#[$attr:meta])* pub $name:tt, restriction, $description:tt } => { declare_tool_lint! { $(#[$attr])* pub clippy::$name, Allow, $description, report_in_external_macro: true } }; { $(#[$attr:meta])* pub $name:tt, cargo, $description:tt } => { declare_tool_lint! { $(#[$attr])* pub clippy::$name, Allow, $description, report_in_external_macro: true } }; { $(#[$attr:meta])* pub $name:tt, nursery, $description:tt } => { declare_tool_lint! { $(#[$attr])* pub clippy::$name, Allow, $description, report_in_external_macro: true } }; { $(#[$attr:meta])* pub $name:tt, internal, $description:tt } => { declare_tool_lint! { $(#[$attr])* pub clippy::$name, Allow, $description, report_in_external_macro: true } }; { $(#[$attr:meta])* pub $name:tt, internal_warn, $description:tt } => { declare_tool_lint! { $(#[$attr])* pub clippy::$name, Warn, $description, report_in_external_macro: true } }; } mod consts; #[macro_use] mod utils; // begin lints modules, do not remove this comment, it’s used in `update_lints` mod approx_const; mod arithmetic; mod as_conversions; mod asm_syntax; mod assertions_on_constants; mod assign_ops; mod async_yields_async; mod atomic_ordering; mod attrs; mod await_holding_invalid; mod bit_mask; mod blacklisted_name; mod blocks_in_if_conditions; mod booleans; mod bytecount; mod cargo_common_metadata; mod case_sensitive_file_extension_comparisons; mod checked_conversions; mod cognitive_complexity; mod collapsible_if; mod collapsible_match; mod comparison_chain; mod copies; mod copy_iterator; mod create_dir; mod dbg_macro; mod default; mod default_numeric_fallback; mod dereference; mod derive; mod disallowed_method; mod doc; mod double_comparison; mod double_parens; mod drop_forget_ref; mod duration_subsec; mod else_if_without_else; mod empty_enum; mod entry; mod enum_clike; mod enum_variants; mod eq_op; mod erasing_op; mod escape; mod eta_reduction; mod eval_order_dependence; mod excessive_bools; mod exhaustive_items; mod exit; mod explicit_write; mod fallible_impl_from; mod float_equality_without_abs; mod float_literal; mod floating_point_arithmetic; mod format; mod formatting; mod from_over_into; mod from_str_radix_10; mod functions; mod future_not_send; mod get_last_with_len; mod identity_op; mod if_let_mutex; mod if_let_some_result; mod if_not_else; mod implicit_return; mod implicit_saturating_sub; mod indexing_slicing; mod infinite_iter; mod inherent_impl; mod inherent_to_string; mod inline_fn_without_body; mod int_plus_one; mod integer_division; mod items_after_statements; mod large_const_arrays; mod large_enum_variant; mod large_stack_arrays; mod len_zero; mod let_if_seq; mod let_underscore; mod lifetimes; mod literal_representation; mod loops; mod macro_use; mod main_recursion; mod manual_async_fn; mod manual_non_exhaustive; mod manual_ok_or; mod manual_strip; mod manual_unwrap_or; mod map_clone; mod map_err_ignore; mod map_identity; mod map_unit_fn; mod match_on_vec_items; mod matches; mod mem_discriminant; mod mem_forget; mod mem_replace; mod methods; mod minmax; mod misc; mod misc_early; mod missing_const_for_fn; mod missing_doc; mod missing_inline; mod modulo_arithmetic; mod multiple_crate_versions; mod mut_key; mod mut_mut; mod mut_mutex_lock; mod mut_reference; mod mutable_debug_assertion; mod mutex_atomic; mod needless_arbitrary_self_type; mod needless_bool; mod needless_borrow; mod needless_borrowed_ref; mod needless_continue; mod needless_pass_by_value; mod needless_question_mark; mod needless_update; mod neg_cmp_op_on_partial_ord; mod neg_multiply; mod new_without_default; mod no_effect; mod non_copy_const; mod non_expressive_names; mod open_options; mod option_env_unwrap; mod option_if_let_else; mod overflow_check_conditional; mod panic_in_result_fn; mod panic_unimplemented; mod partialeq_ne_impl; mod pass_by_ref_or_value; mod path_buf_push_overwrite; mod pattern_type_mismatch; mod precedence; mod ptr; mod ptr_eq; mod ptr_offset_with_cast; mod question_mark; mod ranges; mod redundant_clone; mod redundant_closure_call; mod redundant_else; mod redundant_field_names; mod redundant_pub_crate; mod redundant_slicing; mod redundant_static_lifetimes; mod ref_option_ref; mod reference; mod regex; mod repeat_once; mod returns; mod self_assignment; mod semicolon_if_nothing_returned; mod serde_api; mod shadow; mod single_component_path_imports; mod size_of_in_element_count; mod slow_vector_initialization; mod stable_sort_primitive; mod strings; mod suspicious_operation_groupings; mod suspicious_trait_impl; mod swap; mod tabs_in_doc_comments; mod temporary_assignment; mod to_digit_is_some; mod to_string_in_display; mod trait_bounds; mod transmute; mod transmuting_null; mod try_err; mod types; mod undropped_manually_drops; mod unicode; mod unit_return_expecting_ord; mod unnamed_address; mod unnecessary_sort_by; mod unnecessary_wraps; mod unnested_or_patterns; mod unsafe_removed_from_name; mod unused_io_amount; mod unused_self; mod unused_unit; mod unwrap; mod unwrap_in_result; mod upper_case_acronyms; mod use_self; mod useless_conversion; mod vec; mod vec_init_then_push; mod vec_resize_to_zero; mod verbose_file_reads; mod wildcard_dependencies; mod wildcard_imports; mod write; mod zero_div_zero; mod zero_sized_map_values; // end lints modules, do not remove this comment, it’s used in `update_lints` pub use crate::utils::conf::Conf; /// Register all pre expansion lints /// /// Pre-expansion lints run before any macro expansion has happened. /// /// Note that due to the architecture of the compiler, currently `cfg_attr` attributes on crate /// level (i.e `#![cfg_attr(...)]`) will still be expanded even when using a pre-expansion pass. /// /// Used in `./src/driver.rs`. pub fn register_pre_expansion_lints(store: &mut rustc_lint::LintStore) { store.register_pre_expansion_pass(|| box write::Write::default()); store.register_pre_expansion_pass(|| box attrs::EarlyAttributes); store.register_pre_expansion_pass(|| box dbg_macro::DbgMacro); } #[doc(hidden)] pub fn read_conf(args: &[rustc_ast::NestedMetaItem], sess: &Session) -> Conf { use std::path::Path; match utils::conf::file_from_args(args) { Ok(file_name) => { // if the user specified a file, it must exist, otherwise default to `clippy.toml` but // do not require the file to exist let file_name = match file_name { Some(file_name) => file_name, None => match utils::conf::lookup_conf_file() { Ok(Some(path)) => path, Ok(None) => return Conf::default(), Err(error) => { sess.struct_err(&format!("error finding Clippy's configuration file: {}", error)) .emit(); return Conf::default(); }, }, }; let file_name = if file_name.is_relative() { sess.local_crate_source_file .as_deref() .and_then(Path::parent) .unwrap_or_else(|| Path::new("")) .join(file_name) } else { file_name }; let (conf, errors) = utils::conf::read(&file_name); // all conf errors are non-fatal, we just use the default conf in case of error for error in errors { sess.struct_err(&format!( "error reading Clippy's configuration file `{}`: {}", file_name.display(), error )) .emit(); } conf }, Err((err, span)) => { sess.struct_span_err(span, err) .span_note(span, "Clippy will use default configuration") .emit(); Conf::default() }, } } /// Register all lints and lint groups with the rustc plugin registry /// /// Used in `./src/driver.rs`. #[allow(clippy::too_many_lines)] #[rustfmt::skip] pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: &Conf) { register_removed_non_tool_lints(store); // begin deprecated lints, do not remove this comment, it’s used in `update_lints` store.register_removed( "clippy::should_assert_eq", "`assert!()` will be more flexible with RFC 2011", ); store.register_removed( "clippy::extend_from_slice", "`.extend_from_slice(_)` is a faster way to extend a Vec by a slice", ); store.register_removed( "clippy::range_step_by_zero", "`iterator.step_by(0)` panics nowadays", ); store.register_removed( "clippy::unstable_as_slice", "`Vec::as_slice` has been stabilized in 1.7", ); store.register_removed( "clippy::unstable_as_mut_slice", "`Vec::as_mut_slice` has been stabilized in 1.7", ); store.register_removed( "clippy::misaligned_transmute", "this lint has been split into cast_ptr_alignment and transmute_ptr_to_ptr", ); store.register_removed( "clippy::assign_ops", "using compound assignment operators (e.g., `+=`) is harmless", ); store.register_removed( "clippy::if_let_redundant_pattern_matching", "this lint has been changed to redundant_pattern_matching", ); store.register_removed( "clippy::unsafe_vector_initialization", "the replacement suggested by this lint had substantially different behavior", ); store.register_removed( "clippy::invalid_ref", "superseded by rustc lint `invalid_value`", ); store.register_removed( "clippy::unused_collect", "`collect` has been marked as #[must_use] in rustc and that covers all cases of this lint", ); store.register_removed( "clippy::into_iter_on_array", "this lint has been uplifted to rustc and is now called `array_into_iter`", ); store.register_removed( "clippy::unused_label", "this lint has been uplifted to rustc and is now called `unused_labels`", ); store.register_removed( "clippy::replace_consts", "associated-constants `MIN`/`MAX` of integers are preferred to `{min,max}_value()` and module constants", ); store.register_removed( "clippy::regex_macro", "the regex! macro has been removed from the regex crate in 2018", ); store.register_removed( "clippy::drop_bounds", "this lint has been uplifted to rustc and is now called `drop_bounds`", ); store.register_removed( "clippy::temporary_cstring_as_ptr", "this lint has been uplifted to rustc and is now called `temporary_cstring_as_ptr`", ); store.register_removed( "clippy::panic_params", "this lint has been uplifted to rustc and is now called `panic_fmt`", ); store.register_removed( "clippy::unknown_clippy_lints", "this lint has been integrated into the `unknown_lints` rustc lint", ); store.register_removed( "clippy::find_map", "this lint has been replaced by `manual_find_map`, a more specific lint", ); // end deprecated lints, do not remove this comment, it’s used in `update_lints` // begin register lints, do not remove this comment, it’s used in `update_lints` store.register_lints(&[ #[cfg(feature = "internal-lints")] &utils::internal_lints::CLIPPY_LINTS_INTERNAL, #[cfg(feature = "internal-lints")] &utils::internal_lints::COLLAPSIBLE_SPAN_LINT_CALLS, #[cfg(feature = "internal-lints")] &utils::internal_lints::COMPILER_LINT_FUNCTIONS, #[cfg(feature = "internal-lints")] &utils::internal_lints::DEFAULT_LINT, #[cfg(feature = "internal-lints")] &utils::internal_lints::INTERNING_DEFINED_SYMBOL, #[cfg(feature = "internal-lints")] &utils::internal_lints::INVALID_PATHS, #[cfg(feature = "internal-lints")] &utils::internal_lints::LINT_WITHOUT_LINT_PASS, #[cfg(feature = "internal-lints")] &utils::internal_lints::MATCH_TYPE_ON_DIAGNOSTIC_ITEM, #[cfg(feature = "internal-lints")] &utils::internal_lints::OUTER_EXPN_EXPN_DATA, #[cfg(feature = "internal-lints")] &utils::internal_lints::PRODUCE_ICE, #[cfg(feature = "internal-lints")] &utils::internal_lints::UNNECESSARY_SYMBOL_STR, &approx_const::APPROX_CONSTANT, &arithmetic::FLOAT_ARITHMETIC, &arithmetic::INTEGER_ARITHMETIC, &as_conversions::AS_CONVERSIONS, &asm_syntax::INLINE_ASM_X86_ATT_SYNTAX, &asm_syntax::INLINE_ASM_X86_INTEL_SYNTAX, &assertions_on_constants::ASSERTIONS_ON_CONSTANTS, &assign_ops::ASSIGN_OP_PATTERN, &assign_ops::MISREFACTORED_ASSIGN_OP, &async_yields_async::ASYNC_YIELDS_ASYNC, &atomic_ordering::INVALID_ATOMIC_ORDERING, &attrs::BLANKET_CLIPPY_RESTRICTION_LINTS, &attrs::DEPRECATED_CFG_ATTR, &attrs::DEPRECATED_SEMVER, &attrs::EMPTY_LINE_AFTER_OUTER_ATTR, &attrs::INLINE_ALWAYS, &attrs::MISMATCHED_TARGET_OS, &attrs::USELESS_ATTRIBUTE, &await_holding_invalid::AWAIT_HOLDING_LOCK, &await_holding_invalid::AWAIT_HOLDING_REFCELL_REF, &bit_mask::BAD_BIT_MASK, &bit_mask::INEFFECTIVE_BIT_MASK, &bit_mask::VERBOSE_BIT_MASK, &blacklisted_name::BLACKLISTED_NAME, &blocks_in_if_conditions::BLOCKS_IN_IF_CONDITIONS, &booleans::LOGIC_BUG, &booleans::NONMINIMAL_BOOL, &bytecount::NAIVE_BYTECOUNT, &cargo_common_metadata::CARGO_COMMON_METADATA, &case_sensitive_file_extension_comparisons::CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS, &checked_conversions::CHECKED_CONVERSIONS, &cognitive_complexity::COGNITIVE_COMPLEXITY, &collapsible_if::COLLAPSIBLE_ELSE_IF, &collapsible_if::COLLAPSIBLE_IF, &collapsible_match::COLLAPSIBLE_MATCH, &comparison_chain::COMPARISON_CHAIN, &copies::IFS_SAME_COND, &copies::IF_SAME_THEN_ELSE, &copies::SAME_FUNCTIONS_IN_IF_CONDITION, &copy_iterator::COPY_ITERATOR, &create_dir::CREATE_DIR, &dbg_macro::DBG_MACRO, &default::DEFAULT_TRAIT_ACCESS, &default::FIELD_REASSIGN_WITH_DEFAULT, &default_numeric_fallback::DEFAULT_NUMERIC_FALLBACK, &dereference::EXPLICIT_DEREF_METHODS, &derive::DERIVE_HASH_XOR_EQ, &derive::DERIVE_ORD_XOR_PARTIAL_ORD, &derive::EXPL_IMPL_CLONE_ON_COPY, &derive::UNSAFE_DERIVE_DESERIALIZE, &disallowed_method::DISALLOWED_METHOD, &doc::DOC_MARKDOWN, &doc::MISSING_ERRORS_DOC, &doc::MISSING_PANICS_DOC, &doc::MISSING_SAFETY_DOC, &doc::NEEDLESS_DOCTEST_MAIN, &double_comparison::DOUBLE_COMPARISONS, &double_parens::DOUBLE_PARENS, &drop_forget_ref::DROP_COPY, &drop_forget_ref::DROP_REF, &drop_forget_ref::FORGET_COPY, &drop_forget_ref::FORGET_REF, &duration_subsec::DURATION_SUBSEC, &else_if_without_else::ELSE_IF_WITHOUT_ELSE, &empty_enum::EMPTY_ENUM, &entry::MAP_ENTRY, &enum_clike::ENUM_CLIKE_UNPORTABLE_VARIANT, &enum_variants::ENUM_VARIANT_NAMES, &enum_variants::MODULE_INCEPTION, &enum_variants::MODULE_NAME_REPETITIONS, &enum_variants::PUB_ENUM_VARIANT_NAMES, &eq_op::EQ_OP, &eq_op::OP_REF, &erasing_op::ERASING_OP, &escape::BOXED_LOCAL, &eta_reduction::REDUNDANT_CLOSURE, &eta_reduction::REDUNDANT_CLOSURE_FOR_METHOD_CALLS, &eval_order_dependence::DIVERGING_SUB_EXPRESSION, &eval_order_dependence::EVAL_ORDER_DEPENDENCE, &excessive_bools::FN_PARAMS_EXCESSIVE_BOOLS, &excessive_bools::STRUCT_EXCESSIVE_BOOLS, &exhaustive_items::EXHAUSTIVE_ENUMS, &exhaustive_items::EXHAUSTIVE_STRUCTS, &exit::EXIT, &explicit_write::EXPLICIT_WRITE, &fallible_impl_from::FALLIBLE_IMPL_FROM, &float_equality_without_abs::FLOAT_EQUALITY_WITHOUT_ABS, &float_literal::EXCESSIVE_PRECISION, &float_literal::LOSSY_FLOAT_LITERAL, &floating_point_arithmetic::IMPRECISE_FLOPS, &floating_point_arithmetic::SUBOPTIMAL_FLOPS, &format::USELESS_FORMAT, &formatting::POSSIBLE_MISSING_COMMA, &formatting::SUSPICIOUS_ASSIGNMENT_FORMATTING, &formatting::SUSPICIOUS_ELSE_FORMATTING, &formatting::SUSPICIOUS_UNARY_OP_FORMATTING, &from_over_into::FROM_OVER_INTO, &from_str_radix_10::FROM_STR_RADIX_10, &functions::DOUBLE_MUST_USE, &functions::MUST_USE_CANDIDATE, &functions::MUST_USE_UNIT, &functions::NOT_UNSAFE_PTR_ARG_DEREF, &functions::RESULT_UNIT_ERR, &functions::TOO_MANY_ARGUMENTS, &functions::TOO_MANY_LINES, &future_not_send::FUTURE_NOT_SEND, &get_last_with_len::GET_LAST_WITH_LEN, &identity_op::IDENTITY_OP, &if_let_mutex::IF_LET_MUTEX, &if_let_some_result::IF_LET_SOME_RESULT, &if_not_else::IF_NOT_ELSE, &implicit_return::IMPLICIT_RETURN, &implicit_saturating_sub::IMPLICIT_SATURATING_SUB, &indexing_slicing::INDEXING_SLICING, &indexing_slicing::OUT_OF_BOUNDS_INDEXING, &infinite_iter::INFINITE_ITER, &infinite_iter::MAYBE_INFINITE_ITER, &inherent_impl::MULTIPLE_INHERENT_IMPL, &inherent_to_string::INHERENT_TO_STRING, &inherent_to_string::INHERENT_TO_STRING_SHADOW_DISPLAY, &inline_fn_without_body::INLINE_FN_WITHOUT_BODY, &int_plus_one::INT_PLUS_ONE, &integer_division::INTEGER_DIVISION, &items_after_statements::ITEMS_AFTER_STATEMENTS, &large_const_arrays::LARGE_CONST_ARRAYS, &large_enum_variant::LARGE_ENUM_VARIANT, &large_stack_arrays::LARGE_STACK_ARRAYS, &len_zero::COMPARISON_TO_EMPTY, &len_zero::LEN_WITHOUT_IS_EMPTY, &len_zero::LEN_ZERO, &let_if_seq::USELESS_LET_IF_SEQ, &let_underscore::LET_UNDERSCORE_DROP, &let_underscore::LET_UNDERSCORE_LOCK, &let_underscore::LET_UNDERSCORE_MUST_USE, &lifetimes::EXTRA_UNUSED_LIFETIMES, &lifetimes::NEEDLESS_LIFETIMES, &literal_representation::DECIMAL_LITERAL_REPRESENTATION, &literal_representation::INCONSISTENT_DIGIT_GROUPING, &literal_representation::LARGE_DIGIT_GROUPS, &literal_representation::MISTYPED_LITERAL_SUFFIXES, &literal_representation::UNREADABLE_LITERAL, &literal_representation::UNUSUAL_BYTE_GROUPINGS, &loops::EMPTY_LOOP, &loops::EXPLICIT_COUNTER_LOOP, &loops::EXPLICIT_INTO_ITER_LOOP, &loops::EXPLICIT_ITER_LOOP, &loops::FOR_KV_MAP, &loops::FOR_LOOPS_OVER_FALLIBLES, &loops::ITER_NEXT_LOOP, &loops::MANUAL_FLATTEN, &loops::MANUAL_MEMCPY, &loops::MUT_RANGE_BOUND, &loops::NEEDLESS_COLLECT, &loops::NEEDLESS_RANGE_LOOP, &loops::NEVER_LOOP, &loops::SAME_ITEM_PUSH, &loops::SINGLE_ELEMENT_LOOP, &loops::WHILE_IMMUTABLE_CONDITION, &loops::WHILE_LET_LOOP, &loops::WHILE_LET_ON_ITERATOR, &macro_use::MACRO_USE_IMPORTS, &main_recursion::MAIN_RECURSION, &manual_async_fn::MANUAL_ASYNC_FN, &manual_non_exhaustive::MANUAL_NON_EXHAUSTIVE, &manual_ok_or::MANUAL_OK_OR, &manual_strip::MANUAL_STRIP, &manual_unwrap_or::MANUAL_UNWRAP_OR, &map_clone::MAP_CLONE, &map_err_ignore::MAP_ERR_IGNORE, &map_identity::MAP_IDENTITY, &map_unit_fn::OPTION_MAP_UNIT_FN, &map_unit_fn::RESULT_MAP_UNIT_FN, &match_on_vec_items::MATCH_ON_VEC_ITEMS, &matches::INFALLIBLE_DESTRUCTURING_MATCH, &matches::MATCH_AS_REF, &matches::MATCH_BOOL, &matches::MATCH_LIKE_MATCHES_MACRO, &matches::MATCH_OVERLAPPING_ARM, &matches::MATCH_REF_PATS, &matches::MATCH_SAME_ARMS, &matches::MATCH_SINGLE_BINDING, &matches::MATCH_WILDCARD_FOR_SINGLE_VARIANTS, &matches::MATCH_WILD_ERR_ARM, &matches::REDUNDANT_PATTERN_MATCHING, &matches::REST_PAT_IN_FULLY_BOUND_STRUCTS, &matches::SINGLE_MATCH, &matches::SINGLE_MATCH_ELSE, &matches::WILDCARD_ENUM_MATCH_ARM, &matches::WILDCARD_IN_OR_PATTERNS, &mem_discriminant::MEM_DISCRIMINANT_NON_ENUM, &mem_forget::MEM_FORGET, &mem_replace::MEM_REPLACE_OPTION_WITH_NONE, &mem_replace::MEM_REPLACE_WITH_DEFAULT, &mem_replace::MEM_REPLACE_WITH_UNINIT, &methods::BIND_INSTEAD_OF_MAP, &methods::BYTES_NTH, &methods::CHARS_LAST_CMP, &methods::CHARS_NEXT_CMP, &methods::CLONE_DOUBLE_REF, &methods::CLONE_ON_COPY, &methods::CLONE_ON_REF_PTR, &methods::EXPECT_FUN_CALL, &methods::EXPECT_USED, &methods::FILETYPE_IS_FILE, &methods::FILTER_MAP, &methods::FILTER_MAP_IDENTITY, &methods::FILTER_MAP_NEXT, &methods::FILTER_NEXT, &methods::FLAT_MAP_IDENTITY, &methods::FROM_ITER_INSTEAD_OF_COLLECT, &methods::GET_UNWRAP, &methods::INEFFICIENT_TO_STRING, &methods::INSPECT_FOR_EACH, &methods::INTO_ITER_ON_REF, &methods::ITERATOR_STEP_BY_ZERO, &methods::ITER_CLONED_COLLECT, &methods::ITER_NEXT_SLICE, &methods::ITER_NTH, &methods::ITER_NTH_ZERO, &methods::ITER_SKIP_NEXT, &methods::MANUAL_FILTER_MAP, &methods::MANUAL_FIND_MAP, &methods::MANUAL_SATURATING_ARITHMETIC, &methods::MAP_COLLECT_RESULT_UNIT, &methods::MAP_FLATTEN, &methods::MAP_UNWRAP_OR, &methods::NEW_RET_NO_SELF, &methods::OK_EXPECT, &methods::OPTION_AS_REF_DEREF, &methods::OPTION_MAP_OR_NONE, &methods::OR_FUN_CALL, &methods::RESULT_MAP_OR_INTO_OPTION, &methods::SEARCH_IS_SOME, &methods::SHOULD_IMPLEMENT_TRAIT, &methods::SINGLE_CHAR_ADD_STR, &methods::SINGLE_CHAR_PATTERN, &methods::SKIP_WHILE_NEXT, &methods::STRING_EXTEND_CHARS, &methods::SUSPICIOUS_MAP, &methods::UNINIT_ASSUMED_INIT, &methods::UNNECESSARY_FILTER_MAP, &methods::UNNECESSARY_FOLD, &methods::UNNECESSARY_LAZY_EVALUATIONS, &methods::UNWRAP_USED, &methods::USELESS_ASREF, &methods::WRONG_PUB_SELF_CONVENTION, &methods::WRONG_SELF_CONVENTION, &methods::ZST_OFFSET, &minmax::MIN_MAX, &misc::CMP_NAN, &misc::CMP_OWNED, &misc::FLOAT_CMP, &misc::FLOAT_CMP_CONST, &misc::MODULO_ONE, &misc::SHORT_CIRCUIT_STATEMENT, &misc::TOPLEVEL_REF_ARG, &misc::USED_UNDERSCORE_BINDING, &misc::ZERO_PTR, &misc_early::BUILTIN_TYPE_SHADOW, &misc_early::DOUBLE_NEG, &misc_early::DUPLICATE_UNDERSCORE_ARGUMENT, &misc_early::MIXED_CASE_HEX_LITERALS, &misc_early::REDUNDANT_PATTERN, &misc_early::UNNEEDED_FIELD_PATTERN, &misc_early::UNNEEDED_WILDCARD_PATTERN, &misc_early::UNSEPARATED_LITERAL_SUFFIX, &misc_early::ZERO_PREFIXED_LITERAL, &missing_const_for_fn::MISSING_CONST_FOR_FN, &missing_doc::MISSING_DOCS_IN_PRIVATE_ITEMS, &missing_inline::MISSING_INLINE_IN_PUBLIC_ITEMS, &modulo_arithmetic::MODULO_ARITHMETIC, &multiple_crate_versions::MULTIPLE_CRATE_VERSIONS, &mut_key::MUTABLE_KEY_TYPE, &mut_mut::MUT_MUT, &mut_mutex_lock::MUT_MUTEX_LOCK, &mut_reference::UNNECESSARY_MUT_PASSED, &mutable_debug_assertion::DEBUG_ASSERT_WITH_MUT_CALL, &mutex_atomic::MUTEX_ATOMIC, &mutex_atomic::MUTEX_INTEGER, &needless_arbitrary_self_type::NEEDLESS_ARBITRARY_SELF_TYPE, &needless_bool::BOOL_COMPARISON, &needless_bool::NEEDLESS_BOOL, &needless_borrow::NEEDLESS_BORROW, &needless_borrowed_ref::NEEDLESS_BORROWED_REFERENCE, &needless_continue::NEEDLESS_CONTINUE, &needless_pass_by_value::NEEDLESS_PASS_BY_VALUE, &needless_question_mark::NEEDLESS_QUESTION_MARK, &needless_update::NEEDLESS_UPDATE, &neg_cmp_op_on_partial_ord::NEG_CMP_OP_ON_PARTIAL_ORD, &neg_multiply::NEG_MULTIPLY, &new_without_default::NEW_WITHOUT_DEFAULT, &no_effect::NO_EFFECT, &no_effect::UNNECESSARY_OPERATION, &non_copy_const::BORROW_INTERIOR_MUTABLE_CONST, &non_copy_const::DECLARE_INTERIOR_MUTABLE_CONST, &non_expressive_names::JUST_UNDERSCORES_AND_DIGITS, &non_expressive_names::MANY_SINGLE_CHAR_NAMES, &non_expressive_names::SIMILAR_NAMES, &open_options::NONSENSICAL_OPEN_OPTIONS, &option_env_unwrap::OPTION_ENV_UNWRAP, &option_if_let_else::OPTION_IF_LET_ELSE, &overflow_check_conditional::OVERFLOW_CHECK_CONDITIONAL, &panic_in_result_fn::PANIC_IN_RESULT_FN, &panic_unimplemented::PANIC, &panic_unimplemented::TODO, &panic_unimplemented::UNIMPLEMENTED, &panic_unimplemented::UNREACHABLE, &partialeq_ne_impl::PARTIALEQ_NE_IMPL, &pass_by_ref_or_value::LARGE_TYPES_PASSED_BY_VALUE, &pass_by_ref_or_value::TRIVIALLY_COPY_PASS_BY_REF, &path_buf_push_overwrite::PATH_BUF_PUSH_OVERWRITE, &pattern_type_mismatch::PATTERN_TYPE_MISMATCH, &precedence::PRECEDENCE, &ptr::CMP_NULL, &ptr::MUT_FROM_REF, &ptr::PTR_ARG, &ptr_eq::PTR_EQ, &ptr_offset_with_cast::PTR_OFFSET_WITH_CAST, &question_mark::QUESTION_MARK, &ranges::MANUAL_RANGE_CONTAINS, &ranges::RANGE_MINUS_ONE, &ranges::RANGE_PLUS_ONE, &ranges::RANGE_ZIP_WITH_LEN, &ranges::REVERSED_EMPTY_RANGES, &redundant_clone::REDUNDANT_CLONE, &redundant_closure_call::REDUNDANT_CLOSURE_CALL, &redundant_else::REDUNDANT_ELSE, &redundant_field_names::REDUNDANT_FIELD_NAMES, &redundant_pub_crate::REDUNDANT_PUB_CRATE, &redundant_slicing::REDUNDANT_SLICING, &redundant_static_lifetimes::REDUNDANT_STATIC_LIFETIMES, &ref_option_ref::REF_OPTION_REF, &reference::DEREF_ADDROF, &reference::REF_IN_DEREF, &regex::INVALID_REGEX, &regex::TRIVIAL_REGEX, &repeat_once::REPEAT_ONCE, &returns::LET_AND_RETURN, &returns::NEEDLESS_RETURN, &self_assignment::SELF_ASSIGNMENT, &semicolon_if_nothing_returned::SEMICOLON_IF_NOTHING_RETURNED, &serde_api::SERDE_API_MISUSE, &shadow::SHADOW_REUSE, &shadow::SHADOW_SAME, &shadow::SHADOW_UNRELATED, &single_component_path_imports::SINGLE_COMPONENT_PATH_IMPORTS, &size_of_in_element_count::SIZE_OF_IN_ELEMENT_COUNT, &slow_vector_initialization::SLOW_VECTOR_INITIALIZATION, &stable_sort_primitive::STABLE_SORT_PRIMITIVE, &strings::STRING_ADD, &strings::STRING_ADD_ASSIGN, &strings::STRING_FROM_UTF8_AS_BYTES, &strings::STRING_LIT_AS_BYTES, &strings::STRING_TO_STRING, &strings::STR_TO_STRING, &suspicious_operation_groupings::SUSPICIOUS_OPERATION_GROUPINGS, &suspicious_trait_impl::SUSPICIOUS_ARITHMETIC_IMPL, &suspicious_trait_impl::SUSPICIOUS_OP_ASSIGN_IMPL, &swap::ALMOST_SWAPPED, &swap::MANUAL_SWAP, &tabs_in_doc_comments::TABS_IN_DOC_COMMENTS, &temporary_assignment::TEMPORARY_ASSIGNMENT, &to_digit_is_some::TO_DIGIT_IS_SOME, &to_string_in_display::TO_STRING_IN_DISPLAY, &trait_bounds::TRAIT_DUPLICATION_IN_BOUNDS, &trait_bounds::TYPE_REPETITION_IN_BOUNDS, &transmute::CROSSPOINTER_TRANSMUTE, &transmute::TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS, &transmute::TRANSMUTE_BYTES_TO_STR, &transmute::TRANSMUTE_FLOAT_TO_INT, &transmute::TRANSMUTE_INT_TO_BOOL, &transmute::TRANSMUTE_INT_TO_CHAR, &transmute::TRANSMUTE_INT_TO_FLOAT, &transmute::TRANSMUTE_PTR_TO_PTR, &transmute::TRANSMUTE_PTR_TO_REF, &transmute::UNSOUND_COLLECTION_TRANSMUTE, &transmute::USELESS_TRANSMUTE, &transmute::WRONG_TRANSMUTE, &transmuting_null::TRANSMUTING_NULL, &try_err::TRY_ERR, &types::ABSURD_EXTREME_COMPARISONS, &types::BORROWED_BOX, &types::BOX_VEC, &types::CAST_LOSSLESS, &types::CAST_POSSIBLE_TRUNCATION, &types::CAST_POSSIBLE_WRAP, &types::CAST_PRECISION_LOSS, &types::CAST_PTR_ALIGNMENT, &types::CAST_REF_TO_MUT, &types::CAST_SIGN_LOSS, &types::CHAR_LIT_AS_U8, &types::FN_TO_NUMERIC_CAST, &types::FN_TO_NUMERIC_CAST_WITH_TRUNCATION, &types::IMPLICIT_HASHER, &types::INVALID_UPCAST_COMPARISONS, &types::LET_UNIT_VALUE, &types::LINKEDLIST, &types::OPTION_OPTION, &types::PTR_AS_PTR, &types::RC_BUFFER, &types::REDUNDANT_ALLOCATION, &types::TYPE_COMPLEXITY, &types::UNIT_ARG, &types::UNIT_CMP, &types::UNNECESSARY_CAST, &types::VEC_BOX, &undropped_manually_drops::UNDROPPED_MANUALLY_DROPS, &unicode::INVISIBLE_CHARACTERS, &unicode::NON_ASCII_LITERAL, &unicode::UNICODE_NOT_NFC, &unit_return_expecting_ord::UNIT_RETURN_EXPECTING_ORD, &unnamed_address::FN_ADDRESS_COMPARISONS, &unnamed_address::VTABLE_ADDRESS_COMPARISONS, &unnecessary_sort_by::UNNECESSARY_SORT_BY, &unnecessary_wraps::UNNECESSARY_WRAPS, &unnested_or_patterns::UNNESTED_OR_PATTERNS, &unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME, &unused_io_amount::UNUSED_IO_AMOUNT, &unused_self::UNUSED_SELF, &unused_unit::UNUSED_UNIT, &unwrap::PANICKING_UNWRAP, &unwrap::UNNECESSARY_UNWRAP, &unwrap_in_result::UNWRAP_IN_RESULT, &upper_case_acronyms::UPPER_CASE_ACRONYMS, &use_self::USE_SELF, &useless_conversion::USELESS_CONVERSION, &vec::USELESS_VEC, &vec_init_then_push::VEC_INIT_THEN_PUSH, &vec_resize_to_zero::VEC_RESIZE_TO_ZERO, &verbose_file_reads::VERBOSE_FILE_READS, &wildcard_dependencies::WILDCARD_DEPENDENCIES, &wildcard_imports::ENUM_GLOB_USE, &wildcard_imports::WILDCARD_IMPORTS, &write::PRINTLN_EMPTY_STRING, &write::PRINT_LITERAL, &write::PRINT_STDERR, &write::PRINT_STDOUT, &write::PRINT_WITH_NEWLINE, &write::USE_DEBUG, &write::WRITELN_EMPTY_STRING, &write::WRITE_LITERAL, &write::WRITE_WITH_NEWLINE, &zero_div_zero::ZERO_DIVIDED_BY_ZERO, &zero_sized_map_values::ZERO_SIZED_MAP_VALUES, ]); // end register lints, do not remove this comment, it’s used in `update_lints` // all the internal lints #[cfg(feature = "internal-lints")] { store.register_early_pass(|| box utils::internal_lints::ClippyLintsInternal); store.register_early_pass(|| box utils::internal_lints::ProduceIce); store.register_late_pass(|| box utils::inspector::DeepCodeInspector); store.register_late_pass(|| box utils::internal_lints::CollapsibleCalls); store.register_late_pass(|| box utils::internal_lints::CompilerLintFunctions::new()); store.register_late_pass(|| box utils::internal_lints::InvalidPaths); store.register_late_pass(|| box utils::internal_lints::InterningDefinedSymbol::default()); store.register_late_pass(|| box utils::internal_lints::LintWithoutLintPass::default()); store.register_late_pass(|| box utils::internal_lints::MatchTypeOnDiagItem); store.register_late_pass(|| box utils::internal_lints::OuterExpnDataPass); } store.register_late_pass(|| box utils::author::Author); store.register_late_pass(|| box await_holding_invalid::AwaitHolding); store.register_late_pass(|| box serde_api::SerdeApi); let vec_box_size_threshold = conf.vec_box_size_threshold; store.register_late_pass(move || box types::Types::new(vec_box_size_threshold)); store.register_late_pass(|| box booleans::NonminimalBool); store.register_late_pass(|| box eq_op::EqOp); store.register_late_pass(|| box enum_clike::UnportableVariant); store.register_late_pass(|| box float_literal::FloatLiteral); let verbose_bit_mask_threshold = conf.verbose_bit_mask_threshold; store.register_late_pass(move || box bit_mask::BitMask::new(verbose_bit_mask_threshold)); store.register_late_pass(|| box ptr::Ptr); store.register_late_pass(|| box ptr_eq::PtrEq); store.register_late_pass(|| box needless_bool::NeedlessBool); store.register_late_pass(|| box needless_bool::BoolComparison); store.register_late_pass(|| box approx_const::ApproxConstant); store.register_late_pass(|| box misc::MiscLints); store.register_late_pass(|| box eta_reduction::EtaReduction); store.register_late_pass(|| box identity_op::IdentityOp); store.register_late_pass(|| box erasing_op::ErasingOp); store.register_late_pass(|| box mut_mut::MutMut); store.register_late_pass(|| box mut_reference::UnnecessaryMutPassed); store.register_late_pass(|| box len_zero::LenZero); store.register_late_pass(|| box attrs::Attributes); store.register_late_pass(|| box blocks_in_if_conditions::BlocksInIfConditions); store.register_late_pass(|| box collapsible_match::CollapsibleMatch); store.register_late_pass(|| box unicode::Unicode); store.register_late_pass(|| box unit_return_expecting_ord::UnitReturnExpectingOrd); store.register_late_pass(|| box strings::StringAdd); store.register_late_pass(|| box implicit_return::ImplicitReturn); store.register_late_pass(|| box implicit_saturating_sub::ImplicitSaturatingSub); store.register_late_pass(|| box default_numeric_fallback::DefaultNumericFallback); let msrv = conf.msrv.as_ref().and_then(|s| { parse_msrv(s, None, None).or_else(|| { sess.err(&format!("error reading Clippy's configuration file. `{}` is not a valid Rust version", s)); None }) }); store.register_late_pass(move || box methods::Methods::new(msrv)); store.register_late_pass(move || box matches::Matches::new(msrv)); store.register_early_pass(move || box manual_non_exhaustive::ManualNonExhaustive::new(msrv)); store.register_late_pass(move || box manual_strip::ManualStrip::new(msrv)); store.register_early_pass(move || box redundant_static_lifetimes::RedundantStaticLifetimes::new(msrv)); store.register_early_pass(move || box redundant_field_names::RedundantFieldNames::new(msrv)); store.register_late_pass(move || box checked_conversions::CheckedConversions::new(msrv)); store.register_late_pass(move || box mem_replace::MemReplace::new(msrv)); store.register_late_pass(move || box ranges::Ranges::new(msrv)); store.register_late_pass(move || box from_over_into::FromOverInto::new(msrv)); store.register_late_pass(move || box use_self::UseSelf::new(msrv)); store.register_late_pass(move || box missing_const_for_fn::MissingConstForFn::new(msrv)); store.register_late_pass(move || box needless_question_mark::NeedlessQuestionMark::new(msrv)); store.register_late_pass(|| box size_of_in_element_count::SizeOfInElementCount); store.register_late_pass(|| box map_clone::MapClone); store.register_late_pass(|| box map_err_ignore::MapErrIgnore); store.register_late_pass(|| box shadow::Shadow); store.register_late_pass(|| box types::LetUnitValue); store.register_late_pass(|| box types::UnitCmp); store.register_late_pass(|| box loops::Loops); store.register_late_pass(|| box main_recursion::MainRecursion::default()); store.register_late_pass(|| box lifetimes::Lifetimes); store.register_late_pass(|| box entry::HashMapPass); store.register_late_pass(|| box types::Casts); let type_complexity_threshold = conf.type_complexity_threshold; store.register_late_pass(move || box types::TypeComplexity::new(type_complexity_threshold)); store.register_late_pass(|| box minmax::MinMaxPass); store.register_late_pass(|| box open_options::OpenOptions); store.register_late_pass(|| box zero_div_zero::ZeroDiv); store.register_late_pass(|| box mutex_atomic::Mutex); store.register_late_pass(|| box needless_update::NeedlessUpdate); store.register_late_pass(|| box needless_borrow::NeedlessBorrow::default()); store.register_late_pass(|| box needless_borrowed_ref::NeedlessBorrowedRef); store.register_late_pass(|| box no_effect::NoEffect); store.register_late_pass(|| box temporary_assignment::TemporaryAssignment); store.register_late_pass(|| box transmute::Transmute); let cognitive_complexity_threshold = conf.cognitive_complexity_threshold; store.register_late_pass(move || box cognitive_complexity::CognitiveComplexity::new(cognitive_complexity_threshold)); let too_large_for_stack = conf.too_large_for_stack; store.register_late_pass(move || box escape::BoxedLocal{too_large_for_stack}); store.register_late_pass(move || box vec::UselessVec{too_large_for_stack}); store.register_late_pass(|| box panic_unimplemented::PanicUnimplemented); store.register_late_pass(|| box strings::StringLitAsBytes); store.register_late_pass(|| box derive::Derive); store.register_late_pass(|| box types::CharLitAsU8); store.register_late_pass(|| box get_last_with_len::GetLastWithLen); store.register_late_pass(|| box drop_forget_ref::DropForgetRef); store.register_late_pass(|| box empty_enum::EmptyEnum); store.register_late_pass(|| box types::AbsurdExtremeComparisons); store.register_late_pass(|| box types::InvalidUpcastComparisons); store.register_late_pass(|| box regex::Regex::default()); store.register_late_pass(|| box copies::CopyAndPaste); store.register_late_pass(|| box copy_iterator::CopyIterator); store.register_late_pass(|| box format::UselessFormat); store.register_late_pass(|| box swap::Swap); store.register_late_pass(|| box overflow_check_conditional::OverflowCheckConditional); store.register_late_pass(|| box new_without_default::NewWithoutDefault::default()); let blacklisted_names = conf.blacklisted_names.iter().cloned().collect::<FxHashSet<_>>(); store.register_late_pass(move || box blacklisted_name::BlacklistedName::new(blacklisted_names.clone())); let too_many_arguments_threshold1 = conf.too_many_arguments_threshold; let too_many_lines_threshold2 = conf.too_many_lines_threshold; store.register_late_pass(move || box functions::Functions::new(too_many_arguments_threshold1, too_many_lines_threshold2)); let doc_valid_idents = conf.doc_valid_idents.iter().cloned().collect::<FxHashSet<_>>(); store.register_late_pass(move || box doc::DocMarkdown::new(doc_valid_idents.clone())); store.register_late_pass(|| box neg_multiply::NegMultiply); store.register_late_pass(|| box mem_discriminant::MemDiscriminant); store.register_late_pass(|| box mem_forget::MemForget); store.register_late_pass(|| box arithmetic::Arithmetic::default()); store.register_late_pass(|| box assign_ops::AssignOps); store.register_late_pass(|| box let_if_seq::LetIfSeq); store.register_late_pass(|| box eval_order_dependence::EvalOrderDependence); store.register_late_pass(|| box missing_doc::MissingDoc::new()); store.register_late_pass(|| box missing_inline::MissingInline); store.register_late_pass(move || box exhaustive_items::ExhaustiveItems); store.register_late_pass(|| box if_let_some_result::OkIfLet); store.register_late_pass(|| box partialeq_ne_impl::PartialEqNeImpl); store.register_late_pass(|| box unused_io_amount::UnusedIoAmount); let enum_variant_size_threshold = conf.enum_variant_size_threshold; store.register_late_pass(move || box large_enum_variant::LargeEnumVariant::new(enum_variant_size_threshold)); store.register_late_pass(|| box explicit_write::ExplicitWrite); store.register_late_pass(|| box needless_pass_by_value::NeedlessPassByValue); let pass_by_ref_or_value = pass_by_ref_or_value::PassByRefOrValue::new( conf.trivial_copy_size_limit, conf.pass_by_value_size_limit, &sess.target, ); store.register_late_pass(move || box pass_by_ref_or_value); store.register_late_pass(|| box ref_option_ref::RefOptionRef); store.register_late_pass(|| box try_err::TryErr); store.register_late_pass(|| box bytecount::ByteCount); store.register_late_pass(|| box infinite_iter::InfiniteIter); store.register_late_pass(|| box inline_fn_without_body::InlineFnWithoutBody); store.register_late_pass(|| box useless_conversion::UselessConversion::default()); store.register_late_pass(|| box types::ImplicitHasher); store.register_late_pass(|| box fallible_impl_from::FallibleImplFrom); store.register_late_pass(|| box types::UnitArg); store.register_late_pass(|| box double_comparison::DoubleComparisons); store.register_late_pass(|| box question_mark::QuestionMark); store.register_early_pass(|| box suspicious_operation_groupings::SuspiciousOperationGroupings); store.register_late_pass(|| box suspicious_trait_impl::SuspiciousImpl); store.register_late_pass(|| box map_unit_fn::MapUnit); store.register_late_pass(|| box inherent_impl::MultipleInherentImpl::default()); store.register_late_pass(|| box neg_cmp_op_on_partial_ord::NoNegCompOpForPartialOrd); store.register_late_pass(|| box unwrap::Unwrap); store.register_late_pass(|| box duration_subsec::DurationSubsec); store.register_late_pass(|| box indexing_slicing::IndexingSlicing); store.register_late_pass(|| box non_copy_const::NonCopyConst); store.register_late_pass(|| box ptr_offset_with_cast::PtrOffsetWithCast); store.register_late_pass(|| box redundant_clone::RedundantClone); store.register_late_pass(|| box slow_vector_initialization::SlowVectorInit); store.register_late_pass(|| box unnecessary_sort_by::UnnecessarySortBy); store.register_late_pass(|| box unnecessary_wraps::UnnecessaryWraps); store.register_late_pass(|| box types::RefToMut); store.register_late_pass(|| box assertions_on_constants::AssertionsOnConstants); store.register_late_pass(|| box transmuting_null::TransmutingNull); store.register_late_pass(|| box path_buf_push_overwrite::PathBufPushOverwrite); store.register_late_pass(|| box integer_division::IntegerDivision); store.register_late_pass(|| box inherent_to_string::InherentToString); let max_trait_bounds = conf.max_trait_bounds; store.register_late_pass(move || box trait_bounds::TraitBounds::new(max_trait_bounds)); store.register_late_pass(|| box comparison_chain::ComparisonChain); store.register_late_pass(|| box mut_key::MutableKeyType); store.register_late_pass(|| box modulo_arithmetic::ModuloArithmetic); store.register_early_pass(|| box reference::DerefAddrOf); store.register_early_pass(|| box reference::RefInDeref); store.register_early_pass(|| box double_parens::DoubleParens); store.register_late_pass(|| box to_string_in_display::ToStringInDisplay::new()); store.register_early_pass(|| box unsafe_removed_from_name::UnsafeNameRemoval); store.register_early_pass(|| box if_not_else::IfNotElse); store.register_early_pass(|| box else_if_without_else::ElseIfWithoutElse); store.register_early_pass(|| box int_plus_one::IntPlusOne); store.register_early_pass(|| box formatting::Formatting); store.register_early_pass(|| box misc_early::MiscEarlyLints); store.register_early_pass(|| box redundant_closure_call::RedundantClosureCall); store.register_late_pass(|| box redundant_closure_call::RedundantClosureCall); store.register_early_pass(|| box unused_unit::UnusedUnit); store.register_late_pass(|| box returns::Return); store.register_early_pass(|| box collapsible_if::CollapsibleIf); store.register_early_pass(|| box items_after_statements::ItemsAfterStatements); store.register_early_pass(|| box precedence::Precedence); store.register_early_pass(|| box needless_continue::NeedlessContinue); store.register_early_pass(|| box redundant_else::RedundantElse); store.register_late_pass(|| box create_dir::CreateDir); store.register_early_pass(|| box needless_arbitrary_self_type::NeedlessArbitrarySelfType); let cargo_ignore_publish = conf.cargo_ignore_publish; store.register_late_pass(move || box cargo_common_metadata::CargoCommonMetadata::new(cargo_ignore_publish)); store.register_late_pass(|| box multiple_crate_versions::MultipleCrateVersions); store.register_late_pass(|| box wildcard_dependencies::WildcardDependencies); let literal_representation_lint_fraction_readability = conf.unreadable_literal_lint_fractions; store.register_early_pass(move || box literal_representation::LiteralDigitGrouping::new(literal_representation_lint_fraction_readability)); let literal_representation_threshold = conf.literal_representation_threshold; store.register_early_pass(move || box literal_representation::DecimalLiteralRepresentation::new(literal_representation_threshold)); let enum_variant_name_threshold = conf.enum_variant_name_threshold; store.register_early_pass(move || box enum_variants::EnumVariantNames::new(enum_variant_name_threshold)); store.register_early_pass(|| box tabs_in_doc_comments::TabsInDocComments); store.register_early_pass(|| box upper_case_acronyms::UpperCaseAcronyms); store.register_late_pass(|| box default::Default::default()); store.register_late_pass(|| box unused_self::UnusedSelf); store.register_late_pass(|| box mutable_debug_assertion::DebugAssertWithMutCall); store.register_late_pass(|| box exit::Exit); store.register_late_pass(|| box to_digit_is_some::ToDigitIsSome); let array_size_threshold = conf.array_size_threshold; store.register_late_pass(move || box large_stack_arrays::LargeStackArrays::new(array_size_threshold)); store.register_late_pass(move || box large_const_arrays::LargeConstArrays::new(array_size_threshold)); store.register_late_pass(|| box floating_point_arithmetic::FloatingPointArithmetic); store.register_early_pass(|| box as_conversions::AsConversions); store.register_late_pass(|| box let_underscore::LetUnderscore); store.register_late_pass(|| box atomic_ordering::AtomicOrdering); store.register_early_pass(|| box single_component_path_imports::SingleComponentPathImports); let max_fn_params_bools = conf.max_fn_params_bools; let max_struct_bools = conf.max_struct_bools; store.register_early_pass(move || box excessive_bools::ExcessiveBools::new(max_struct_bools, max_fn_params_bools)); store.register_early_pass(|| box option_env_unwrap::OptionEnvUnwrap); let warn_on_all_wildcard_imports = conf.warn_on_all_wildcard_imports; store.register_late_pass(move || box wildcard_imports::WildcardImports::new(warn_on_all_wildcard_imports)); store.register_late_pass(|| box verbose_file_reads::VerboseFileReads); store.register_late_pass(|| box redundant_pub_crate::RedundantPubCrate::default()); store.register_late_pass(|| box unnamed_address::UnnamedAddress); store.register_late_pass(|| box dereference::Dereferencing); store.register_late_pass(|| box option_if_let_else::OptionIfLetElse); store.register_late_pass(|| box future_not_send::FutureNotSend); store.register_late_pass(|| box if_let_mutex::IfLetMutex); store.register_late_pass(|| box mut_mutex_lock::MutMutexLock); store.register_late_pass(|| box match_on_vec_items::MatchOnVecItems); store.register_late_pass(|| box manual_async_fn::ManualAsyncFn); store.register_late_pass(|| box vec_resize_to_zero::VecResizeToZero); store.register_late_pass(|| box panic_in_result_fn::PanicInResultFn); let single_char_binding_names_threshold = conf.single_char_binding_names_threshold; store.register_early_pass(move || box non_expressive_names::NonExpressiveNames { single_char_binding_names_threshold, }); store.register_early_pass(|| box unnested_or_patterns::UnnestedOrPatterns); store.register_late_pass(|| box macro_use::MacroUseImports::default()); store.register_late_pass(|| box map_identity::MapIdentity); store.register_late_pass(|| box pattern_type_mismatch::PatternTypeMismatch); store.register_late_pass(|| box stable_sort_primitive::StableSortPrimitive); store.register_late_pass(|| box repeat_once::RepeatOnce); store.register_late_pass(|| box unwrap_in_result::UnwrapInResult); store.register_late_pass(|| box self_assignment::SelfAssignment); store.register_late_pass(|| box manual_unwrap_or::ManualUnwrapOr); store.register_late_pass(|| box manual_ok_or::ManualOkOr); store.register_late_pass(|| box float_equality_without_abs::FloatEqualityWithoutAbs); store.register_late_pass(|| box semicolon_if_nothing_returned::SemicolonIfNothingReturned); store.register_late_pass(|| box async_yields_async::AsyncYieldsAsync); let disallowed_methods = conf.disallowed_methods.iter().cloned().collect::<FxHashSet<_>>(); store.register_late_pass(move || box disallowed_method::DisallowedMethod::new(&disallowed_methods)); store.register_early_pass(|| box asm_syntax::InlineAsmX86AttSyntax); store.register_early_pass(|| box asm_syntax::InlineAsmX86IntelSyntax); store.register_late_pass(|| box undropped_manually_drops::UndroppedManuallyDrops); store.register_late_pass(|| box strings::StrToString); store.register_late_pass(|| box strings::StringToString); store.register_late_pass(|| box zero_sized_map_values::ZeroSizedMapValues); store.register_late_pass(|| box vec_init_then_push::VecInitThenPush::default()); store.register_late_pass(move || box types::PtrAsPtr::new(msrv)); store.register_late_pass(|| box case_sensitive_file_extension_comparisons::CaseSensitiveFileExtensionComparisons); store.register_late_pass(|| box redundant_slicing::RedundantSlicing); store.register_late_pass(|| box from_str_radix_10::FromStrRadix10); store.register_group(true, "clippy::restriction", Some("clippy_restriction"), vec![ LintId::of(&arithmetic::FLOAT_ARITHMETIC), LintId::of(&arithmetic::INTEGER_ARITHMETIC), LintId::of(&as_conversions::AS_CONVERSIONS), LintId::of(&asm_syntax::INLINE_ASM_X86_ATT_SYNTAX), LintId::of(&asm_syntax::INLINE_ASM_X86_INTEL_SYNTAX), LintId::of(&create_dir::CREATE_DIR), LintId::of(&dbg_macro::DBG_MACRO), LintId::of(&default_numeric_fallback::DEFAULT_NUMERIC_FALLBACK), LintId::of(&else_if_without_else::ELSE_IF_WITHOUT_ELSE), LintId::of(&exhaustive_items::EXHAUSTIVE_ENUMS), LintId::of(&exhaustive_items::EXHAUSTIVE_STRUCTS), LintId::of(&exit::EXIT), LintId::of(&float_literal::LOSSY_FLOAT_LITERAL), LintId::of(&implicit_return::IMPLICIT_RETURN), LintId::of(&indexing_slicing::INDEXING_SLICING), LintId::of(&inherent_impl::MULTIPLE_INHERENT_IMPL), LintId::of(&integer_division::INTEGER_DIVISION), LintId::of(&let_underscore::LET_UNDERSCORE_MUST_USE), LintId::of(&literal_representation::DECIMAL_LITERAL_REPRESENTATION), LintId::of(&map_err_ignore::MAP_ERR_IGNORE), LintId::of(&matches::REST_PAT_IN_FULLY_BOUND_STRUCTS), LintId::of(&matches::WILDCARD_ENUM_MATCH_ARM), LintId::of(&mem_forget::MEM_FORGET), LintId::of(&methods::CLONE_ON_REF_PTR), LintId::of(&methods::EXPECT_USED), LintId::of(&methods::FILETYPE_IS_FILE), LintId::of(&methods::GET_UNWRAP), LintId::of(&methods::UNWRAP_USED), LintId::of(&methods::WRONG_PUB_SELF_CONVENTION), LintId::of(&misc::FLOAT_CMP_CONST), LintId::of(&misc_early::UNNEEDED_FIELD_PATTERN), LintId::of(&missing_doc::MISSING_DOCS_IN_PRIVATE_ITEMS), LintId::of(&missing_inline::MISSING_INLINE_IN_PUBLIC_ITEMS), LintId::of(&modulo_arithmetic::MODULO_ARITHMETIC), LintId::of(&panic_in_result_fn::PANIC_IN_RESULT_FN), LintId::of(&panic_unimplemented::PANIC), LintId::of(&panic_unimplemented::TODO), LintId::of(&panic_unimplemented::UNIMPLEMENTED), LintId::of(&panic_unimplemented::UNREACHABLE), LintId::of(&pattern_type_mismatch::PATTERN_TYPE_MISMATCH), LintId::of(&semicolon_if_nothing_returned::SEMICOLON_IF_NOTHING_RETURNED), LintId::of(&shadow::SHADOW_REUSE), LintId::of(&shadow::SHADOW_SAME), LintId::of(&strings::STRING_ADD), LintId::of(&strings::STRING_TO_STRING), LintId::of(&strings::STR_TO_STRING), LintId::of(&types::RC_BUFFER), LintId::of(&unwrap_in_result::UNWRAP_IN_RESULT), LintId::of(&verbose_file_reads::VERBOSE_FILE_READS), LintId::of(&write::PRINT_STDERR), LintId::of(&write::PRINT_STDOUT), LintId::of(&write::USE_DEBUG), ]); store.register_group(true, "clippy::pedantic", Some("clippy_pedantic"), vec![ LintId::of(&attrs::INLINE_ALWAYS), LintId::of(&await_holding_invalid::AWAIT_HOLDING_LOCK), LintId::of(&await_holding_invalid::AWAIT_HOLDING_REFCELL_REF), LintId::of(&bit_mask::VERBOSE_BIT_MASK), LintId::of(&case_sensitive_file_extension_comparisons::CASE_SENSITIVE_FILE_EXTENSION_COMPARISONS), LintId::of(&checked_conversions::CHECKED_CONVERSIONS), LintId::of(&copies::SAME_FUNCTIONS_IN_IF_CONDITION), LintId::of(&copy_iterator::COPY_ITERATOR), LintId::of(&default::DEFAULT_TRAIT_ACCESS), LintId::of(&dereference::EXPLICIT_DEREF_METHODS), LintId::of(&derive::EXPL_IMPL_CLONE_ON_COPY), LintId::of(&derive::UNSAFE_DERIVE_DESERIALIZE), LintId::of(&doc::DOC_MARKDOWN), LintId::of(&doc::MISSING_ERRORS_DOC), LintId::of(&doc::MISSING_PANICS_DOC), LintId::of(&empty_enum::EMPTY_ENUM), LintId::of(&enum_variants::MODULE_NAME_REPETITIONS), LintId::of(&enum_variants::PUB_ENUM_VARIANT_NAMES), LintId::of(&eta_reduction::REDUNDANT_CLOSURE_FOR_METHOD_CALLS), LintId::of(&excessive_bools::FN_PARAMS_EXCESSIVE_BOOLS), LintId::of(&excessive_bools::STRUCT_EXCESSIVE_BOOLS), LintId::of(&functions::MUST_USE_CANDIDATE), LintId::of(&functions::TOO_MANY_LINES), LintId::of(&if_not_else::IF_NOT_ELSE), LintId::of(&implicit_saturating_sub::IMPLICIT_SATURATING_SUB), LintId::of(&infinite_iter::MAYBE_INFINITE_ITER), LintId::of(&items_after_statements::ITEMS_AFTER_STATEMENTS), LintId::of(&large_stack_arrays::LARGE_STACK_ARRAYS), LintId::of(&let_underscore::LET_UNDERSCORE_DROP), LintId::of(&literal_representation::LARGE_DIGIT_GROUPS), LintId::of(&literal_representation::UNREADABLE_LITERAL), LintId::of(&loops::EXPLICIT_INTO_ITER_LOOP), LintId::of(&loops::EXPLICIT_ITER_LOOP), LintId::of(&macro_use::MACRO_USE_IMPORTS), LintId::of(&manual_ok_or::MANUAL_OK_OR), LintId::of(&match_on_vec_items::MATCH_ON_VEC_ITEMS), LintId::of(&matches::MATCH_BOOL), LintId::of(&matches::MATCH_SAME_ARMS), LintId::of(&matches::MATCH_WILDCARD_FOR_SINGLE_VARIANTS), LintId::of(&matches::MATCH_WILD_ERR_ARM), LintId::of(&matches::SINGLE_MATCH_ELSE), LintId::of(&methods::FILTER_MAP), LintId::of(&methods::FILTER_MAP_NEXT), LintId::of(&methods::INEFFICIENT_TO_STRING), LintId::of(&methods::MAP_FLATTEN), LintId::of(&methods::MAP_UNWRAP_OR), LintId::of(&misc::USED_UNDERSCORE_BINDING), LintId::of(&misc_early::UNSEPARATED_LITERAL_SUFFIX), LintId::of(&mut_mut::MUT_MUT), LintId::of(&needless_continue::NEEDLESS_CONTINUE), LintId::of(&needless_pass_by_value::NEEDLESS_PASS_BY_VALUE), LintId::of(&non_expressive_names::SIMILAR_NAMES), LintId::of(&option_if_let_else::OPTION_IF_LET_ELSE), LintId::of(&pass_by_ref_or_value::LARGE_TYPES_PASSED_BY_VALUE), LintId::of(&pass_by_ref_or_value::TRIVIALLY_COPY_PASS_BY_REF), LintId::of(&ranges::RANGE_MINUS_ONE), LintId::of(&ranges::RANGE_PLUS_ONE), LintId::of(&redundant_else::REDUNDANT_ELSE), LintId::of(&ref_option_ref::REF_OPTION_REF), LintId::of(&shadow::SHADOW_UNRELATED), LintId::of(&strings::STRING_ADD_ASSIGN), LintId::of(&trait_bounds::TRAIT_DUPLICATION_IN_BOUNDS), LintId::of(&trait_bounds::TYPE_REPETITION_IN_BOUNDS), LintId::of(&types::CAST_LOSSLESS), LintId::of(&types::CAST_POSSIBLE_TRUNCATION), LintId::of(&types::CAST_POSSIBLE_WRAP), LintId::of(&types::CAST_PRECISION_LOSS), LintId::of(&types::CAST_PTR_ALIGNMENT), LintId::of(&types::CAST_SIGN_LOSS), LintId::of(&types::IMPLICIT_HASHER), LintId::of(&types::INVALID_UPCAST_COMPARISONS), LintId::of(&types::LET_UNIT_VALUE), LintId::of(&types::LINKEDLIST), LintId::of(&types::OPTION_OPTION), LintId::of(&types::PTR_AS_PTR), LintId::of(&unicode::NON_ASCII_LITERAL), LintId::of(&unicode::UNICODE_NOT_NFC), LintId::of(&unnested_or_patterns::UNNESTED_OR_PATTERNS), LintId::of(&unused_self::UNUSED_SELF), LintId::of(&wildcard_imports::ENUM_GLOB_USE), LintId::of(&wildcard_imports::WILDCARD_IMPORTS), LintId::of(&zero_sized_map_values::ZERO_SIZED_MAP_VALUES), ]); #[cfg(feature = "internal-lints")] store.register_group(true, "clippy::internal", Some("clippy_internal"), vec![ LintId::of(&utils::internal_lints::CLIPPY_LINTS_INTERNAL), LintId::of(&utils::internal_lints::COLLAPSIBLE_SPAN_LINT_CALLS), LintId::of(&utils::internal_lints::COMPILER_LINT_FUNCTIONS), LintId::of(&utils::internal_lints::DEFAULT_LINT), LintId::of(&utils::internal_lints::INTERNING_DEFINED_SYMBOL), LintId::of(&utils::internal_lints::INVALID_PATHS), LintId::of(&utils::internal_lints::LINT_WITHOUT_LINT_PASS), LintId::of(&utils::internal_lints::MATCH_TYPE_ON_DIAGNOSTIC_ITEM), LintId::of(&utils::internal_lints::OUTER_EXPN_EXPN_DATA), LintId::of(&utils::internal_lints::PRODUCE_ICE), LintId::of(&utils::internal_lints::UNNECESSARY_SYMBOL_STR), ]); store.register_group(true, "clippy::all", Some("clippy"), vec![ LintId::of(&approx_const::APPROX_CONSTANT), LintId::of(&assertions_on_constants::ASSERTIONS_ON_CONSTANTS), LintId::of(&assign_ops::ASSIGN_OP_PATTERN), LintId::of(&assign_ops::MISREFACTORED_ASSIGN_OP), LintId::of(&async_yields_async::ASYNC_YIELDS_ASYNC), LintId::of(&atomic_ordering::INVALID_ATOMIC_ORDERING), LintId::of(&attrs::BLANKET_CLIPPY_RESTRICTION_LINTS), LintId::of(&attrs::DEPRECATED_CFG_ATTR), LintId::of(&attrs::DEPRECATED_SEMVER), LintId::of(&attrs::MISMATCHED_TARGET_OS), LintId::of(&attrs::USELESS_ATTRIBUTE), LintId::of(&bit_mask::BAD_BIT_MASK), LintId::of(&bit_mask::INEFFECTIVE_BIT_MASK), LintId::of(&blacklisted_name::BLACKLISTED_NAME), LintId::of(&blocks_in_if_conditions::BLOCKS_IN_IF_CONDITIONS), LintId::of(&booleans::LOGIC_BUG), LintId::of(&booleans::NONMINIMAL_BOOL), LintId::of(&bytecount::NAIVE_BYTECOUNT), LintId::of(&collapsible_if::COLLAPSIBLE_ELSE_IF), LintId::of(&collapsible_if::COLLAPSIBLE_IF), LintId::of(&collapsible_match::COLLAPSIBLE_MATCH), LintId::of(&comparison_chain::COMPARISON_CHAIN), LintId::of(&copies::IFS_SAME_COND), LintId::of(&copies::IF_SAME_THEN_ELSE), LintId::of(&default::FIELD_REASSIGN_WITH_DEFAULT), LintId::of(&derive::DERIVE_HASH_XOR_EQ), LintId::of(&derive::DERIVE_ORD_XOR_PARTIAL_ORD), LintId::of(&doc::MISSING_SAFETY_DOC), LintId::of(&doc::NEEDLESS_DOCTEST_MAIN), LintId::of(&double_comparison::DOUBLE_COMPARISONS), LintId::of(&double_parens::DOUBLE_PARENS), LintId::of(&drop_forget_ref::DROP_COPY), LintId::of(&drop_forget_ref::DROP_REF), LintId::of(&drop_forget_ref::FORGET_COPY), LintId::of(&drop_forget_ref::FORGET_REF), LintId::of(&duration_subsec::DURATION_SUBSEC), LintId::of(&entry::MAP_ENTRY), LintId::of(&enum_clike::ENUM_CLIKE_UNPORTABLE_VARIANT), LintId::of(&enum_variants::ENUM_VARIANT_NAMES), LintId::of(&enum_variants::MODULE_INCEPTION), LintId::of(&eq_op::EQ_OP), LintId::of(&eq_op::OP_REF), LintId::of(&erasing_op::ERASING_OP), LintId::of(&escape::BOXED_LOCAL), LintId::of(&eta_reduction::REDUNDANT_CLOSURE), LintId::of(&eval_order_dependence::DIVERGING_SUB_EXPRESSION), LintId::of(&eval_order_dependence::EVAL_ORDER_DEPENDENCE), LintId::of(&explicit_write::EXPLICIT_WRITE), LintId::of(&float_equality_without_abs::FLOAT_EQUALITY_WITHOUT_ABS), LintId::of(&float_literal::EXCESSIVE_PRECISION), LintId::of(&format::USELESS_FORMAT), LintId::of(&formatting::POSSIBLE_MISSING_COMMA), LintId::of(&formatting::SUSPICIOUS_ASSIGNMENT_FORMATTING), LintId::of(&formatting::SUSPICIOUS_ELSE_FORMATTING), LintId::of(&formatting::SUSPICIOUS_UNARY_OP_FORMATTING), LintId::of(&from_over_into::FROM_OVER_INTO), LintId::of(&from_str_radix_10::FROM_STR_RADIX_10), LintId::of(&functions::DOUBLE_MUST_USE), LintId::of(&functions::MUST_USE_UNIT), LintId::of(&functions::NOT_UNSAFE_PTR_ARG_DEREF), LintId::of(&functions::RESULT_UNIT_ERR), LintId::of(&functions::TOO_MANY_ARGUMENTS), LintId::of(&get_last_with_len::GET_LAST_WITH_LEN), LintId::of(&identity_op::IDENTITY_OP), LintId::of(&if_let_mutex::IF_LET_MUTEX), LintId::of(&if_let_some_result::IF_LET_SOME_RESULT), LintId::of(&indexing_slicing::OUT_OF_BOUNDS_INDEXING), LintId::of(&infinite_iter::INFINITE_ITER), LintId::of(&inherent_to_string::INHERENT_TO_STRING), LintId::of(&inherent_to_string::INHERENT_TO_STRING_SHADOW_DISPLAY), LintId::of(&inline_fn_without_body::INLINE_FN_WITHOUT_BODY), LintId::of(&int_plus_one::INT_PLUS_ONE), LintId::of(&large_const_arrays::LARGE_CONST_ARRAYS), LintId::of(&large_enum_variant::LARGE_ENUM_VARIANT), LintId::of(&len_zero::COMPARISON_TO_EMPTY), LintId::of(&len_zero::LEN_WITHOUT_IS_EMPTY), LintId::of(&len_zero::LEN_ZERO), LintId::of(&let_underscore::LET_UNDERSCORE_LOCK), LintId::of(&lifetimes::EXTRA_UNUSED_LIFETIMES), LintId::of(&lifetimes::NEEDLESS_LIFETIMES), LintId::of(&literal_representation::INCONSISTENT_DIGIT_GROUPING), LintId::of(&literal_representation::MISTYPED_LITERAL_SUFFIXES), LintId::of(&literal_representation::UNUSUAL_BYTE_GROUPINGS), LintId::of(&loops::EMPTY_LOOP), LintId::of(&loops::EXPLICIT_COUNTER_LOOP), LintId::of(&loops::FOR_KV_MAP), LintId::of(&loops::FOR_LOOPS_OVER_FALLIBLES), LintId::of(&loops::ITER_NEXT_LOOP), LintId::of(&loops::MANUAL_FLATTEN), LintId::of(&loops::MANUAL_MEMCPY), LintId::of(&loops::MUT_RANGE_BOUND), LintId::of(&loops::NEEDLESS_COLLECT), LintId::of(&loops::NEEDLESS_RANGE_LOOP), LintId::of(&loops::NEVER_LOOP), LintId::of(&loops::SAME_ITEM_PUSH), LintId::of(&loops::SINGLE_ELEMENT_LOOP), LintId::of(&loops::WHILE_IMMUTABLE_CONDITION), LintId::of(&loops::WHILE_LET_LOOP), LintId::of(&loops::WHILE_LET_ON_ITERATOR), LintId::of(&main_recursion::MAIN_RECURSION), LintId::of(&manual_async_fn::MANUAL_ASYNC_FN), LintId::of(&manual_non_exhaustive::MANUAL_NON_EXHAUSTIVE), LintId::of(&manual_strip::MANUAL_STRIP), LintId::of(&manual_unwrap_or::MANUAL_UNWRAP_OR), LintId::of(&map_clone::MAP_CLONE), LintId::of(&map_identity::MAP_IDENTITY), LintId::of(&map_unit_fn::OPTION_MAP_UNIT_FN), LintId::of(&map_unit_fn::RESULT_MAP_UNIT_FN), LintId::of(&matches::INFALLIBLE_DESTRUCTURING_MATCH), LintId::of(&matches::MATCH_AS_REF), LintId::of(&matches::MATCH_LIKE_MATCHES_MACRO), LintId::of(&matches::MATCH_OVERLAPPING_ARM), LintId::of(&matches::MATCH_REF_PATS), LintId::of(&matches::MATCH_SINGLE_BINDING), LintId::of(&matches::REDUNDANT_PATTERN_MATCHING), LintId::of(&matches::SINGLE_MATCH), LintId::of(&matches::WILDCARD_IN_OR_PATTERNS), LintId::of(&mem_discriminant::MEM_DISCRIMINANT_NON_ENUM), LintId::of(&mem_replace::MEM_REPLACE_OPTION_WITH_NONE), LintId::of(&mem_replace::MEM_REPLACE_WITH_DEFAULT), LintId::of(&mem_replace::MEM_REPLACE_WITH_UNINIT), LintId::of(&methods::BIND_INSTEAD_OF_MAP), LintId::of(&methods::BYTES_NTH), LintId::of(&methods::CHARS_LAST_CMP), LintId::of(&methods::CHARS_NEXT_CMP), LintId::of(&methods::CLONE_DOUBLE_REF), LintId::of(&methods::CLONE_ON_COPY), LintId::of(&methods::EXPECT_FUN_CALL), LintId::of(&methods::FILTER_MAP_IDENTITY), LintId::of(&methods::FILTER_NEXT), LintId::of(&methods::FLAT_MAP_IDENTITY), LintId::of(&methods::FROM_ITER_INSTEAD_OF_COLLECT), LintId::of(&methods::INSPECT_FOR_EACH), LintId::of(&methods::INTO_ITER_ON_REF), LintId::of(&methods::ITERATOR_STEP_BY_ZERO), LintId::of(&methods::ITER_CLONED_COLLECT), LintId::of(&methods::ITER_NEXT_SLICE), LintId::of(&methods::ITER_NTH), LintId::of(&methods::ITER_NTH_ZERO), LintId::of(&methods::ITER_SKIP_NEXT), LintId::of(&methods::MANUAL_FILTER_MAP), LintId::of(&methods::MANUAL_FIND_MAP), LintId::of(&methods::MANUAL_SATURATING_ARITHMETIC), LintId::of(&methods::MAP_COLLECT_RESULT_UNIT), LintId::of(&methods::NEW_RET_NO_SELF), LintId::of(&methods::OK_EXPECT), LintId::of(&methods::OPTION_AS_REF_DEREF), LintId::of(&methods::OPTION_MAP_OR_NONE), LintId::of(&methods::OR_FUN_CALL), LintId::of(&methods::RESULT_MAP_OR_INTO_OPTION), LintId::of(&methods::SEARCH_IS_SOME), LintId::of(&methods::SHOULD_IMPLEMENT_TRAIT), LintId::of(&methods::SINGLE_CHAR_ADD_STR), LintId::of(&methods::SINGLE_CHAR_PATTERN), LintId::of(&methods::SKIP_WHILE_NEXT), LintId::of(&methods::STRING_EXTEND_CHARS), LintId::of(&methods::SUSPICIOUS_MAP), LintId::of(&methods::UNINIT_ASSUMED_INIT), LintId::of(&methods::UNNECESSARY_FILTER_MAP), LintId::of(&methods::UNNECESSARY_FOLD), LintId::of(&methods::UNNECESSARY_LAZY_EVALUATIONS), LintId::of(&methods::USELESS_ASREF), LintId::of(&methods::WRONG_SELF_CONVENTION), LintId::of(&methods::ZST_OFFSET), LintId::of(&minmax::MIN_MAX), LintId::of(&misc::CMP_NAN), LintId::of(&misc::CMP_OWNED), LintId::of(&misc::FLOAT_CMP), LintId::of(&misc::MODULO_ONE), LintId::of(&misc::SHORT_CIRCUIT_STATEMENT), LintId::of(&misc::TOPLEVEL_REF_ARG), LintId::of(&misc::ZERO_PTR), LintId::of(&misc_early::BUILTIN_TYPE_SHADOW), LintId::of(&misc_early::DOUBLE_NEG), LintId::of(&misc_early::DUPLICATE_UNDERSCORE_ARGUMENT), LintId::of(&misc_early::MIXED_CASE_HEX_LITERALS), LintId::of(&misc_early::REDUNDANT_PATTERN), LintId::of(&misc_early::UNNEEDED_WILDCARD_PATTERN), LintId::of(&misc_early::ZERO_PREFIXED_LITERAL), LintId::of(&mut_key::MUTABLE_KEY_TYPE), LintId::of(&mut_mutex_lock::MUT_MUTEX_LOCK), LintId::of(&mut_reference::UNNECESSARY_MUT_PASSED), LintId::of(&mutex_atomic::MUTEX_ATOMIC), LintId::of(&needless_arbitrary_self_type::NEEDLESS_ARBITRARY_SELF_TYPE), LintId::of(&needless_bool::BOOL_COMPARISON), LintId::of(&needless_bool::NEEDLESS_BOOL), LintId::of(&needless_borrowed_ref::NEEDLESS_BORROWED_REFERENCE), LintId::of(&needless_question_mark::NEEDLESS_QUESTION_MARK), LintId::of(&needless_update::NEEDLESS_UPDATE), LintId::of(&neg_cmp_op_on_partial_ord::NEG_CMP_OP_ON_PARTIAL_ORD), LintId::of(&neg_multiply::NEG_MULTIPLY), LintId::of(&new_without_default::NEW_WITHOUT_DEFAULT), LintId::of(&no_effect::NO_EFFECT), LintId::of(&no_effect::UNNECESSARY_OPERATION), LintId::of(&non_copy_const::BORROW_INTERIOR_MUTABLE_CONST), LintId::of(&non_copy_const::DECLARE_INTERIOR_MUTABLE_CONST), LintId::of(&non_expressive_names::JUST_UNDERSCORES_AND_DIGITS), LintId::of(&non_expressive_names::MANY_SINGLE_CHAR_NAMES), LintId::of(&open_options::NONSENSICAL_OPEN_OPTIONS), LintId::of(&option_env_unwrap::OPTION_ENV_UNWRAP), LintId::of(&overflow_check_conditional::OVERFLOW_CHECK_CONDITIONAL), LintId::of(&partialeq_ne_impl::PARTIALEQ_NE_IMPL), LintId::of(&precedence::PRECEDENCE), LintId::of(&ptr::CMP_NULL), LintId::of(&ptr::MUT_FROM_REF), LintId::of(&ptr::PTR_ARG), LintId::of(&ptr_eq::PTR_EQ), LintId::of(&ptr_offset_with_cast::PTR_OFFSET_WITH_CAST), LintId::of(&question_mark::QUESTION_MARK), LintId::of(&ranges::MANUAL_RANGE_CONTAINS), LintId::of(&ranges::RANGE_ZIP_WITH_LEN), LintId::of(&ranges::REVERSED_EMPTY_RANGES), LintId::of(&redundant_clone::REDUNDANT_CLONE), LintId::of(&redundant_closure_call::REDUNDANT_CLOSURE_CALL), LintId::of(&redundant_field_names::REDUNDANT_FIELD_NAMES), LintId::of(&redundant_slicing::REDUNDANT_SLICING), LintId::of(&redundant_static_lifetimes::REDUNDANT_STATIC_LIFETIMES), LintId::of(&reference::DEREF_ADDROF), LintId::of(&reference::REF_IN_DEREF), LintId::of(&regex::INVALID_REGEX), LintId::of(&repeat_once::REPEAT_ONCE), LintId::of(&returns::LET_AND_RETURN), LintId::of(&returns::NEEDLESS_RETURN), LintId::of(&self_assignment::SELF_ASSIGNMENT), LintId::of(&serde_api::SERDE_API_MISUSE), LintId::of(&single_component_path_imports::SINGLE_COMPONENT_PATH_IMPORTS), LintId::of(&size_of_in_element_count::SIZE_OF_IN_ELEMENT_COUNT), LintId::of(&slow_vector_initialization::SLOW_VECTOR_INITIALIZATION), LintId::of(&stable_sort_primitive::STABLE_SORT_PRIMITIVE), LintId::of(&strings::STRING_FROM_UTF8_AS_BYTES), LintId::of(&suspicious_operation_groupings::SUSPICIOUS_OPERATION_GROUPINGS), LintId::of(&suspicious_trait_impl::SUSPICIOUS_ARITHMETIC_IMPL), LintId::of(&suspicious_trait_impl::SUSPICIOUS_OP_ASSIGN_IMPL), LintId::of(&swap::ALMOST_SWAPPED), LintId::of(&swap::MANUAL_SWAP), LintId::of(&tabs_in_doc_comments::TABS_IN_DOC_COMMENTS), LintId::of(&temporary_assignment::TEMPORARY_ASSIGNMENT), LintId::of(&to_digit_is_some::TO_DIGIT_IS_SOME), LintId::of(&to_string_in_display::TO_STRING_IN_DISPLAY), LintId::of(&transmute::CROSSPOINTER_TRANSMUTE), LintId::of(&transmute::TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS), LintId::of(&transmute::TRANSMUTE_BYTES_TO_STR), LintId::of(&transmute::TRANSMUTE_FLOAT_TO_INT), LintId::of(&transmute::TRANSMUTE_INT_TO_BOOL), LintId::of(&transmute::TRANSMUTE_INT_TO_CHAR), LintId::of(&transmute::TRANSMUTE_INT_TO_FLOAT), LintId::of(&transmute::TRANSMUTE_PTR_TO_PTR), LintId::of(&transmute::TRANSMUTE_PTR_TO_REF), LintId::of(&transmute::UNSOUND_COLLECTION_TRANSMUTE), LintId::of(&transmute::WRONG_TRANSMUTE), LintId::of(&transmuting_null::TRANSMUTING_NULL), LintId::of(&try_err::TRY_ERR), LintId::of(&types::ABSURD_EXTREME_COMPARISONS), LintId::of(&types::BORROWED_BOX), LintId::of(&types::BOX_VEC), LintId::of(&types::CAST_REF_TO_MUT), LintId::of(&types::CHAR_LIT_AS_U8), LintId::of(&types::FN_TO_NUMERIC_CAST), LintId::of(&types::FN_TO_NUMERIC_CAST_WITH_TRUNCATION), LintId::of(&types::REDUNDANT_ALLOCATION), LintId::of(&types::TYPE_COMPLEXITY), LintId::of(&types::UNIT_ARG), LintId::of(&types::UNIT_CMP), LintId::of(&types::UNNECESSARY_CAST), LintId::of(&types::VEC_BOX), LintId::of(&undropped_manually_drops::UNDROPPED_MANUALLY_DROPS), LintId::of(&unicode::INVISIBLE_CHARACTERS), LintId::of(&unit_return_expecting_ord::UNIT_RETURN_EXPECTING_ORD), LintId::of(&unnamed_address::FN_ADDRESS_COMPARISONS), LintId::of(&unnamed_address::VTABLE_ADDRESS_COMPARISONS), LintId::of(&unnecessary_sort_by::UNNECESSARY_SORT_BY), LintId::of(&unnecessary_wraps::UNNECESSARY_WRAPS), LintId::of(&unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME), LintId::of(&unused_io_amount::UNUSED_IO_AMOUNT), LintId::of(&unused_unit::UNUSED_UNIT), LintId::of(&unwrap::PANICKING_UNWRAP), LintId::of(&unwrap::UNNECESSARY_UNWRAP), LintId::of(&upper_case_acronyms::UPPER_CASE_ACRONYMS), LintId::of(&useless_conversion::USELESS_CONVERSION), LintId::of(&vec::USELESS_VEC), LintId::of(&vec_init_then_push::VEC_INIT_THEN_PUSH), LintId::of(&vec_resize_to_zero::VEC_RESIZE_TO_ZERO), LintId::of(&write::PRINTLN_EMPTY_STRING), LintId::of(&write::PRINT_LITERAL), LintId::of(&write::PRINT_WITH_NEWLINE), LintId::of(&write::WRITELN_EMPTY_STRING), LintId::of(&write::WRITE_LITERAL), LintId::of(&write::WRITE_WITH_NEWLINE), LintId::of(&zero_div_zero::ZERO_DIVIDED_BY_ZERO), ]); store.register_group(true, "clippy::style", Some("clippy_style"), vec![ LintId::of(&assertions_on_constants::ASSERTIONS_ON_CONSTANTS), LintId::of(&assign_ops::ASSIGN_OP_PATTERN), LintId::of(&attrs::BLANKET_CLIPPY_RESTRICTION_LINTS), LintId::of(&blacklisted_name::BLACKLISTED_NAME), LintId::of(&blocks_in_if_conditions::BLOCKS_IN_IF_CONDITIONS), LintId::of(&collapsible_if::COLLAPSIBLE_ELSE_IF), LintId::of(&collapsible_if::COLLAPSIBLE_IF), LintId::of(&collapsible_match::COLLAPSIBLE_MATCH), LintId::of(&comparison_chain::COMPARISON_CHAIN), LintId::of(&default::FIELD_REASSIGN_WITH_DEFAULT), LintId::of(&doc::MISSING_SAFETY_DOC), LintId::of(&doc::NEEDLESS_DOCTEST_MAIN), LintId::of(&enum_variants::ENUM_VARIANT_NAMES), LintId::of(&enum_variants::MODULE_INCEPTION), LintId::of(&eq_op::OP_REF), LintId::of(&eta_reduction::REDUNDANT_CLOSURE), LintId::of(&float_literal::EXCESSIVE_PRECISION), LintId::of(&formatting::SUSPICIOUS_ASSIGNMENT_FORMATTING), LintId::of(&formatting::SUSPICIOUS_ELSE_FORMATTING), LintId::of(&formatting::SUSPICIOUS_UNARY_OP_FORMATTING), LintId::of(&from_over_into::FROM_OVER_INTO), LintId::of(&from_str_radix_10::FROM_STR_RADIX_10), LintId::of(&functions::DOUBLE_MUST_USE), LintId::of(&functions::MUST_USE_UNIT), LintId::of(&functions::RESULT_UNIT_ERR), LintId::of(&if_let_some_result::IF_LET_SOME_RESULT), LintId::of(&inherent_to_string::INHERENT_TO_STRING), LintId::of(&len_zero::COMPARISON_TO_EMPTY), LintId::of(&len_zero::LEN_WITHOUT_IS_EMPTY), LintId::of(&len_zero::LEN_ZERO), LintId::of(&literal_representation::INCONSISTENT_DIGIT_GROUPING), LintId::of(&literal_representation::UNUSUAL_BYTE_GROUPINGS), LintId::of(&loops::EMPTY_LOOP), LintId::of(&loops::FOR_KV_MAP), LintId::of(&loops::NEEDLESS_RANGE_LOOP), LintId::of(&loops::SAME_ITEM_PUSH), LintId::of(&loops::WHILE_LET_ON_ITERATOR), LintId::of(&main_recursion::MAIN_RECURSION), LintId::of(&manual_async_fn::MANUAL_ASYNC_FN), LintId::of(&manual_non_exhaustive::MANUAL_NON_EXHAUSTIVE), LintId::of(&map_clone::MAP_CLONE), LintId::of(&matches::INFALLIBLE_DESTRUCTURING_MATCH), LintId::of(&matches::MATCH_LIKE_MATCHES_MACRO), LintId::of(&matches::MATCH_OVERLAPPING_ARM), LintId::of(&matches::MATCH_REF_PATS), LintId::of(&matches::REDUNDANT_PATTERN_MATCHING), LintId::of(&matches::SINGLE_MATCH), LintId::of(&mem_replace::MEM_REPLACE_OPTION_WITH_NONE), LintId::of(&mem_replace::MEM_REPLACE_WITH_DEFAULT), LintId::of(&methods::BYTES_NTH), LintId::of(&methods::CHARS_LAST_CMP), LintId::of(&methods::CHARS_NEXT_CMP), LintId::of(&methods::FROM_ITER_INSTEAD_OF_COLLECT), LintId::of(&methods::INTO_ITER_ON_REF), LintId::of(&methods::ITER_CLONED_COLLECT), LintId::of(&methods::ITER_NEXT_SLICE), LintId::of(&methods::ITER_NTH_ZERO), LintId::of(&methods::ITER_SKIP_NEXT), LintId::of(&methods::MANUAL_SATURATING_ARITHMETIC), LintId::of(&methods::MAP_COLLECT_RESULT_UNIT), LintId::of(&methods::NEW_RET_NO_SELF), LintId::of(&methods::OK_EXPECT), LintId::of(&methods::OPTION_MAP_OR_NONE), LintId::of(&methods::RESULT_MAP_OR_INTO_OPTION), LintId::of(&methods::SHOULD_IMPLEMENT_TRAIT), LintId::of(&methods::SINGLE_CHAR_ADD_STR), LintId::of(&methods::STRING_EXTEND_CHARS), LintId::of(&methods::UNNECESSARY_FOLD), LintId::of(&methods::UNNECESSARY_LAZY_EVALUATIONS), LintId::of(&methods::WRONG_SELF_CONVENTION), LintId::of(&misc::TOPLEVEL_REF_ARG), LintId::of(&misc::ZERO_PTR), LintId::of(&misc_early::BUILTIN_TYPE_SHADOW), LintId::of(&misc_early::DOUBLE_NEG), LintId::of(&misc_early::DUPLICATE_UNDERSCORE_ARGUMENT), LintId::of(&misc_early::MIXED_CASE_HEX_LITERALS), LintId::of(&misc_early::REDUNDANT_PATTERN), LintId::of(&mut_mutex_lock::MUT_MUTEX_LOCK), LintId::of(&mut_reference::UNNECESSARY_MUT_PASSED), LintId::of(&neg_multiply::NEG_MULTIPLY), LintId::of(&new_without_default::NEW_WITHOUT_DEFAULT), LintId::of(&non_copy_const::BORROW_INTERIOR_MUTABLE_CONST), LintId::of(&non_copy_const::DECLARE_INTERIOR_MUTABLE_CONST), LintId::of(&non_expressive_names::JUST_UNDERSCORES_AND_DIGITS), LintId::of(&non_expressive_names::MANY_SINGLE_CHAR_NAMES), LintId::of(&ptr::CMP_NULL), LintId::of(&ptr::PTR_ARG), LintId::of(&ptr_eq::PTR_EQ), LintId::of(&question_mark::QUESTION_MARK), LintId::of(&ranges::MANUAL_RANGE_CONTAINS), LintId::of(&redundant_field_names::REDUNDANT_FIELD_NAMES), LintId::of(&redundant_static_lifetimes::REDUNDANT_STATIC_LIFETIMES), LintId::of(&returns::LET_AND_RETURN), LintId::of(&returns::NEEDLESS_RETURN), LintId::of(&single_component_path_imports::SINGLE_COMPONENT_PATH_IMPORTS), LintId::of(&suspicious_operation_groupings::SUSPICIOUS_OPERATION_GROUPINGS), LintId::of(&tabs_in_doc_comments::TABS_IN_DOC_COMMENTS), LintId::of(&to_digit_is_some::TO_DIGIT_IS_SOME), LintId::of(&try_err::TRY_ERR), LintId::of(&types::FN_TO_NUMERIC_CAST), LintId::of(&types::FN_TO_NUMERIC_CAST_WITH_TRUNCATION), LintId::of(&unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME), LintId::of(&unused_unit::UNUSED_UNIT), LintId::of(&upper_case_acronyms::UPPER_CASE_ACRONYMS), LintId::of(&write::PRINTLN_EMPTY_STRING), LintId::of(&write::PRINT_LITERAL), LintId::of(&write::PRINT_WITH_NEWLINE), LintId::of(&write::WRITELN_EMPTY_STRING), LintId::of(&write::WRITE_LITERAL), LintId::of(&write::WRITE_WITH_NEWLINE), ]); store.register_group(true, "clippy::complexity", Some("clippy_complexity"), vec![ LintId::of(&assign_ops::MISREFACTORED_ASSIGN_OP), LintId::of(&attrs::DEPRECATED_CFG_ATTR), LintId::of(&booleans::NONMINIMAL_BOOL), LintId::of(&double_comparison::DOUBLE_COMPARISONS), LintId::of(&double_parens::DOUBLE_PARENS), LintId::of(&duration_subsec::DURATION_SUBSEC), LintId::of(&eval_order_dependence::DIVERGING_SUB_EXPRESSION), LintId::of(&eval_order_dependence::EVAL_ORDER_DEPENDENCE), LintId::of(&explicit_write::EXPLICIT_WRITE), LintId::of(&format::USELESS_FORMAT), LintId::of(&functions::TOO_MANY_ARGUMENTS), LintId::of(&get_last_with_len::GET_LAST_WITH_LEN), LintId::of(&identity_op::IDENTITY_OP), LintId::of(&int_plus_one::INT_PLUS_ONE), LintId::of(&lifetimes::EXTRA_UNUSED_LIFETIMES), LintId::of(&lifetimes::NEEDLESS_LIFETIMES), LintId::of(&loops::EXPLICIT_COUNTER_LOOP), LintId::of(&loops::MANUAL_FLATTEN), LintId::of(&loops::MUT_RANGE_BOUND), LintId::of(&loops::SINGLE_ELEMENT_LOOP), LintId::of(&loops::WHILE_LET_LOOP), LintId::of(&manual_strip::MANUAL_STRIP), LintId::of(&manual_unwrap_or::MANUAL_UNWRAP_OR), LintId::of(&map_identity::MAP_IDENTITY), LintId::of(&map_unit_fn::OPTION_MAP_UNIT_FN), LintId::of(&map_unit_fn::RESULT_MAP_UNIT_FN), LintId::of(&matches::MATCH_AS_REF), LintId::of(&matches::MATCH_SINGLE_BINDING), LintId::of(&matches::WILDCARD_IN_OR_PATTERNS), LintId::of(&methods::BIND_INSTEAD_OF_MAP), LintId::of(&methods::CLONE_ON_COPY), LintId::of(&methods::FILTER_MAP_IDENTITY), LintId::of(&methods::FILTER_NEXT), LintId::of(&methods::FLAT_MAP_IDENTITY), LintId::of(&methods::INSPECT_FOR_EACH), LintId::of(&methods::MANUAL_FILTER_MAP), LintId::of(&methods::MANUAL_FIND_MAP), LintId::of(&methods::OPTION_AS_REF_DEREF), LintId::of(&methods::SEARCH_IS_SOME), LintId::of(&methods::SKIP_WHILE_NEXT), LintId::of(&methods::SUSPICIOUS_MAP), LintId::of(&methods::UNNECESSARY_FILTER_MAP), LintId::of(&methods::USELESS_ASREF), LintId::of(&misc::SHORT_CIRCUIT_STATEMENT), LintId::of(&misc_early::UNNEEDED_WILDCARD_PATTERN), LintId::of(&misc_early::ZERO_PREFIXED_LITERAL), LintId::of(&needless_arbitrary_self_type::NEEDLESS_ARBITRARY_SELF_TYPE), LintId::of(&needless_bool::BOOL_COMPARISON), LintId::of(&needless_bool::NEEDLESS_BOOL), LintId::of(&needless_borrowed_ref::NEEDLESS_BORROWED_REFERENCE), LintId::of(&needless_question_mark::NEEDLESS_QUESTION_MARK), LintId::of(&needless_update::NEEDLESS_UPDATE), LintId::of(&neg_cmp_op_on_partial_ord::NEG_CMP_OP_ON_PARTIAL_ORD), LintId::of(&no_effect::NO_EFFECT), LintId::of(&no_effect::UNNECESSARY_OPERATION), LintId::of(&overflow_check_conditional::OVERFLOW_CHECK_CONDITIONAL), LintId::of(&partialeq_ne_impl::PARTIALEQ_NE_IMPL), LintId::of(&precedence::PRECEDENCE), LintId::of(&ptr_offset_with_cast::PTR_OFFSET_WITH_CAST), LintId::of(&ranges::RANGE_ZIP_WITH_LEN), LintId::of(&redundant_closure_call::REDUNDANT_CLOSURE_CALL), LintId::of(&redundant_slicing::REDUNDANT_SLICING), LintId::of(&reference::DEREF_ADDROF), LintId::of(&reference::REF_IN_DEREF), LintId::of(&repeat_once::REPEAT_ONCE), LintId::of(&strings::STRING_FROM_UTF8_AS_BYTES), LintId::of(&swap::MANUAL_SWAP), LintId::of(&temporary_assignment::TEMPORARY_ASSIGNMENT), LintId::of(&transmute::CROSSPOINTER_TRANSMUTE), LintId::of(&transmute::TRANSMUTES_EXPRESSIBLE_AS_PTR_CASTS), LintId::of(&transmute::TRANSMUTE_BYTES_TO_STR), LintId::of(&transmute::TRANSMUTE_FLOAT_TO_INT), LintId::of(&transmute::TRANSMUTE_INT_TO_BOOL), LintId::of(&transmute::TRANSMUTE_INT_TO_CHAR), LintId::of(&transmute::TRANSMUTE_INT_TO_FLOAT), LintId::of(&transmute::TRANSMUTE_PTR_TO_PTR), LintId::of(&transmute::TRANSMUTE_PTR_TO_REF), LintId::of(&types::BORROWED_BOX), LintId::of(&types::CHAR_LIT_AS_U8), LintId::of(&types::TYPE_COMPLEXITY), LintId::of(&types::UNIT_ARG), LintId::of(&types::UNNECESSARY_CAST), LintId::of(&types::VEC_BOX), LintId::of(&unnecessary_sort_by::UNNECESSARY_SORT_BY), LintId::of(&unnecessary_wraps::UNNECESSARY_WRAPS), LintId::of(&unwrap::UNNECESSARY_UNWRAP), LintId::of(&useless_conversion::USELESS_CONVERSION), LintId::of(&zero_div_zero::ZERO_DIVIDED_BY_ZERO), ]); store.register_group(true, "clippy::correctness", Some("clippy_correctness"), vec![ LintId::of(&approx_const::APPROX_CONSTANT), LintId::of(&async_yields_async::ASYNC_YIELDS_ASYNC), LintId::of(&atomic_ordering::INVALID_ATOMIC_ORDERING), LintId::of(&attrs::DEPRECATED_SEMVER), LintId::of(&attrs::MISMATCHED_TARGET_OS), LintId::of(&attrs::USELESS_ATTRIBUTE), LintId::of(&bit_mask::BAD_BIT_MASK), LintId::of(&bit_mask::INEFFECTIVE_BIT_MASK), LintId::of(&booleans::LOGIC_BUG), LintId::of(&copies::IFS_SAME_COND), LintId::of(&copies::IF_SAME_THEN_ELSE), LintId::of(&derive::DERIVE_HASH_XOR_EQ), LintId::of(&derive::DERIVE_ORD_XOR_PARTIAL_ORD), LintId::of(&drop_forget_ref::DROP_COPY), LintId::of(&drop_forget_ref::DROP_REF), LintId::of(&drop_forget_ref::FORGET_COPY), LintId::of(&drop_forget_ref::FORGET_REF), LintId::of(&enum_clike::ENUM_CLIKE_UNPORTABLE_VARIANT), LintId::of(&eq_op::EQ_OP), LintId::of(&erasing_op::ERASING_OP), LintId::of(&float_equality_without_abs::FLOAT_EQUALITY_WITHOUT_ABS), LintId::of(&formatting::POSSIBLE_MISSING_COMMA), LintId::of(&functions::NOT_UNSAFE_PTR_ARG_DEREF), LintId::of(&if_let_mutex::IF_LET_MUTEX), LintId::of(&indexing_slicing::OUT_OF_BOUNDS_INDEXING), LintId::of(&infinite_iter::INFINITE_ITER), LintId::of(&inherent_to_string::INHERENT_TO_STRING_SHADOW_DISPLAY), LintId::of(&inline_fn_without_body::INLINE_FN_WITHOUT_BODY), LintId::of(&let_underscore::LET_UNDERSCORE_LOCK), LintId::of(&literal_representation::MISTYPED_LITERAL_SUFFIXES), LintId::of(&loops::FOR_LOOPS_OVER_FALLIBLES), LintId::of(&loops::ITER_NEXT_LOOP), LintId::of(&loops::NEVER_LOOP), LintId::of(&loops::WHILE_IMMUTABLE_CONDITION), LintId::of(&mem_discriminant::MEM_DISCRIMINANT_NON_ENUM), LintId::of(&mem_replace::MEM_REPLACE_WITH_UNINIT), LintId::of(&methods::CLONE_DOUBLE_REF), LintId::of(&methods::ITERATOR_STEP_BY_ZERO), LintId::of(&methods::UNINIT_ASSUMED_INIT), LintId::of(&methods::ZST_OFFSET), LintId::of(&minmax::MIN_MAX), LintId::of(&misc::CMP_NAN), LintId::of(&misc::FLOAT_CMP), LintId::of(&misc::MODULO_ONE), LintId::of(&mut_key::MUTABLE_KEY_TYPE), LintId::of(&open_options::NONSENSICAL_OPEN_OPTIONS), LintId::of(&option_env_unwrap::OPTION_ENV_UNWRAP), LintId::of(&ptr::MUT_FROM_REF), LintId::of(&ranges::REVERSED_EMPTY_RANGES), LintId::of(&regex::INVALID_REGEX), LintId::of(&self_assignment::SELF_ASSIGNMENT), LintId::of(&serde_api::SERDE_API_MISUSE), LintId::of(&size_of_in_element_count::SIZE_OF_IN_ELEMENT_COUNT), LintId::of(&suspicious_trait_impl::SUSPICIOUS_ARITHMETIC_IMPL), LintId::of(&suspicious_trait_impl::SUSPICIOUS_OP_ASSIGN_IMPL), LintId::of(&swap::ALMOST_SWAPPED), LintId::of(&to_string_in_display::TO_STRING_IN_DISPLAY), LintId::of(&transmute::UNSOUND_COLLECTION_TRANSMUTE), LintId::of(&transmute::WRONG_TRANSMUTE), LintId::of(&transmuting_null::TRANSMUTING_NULL), LintId::of(&types::ABSURD_EXTREME_COMPARISONS), LintId::of(&types::CAST_REF_TO_MUT), LintId::of(&types::UNIT_CMP), LintId::of(&undropped_manually_drops::UNDROPPED_MANUALLY_DROPS), LintId::of(&unicode::INVISIBLE_CHARACTERS), LintId::of(&unit_return_expecting_ord::UNIT_RETURN_EXPECTING_ORD), LintId::of(&unnamed_address::FN_ADDRESS_COMPARISONS), LintId::of(&unnamed_address::VTABLE_ADDRESS_COMPARISONS), LintId::of(&unused_io_amount::UNUSED_IO_AMOUNT), LintId::of(&unwrap::PANICKING_UNWRAP), LintId::of(&vec_resize_to_zero::VEC_RESIZE_TO_ZERO), ]); store.register_group(true, "clippy::perf", Some("clippy_perf"), vec![ LintId::of(&bytecount::NAIVE_BYTECOUNT), LintId::of(&entry::MAP_ENTRY), LintId::of(&escape::BOXED_LOCAL), LintId::of(&large_const_arrays::LARGE_CONST_ARRAYS), LintId::of(&large_enum_variant::LARGE_ENUM_VARIANT), LintId::of(&loops::MANUAL_MEMCPY), LintId::of(&loops::NEEDLESS_COLLECT), LintId::of(&methods::EXPECT_FUN_CALL), LintId::of(&methods::ITER_NTH), LintId::of(&methods::OR_FUN_CALL), LintId::of(&methods::SINGLE_CHAR_PATTERN), LintId::of(&misc::CMP_OWNED), LintId::of(&mutex_atomic::MUTEX_ATOMIC), LintId::of(&redundant_clone::REDUNDANT_CLONE), LintId::of(&slow_vector_initialization::SLOW_VECTOR_INITIALIZATION), LintId::of(&stable_sort_primitive::STABLE_SORT_PRIMITIVE), LintId::of(&types::BOX_VEC), LintId::of(&types::REDUNDANT_ALLOCATION), LintId::of(&vec::USELESS_VEC), LintId::of(&vec_init_then_push::VEC_INIT_THEN_PUSH), ]); store.register_group(true, "clippy::cargo", Some("clippy_cargo"), vec![ LintId::of(&cargo_common_metadata::CARGO_COMMON_METADATA), LintId::of(&multiple_crate_versions::MULTIPLE_CRATE_VERSIONS), LintId::of(&wildcard_dependencies::WILDCARD_DEPENDENCIES), ]); store.register_group(true, "clippy::nursery", Some("clippy_nursery"), vec![ LintId::of(&attrs::EMPTY_LINE_AFTER_OUTER_ATTR), LintId::of(&cognitive_complexity::COGNITIVE_COMPLEXITY), LintId::of(&disallowed_method::DISALLOWED_METHOD), LintId::of(&fallible_impl_from::FALLIBLE_IMPL_FROM), LintId::of(&floating_point_arithmetic::IMPRECISE_FLOPS), LintId::of(&floating_point_arithmetic::SUBOPTIMAL_FLOPS), LintId::of(&future_not_send::FUTURE_NOT_SEND), LintId::of(&let_if_seq::USELESS_LET_IF_SEQ), LintId::of(&missing_const_for_fn::MISSING_CONST_FOR_FN), LintId::of(&mutable_debug_assertion::DEBUG_ASSERT_WITH_MUT_CALL), LintId::of(&mutex_atomic::MUTEX_INTEGER), LintId::of(&needless_borrow::NEEDLESS_BORROW), LintId::of(&path_buf_push_overwrite::PATH_BUF_PUSH_OVERWRITE), LintId::of(&redundant_pub_crate::REDUNDANT_PUB_CRATE), LintId::of(&regex::TRIVIAL_REGEX), LintId::of(&strings::STRING_LIT_AS_BYTES), LintId::of(&transmute::USELESS_TRANSMUTE), LintId::of(&use_self::USE_SELF), ]); } #[rustfmt::skip] fn register_removed_non_tool_lints(store: &mut rustc_lint::LintStore) { store.register_removed( "should_assert_eq", "`assert!()` will be more flexible with RFC 2011", ); store.register_removed( "extend_from_slice", "`.extend_from_slice(_)` is a faster way to extend a Vec by a slice", ); store.register_removed( "range_step_by_zero", "`iterator.step_by(0)` panics nowadays", ); store.register_removed( "unstable_as_slice", "`Vec::as_slice` has been stabilized in 1.7", ); store.register_removed( "unstable_as_mut_slice", "`Vec::as_mut_slice` has been stabilized in 1.7", ); store.register_removed( "misaligned_transmute", "this lint has been split into cast_ptr_alignment and transmute_ptr_to_ptr", ); store.register_removed( "assign_ops", "using compound assignment operators (e.g., `+=`) is harmless", ); store.register_removed( "if_let_redundant_pattern_matching", "this lint has been changed to redundant_pattern_matching", ); store.register_removed( "unsafe_vector_initialization", "the replacement suggested by this lint had substantially different behavior", ); store.register_removed( "reverse_range_loop", "this lint is now included in reversed_empty_ranges", ); } /// Register renamed lints. /// /// Used in `./src/driver.rs`. pub fn register_renamed(ls: &mut rustc_lint::LintStore) { ls.register_renamed("clippy::stutter", "clippy::module_name_repetitions"); ls.register_renamed("clippy::new_without_default_derive", "clippy::new_without_default"); ls.register_renamed("clippy::cyclomatic_complexity", "clippy::cognitive_complexity"); ls.register_renamed("clippy::const_static_lifetime", "clippy::redundant_static_lifetimes"); ls.register_renamed("clippy::option_and_then_some", "clippy::bind_instead_of_map"); ls.register_renamed("clippy::block_in_if_condition_expr", "clippy::blocks_in_if_conditions"); ls.register_renamed("clippy::block_in_if_condition_stmt", "clippy::blocks_in_if_conditions"); ls.register_renamed("clippy::option_map_unwrap_or", "clippy::map_unwrap_or"); ls.register_renamed("clippy::option_map_unwrap_or_else", "clippy::map_unwrap_or"); ls.register_renamed("clippy::result_map_unwrap_or_else", "clippy::map_unwrap_or"); ls.register_renamed("clippy::option_unwrap_used", "clippy::unwrap_used"); ls.register_renamed("clippy::result_unwrap_used", "clippy::unwrap_used"); ls.register_renamed("clippy::option_expect_used", "clippy::expect_used"); ls.register_renamed("clippy::result_expect_used", "clippy::expect_used"); ls.register_renamed("clippy::for_loop_over_option", "clippy::for_loops_over_fallibles"); ls.register_renamed("clippy::for_loop_over_result", "clippy::for_loops_over_fallibles"); ls.register_renamed("clippy::identity_conversion", "clippy::useless_conversion"); ls.register_renamed("clippy::zero_width_space", "clippy::invisible_characters"); ls.register_renamed("clippy::single_char_push_str", "clippy::single_char_add_str"); } // only exists to let the dogfood integration test works. // Don't run clippy as an executable directly #[allow(dead_code)] fn main() { panic!("Please use the cargo-clippy executable"); }
47.093529
143
0.704264
d5243e0871243d446e1cdc90eca16f1a29d9616c
34,905
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ block_storage::{BlockReader, BlockStore}, liveness::{ proposal_generator::ProposalGenerator, proposer_election::ProposerElection, rotating_proposer_election::RotatingProposer, round_state::{ExponentialTimeInterval, RoundState}, }, metrics_safety_rules::MetricsSafetyRules, network::{IncomingBlockRetrievalRequest, NetworkSender}, network_interface::{ConsensusMsg, ConsensusNetworkEvents, ConsensusNetworkSender}, network_tests::{NetworkPlayground, TwinId}, persistent_liveness_storage::RecoveryData, round_manager::RoundManager, test_utils::{ consensus_runtime, timed_block_on, MockStateComputer, MockStorage, MockTransactionManager, TreeInserter, }, util::time_service::{ClockTimeService, TimeService}, }; use channel::{self, diem_channel, message_queues::QueueStyle}; use consensus_types::{ block::{ block_test_utils::{certificate_for_genesis, gen_test_certificate}, Block, }, block_retrieval::{BlockRetrievalRequest, BlockRetrievalStatus}, common::{Author, Payload}, proposal_msg::ProposalMsg, sync_info::SyncInfo, timeout::Timeout, timeout_certificate::TimeoutCertificate, vote_msg::VoteMsg, }; use diem_crypto::{ed25519::Ed25519PrivateKey, HashValue, Uniform}; use diem_secure_storage::Storage; use diem_types::{ epoch_state::EpochState, ledger_info::{LedgerInfo, LedgerInfoWithSignatures}, validator_signer::ValidatorSigner, validator_verifier::random_validator_verifier, waypoint::Waypoint, }; use futures::{ channel::{mpsc, oneshot}, executor::block_on, stream::select, Stream, StreamExt, }; use network::{ peer_manager::{conn_notifs_channel, ConnectionRequestSender, PeerManagerRequestSender}, protocols::network::{Event, NewNetworkEvents, NewNetworkSender}, }; use safety_rules::{PersistentSafetyStorage, SafetyRulesManager}; use std::{sync::Arc, time::Duration}; use tokio::runtime::Handle; /// Auxiliary struct that is setting up node environment for the test. pub struct NodeSetup { block_store: Arc<BlockStore>, round_manager: RoundManager, storage: Arc<MockStorage>, signer: ValidatorSigner, proposer_author: Author, safety_rules_manager: SafetyRulesManager, all_events: Box<dyn Stream<Item = Event<ConsensusMsg>> + Send + Unpin>, commit_cb_receiver: mpsc::UnboundedReceiver<LedgerInfoWithSignatures>, _state_sync_receiver: mpsc::UnboundedReceiver<Payload>, id: usize, } impl NodeSetup { fn create_round_state(time_service: Arc<dyn TimeService>) -> RoundState { let base_timeout = Duration::new(60, 0); let time_interval = Box::new(ExponentialTimeInterval::fixed(base_timeout)); let (round_timeout_sender, _) = channel::new_test(1_024); RoundState::new(time_interval, time_service, round_timeout_sender) } fn create_proposer_election(author: Author) -> Box<dyn ProposerElection + Send + Sync> { Box::new(RotatingProposer::new(vec![author], 1)) } fn create_nodes( playground: &mut NetworkPlayground, executor: Handle, num_nodes: usize, ) -> Vec<Self> { let (signers, validators) = random_validator_verifier(num_nodes, None, false); let proposer_author = signers[0].author(); let validator_set = (&validators).into(); let waypoint = Waypoint::new_epoch_boundary(&LedgerInfo::mock_genesis(Some(validator_set))).unwrap(); let mut nodes = vec![]; for (id, signer) in signers.iter().take(num_nodes).enumerate() { let (initial_data, storage) = MockStorage::start_for_testing((&validators).into()); let safety_storage = PersistentSafetyStorage::initialize( Storage::from(diem_secure_storage::InMemoryStorage::new()), signer.author(), signer.private_key().clone(), Ed25519PrivateKey::generate_for_testing(), waypoint, true, ); let safety_rules_manager = SafetyRulesManager::new_local(safety_storage, false, false); nodes.push(Self::new( playground, executor.clone(), signer.to_owned(), proposer_author, storage, initial_data, safety_rules_manager, id, )); } nodes } fn new( playground: &mut NetworkPlayground, executor: Handle, signer: ValidatorSigner, proposer_author: Author, storage: Arc<MockStorage>, initial_data: RecoveryData, safety_rules_manager: SafetyRulesManager, id: usize, ) -> Self { let epoch_state = EpochState { epoch: 1, verifier: storage.get_validator_set().into(), }; let validators = epoch_state.verifier.clone(); let (network_reqs_tx, network_reqs_rx) = diem_channel::new(QueueStyle::FIFO, 8, None); let (connection_reqs_tx, _) = diem_channel::new(QueueStyle::FIFO, 8, None); let (consensus_tx, consensus_rx) = diem_channel::new(QueueStyle::FIFO, 8, None); let (_conn_mgr_reqs_tx, conn_mgr_reqs_rx) = channel::new_test(8); let (_, conn_status_rx) = conn_notifs_channel::new(); let network_sender = ConsensusNetworkSender::new( PeerManagerRequestSender::new(network_reqs_tx), ConnectionRequestSender::new(connection_reqs_tx), ); let network_events = ConsensusNetworkEvents::new(consensus_rx, conn_status_rx); let author = signer.author(); let twin_id = TwinId { id, author }; playground.add_node(twin_id, consensus_tx, network_reqs_rx, conn_mgr_reqs_rx); let (self_sender, self_receiver) = channel::new_test(1000); let network = NetworkSender::new(author, network_sender, self_sender, validators); let all_events = Box::new(select(network_events, self_receiver)); let last_vote_sent = initial_data.last_vote(); let (commit_cb_sender, commit_cb_receiver) = mpsc::unbounded::<LedgerInfoWithSignatures>(); let (state_sync_client, _state_sync_receiver) = mpsc::unbounded(); let state_computer = Arc::new(MockStateComputer::new( state_sync_client, commit_cb_sender, Arc::clone(&storage), )); let time_service = Arc::new(ClockTimeService::new(executor)); let block_store = Arc::new(BlockStore::new( storage.clone(), initial_data, state_computer, 10, // max pruned blocks in mem time_service.clone(), )); let proposal_generator = ProposalGenerator::new( author, block_store.clone(), Arc::new(MockTransactionManager::new(None)), time_service.clone(), 1, ); let round_state = Self::create_round_state(time_service); let proposer_election = Self::create_proposer_election(proposer_author); let mut safety_rules = MetricsSafetyRules::new(safety_rules_manager.client(), storage.clone()); safety_rules.perform_initialize().unwrap(); let mut round_manager = RoundManager::new( epoch_state, Arc::clone(&block_store), round_state, proposer_election, proposal_generator, safety_rules, network, Arc::new(MockTransactionManager::new(None)), storage.clone(), false, ); block_on(round_manager.start(last_vote_sent)); Self { block_store, round_manager, storage, signer, proposer_author, safety_rules_manager, all_events, commit_cb_receiver, _state_sync_receiver, id, } } pub fn restart(self, playground: &mut NetworkPlayground, executor: Handle) -> Self { let recover_data = self .storage .try_start() .unwrap_or_else(|e| panic!("fail to restart due to: {}", e)); Self::new( playground, executor, self.signer, self.proposer_author, self.storage, recover_data, self.safety_rules_manager, self.id, ) } pub async fn next_proposal(&mut self) -> ProposalMsg { match self.all_events.next().await.unwrap() { Event::Message(_, msg) => match msg { ConsensusMsg::ProposalMsg(p) => *p, msg => panic!("Unexpected Consensus Message: {:?}", msg), }, _ => panic!("Unexpected Network Event"), } } pub async fn next_vote(&mut self) -> VoteMsg { match self.all_events.next().await.unwrap() { Event::Message(_, msg) => match msg { ConsensusMsg::VoteMsg(v) => *v, msg => panic!("Unexpected Consensus Message: {:?}", msg), }, _ => panic!("Unexpected Network Event"), } } pub async fn next_sync_info(&mut self) -> SyncInfo { match self.all_events.next().await.unwrap() { Event::Message(_, msg) => match msg { ConsensusMsg::SyncInfo(s) => *s, msg => panic!("Unexpected Consensus Message: {:?}", msg), }, _ => panic!("Unexpected Network Event"), } } pub async fn next_message(&mut self) -> ConsensusMsg { match self.all_events.next().await.unwrap() { Event::Message(_, msg) => msg, _ => panic!("Unexpected Network Event"), } } } #[test] fn new_round_on_quorum_cert() { let mut runtime = consensus_runtime(); let mut playground = NetworkPlayground::new(runtime.handle().clone()); let mut nodes = NodeSetup::create_nodes(&mut playground, runtime.handle().clone(), 1); let node = &mut nodes[0]; let genesis = node.block_store.root(); timed_block_on(&mut runtime, async { // round 1 should start let proposal_msg = node.next_proposal().await; assert_eq!( proposal_msg.proposal().quorum_cert().certified_block().id(), genesis.id() ); let b1_id = proposal_msg.proposal().id(); assert_eq!(proposal_msg.proposer(), node.signer.author()); node.round_manager .process_proposal_msg(proposal_msg) .await .unwrap(); let vote_msg = node.next_vote().await; // Adding vote to form a QC node.round_manager.process_vote_msg(vote_msg).await.unwrap(); // round 2 should start let proposal_msg = node.next_proposal().await; let proposal = proposal_msg.proposal(); assert_eq!(proposal.round(), 2); assert_eq!(proposal.parent_id(), b1_id); assert_eq!(proposal.quorum_cert().certified_block().id(), b1_id); }); } #[test] /// If the proposal is valid, a vote should be sent fn vote_on_successful_proposal() { let mut runtime = consensus_runtime(); let mut playground = NetworkPlayground::new(runtime.handle().clone()); // In order to observe the votes we're going to check proposal processing on the non-proposer // node (which will send the votes to the proposer). let mut nodes = NodeSetup::create_nodes(&mut playground, runtime.handle().clone(), 1); let node = &mut nodes[0]; let genesis_qc = certificate_for_genesis(); timed_block_on(&mut runtime, async { // Start round 1 and clear the message queue node.next_proposal().await; let proposal = Block::new_proposal(vec![], 1, 1, genesis_qc.clone(), &node.signer); let proposal_id = proposal.id(); node.round_manager.process_proposal(proposal).await.unwrap(); let vote_msg = node.next_vote().await; assert_eq!(vote_msg.vote().author(), node.signer.author()); assert_eq!(vote_msg.vote().vote_data().proposed().id(), proposal_id); let consensus_state = node.round_manager.consensus_state(); assert_eq!(consensus_state.epoch(), 1); assert_eq!(consensus_state.last_voted_round(), 1); assert_eq!(consensus_state.preferred_round(), 0); assert_eq!(consensus_state.in_validator_set(), true); }); } #[test] /// If the proposal does not pass voting rules, /// No votes are sent, but the block is still added to the block tree. fn no_vote_on_old_proposal() { let mut runtime = consensus_runtime(); let mut playground = NetworkPlayground::new(runtime.handle().clone()); // In order to observe the votes we're going to check proposal processing on the non-proposer // node (which will send the votes to the proposer). let mut nodes = NodeSetup::create_nodes(&mut playground, runtime.handle().clone(), 1); let node = &mut nodes[0]; let genesis_qc = certificate_for_genesis(); let new_block = Block::new_proposal(vec![], 1, 1, genesis_qc.clone(), &node.signer); let new_block_id = new_block.id(); let old_block = Block::new_proposal(vec![], 1, 2, genesis_qc, &node.signer); let old_block_id = old_block.id(); timed_block_on(&mut runtime, async { // clear the message queue node.next_proposal().await; node.round_manager .process_proposal(new_block) .await .unwrap(); node.round_manager .process_proposal(old_block) .await .unwrap_err(); let vote_msg = node.next_vote().await; assert_eq!(vote_msg.vote().vote_data().proposed().id(), new_block_id); assert!(node.block_store.get_block(old_block_id).is_some()); }); } #[test] /// We don't vote for proposals that 'skips' rounds /// After that when we then receive proposal for correct round, we vote for it /// Basically it checks that adversary can not send proposal and skip rounds violating round_state /// rules fn no_vote_on_mismatch_round() { let mut runtime = consensus_runtime(); let mut playground = NetworkPlayground::new(runtime.handle().clone()); // In order to observe the votes we're going to check proposal processing on the non-proposer // node (which will send the votes to the proposer). let mut node = NodeSetup::create_nodes(&mut playground, runtime.handle().clone(), 1) .pop() .unwrap(); let genesis_qc = certificate_for_genesis(); let correct_block = Block::new_proposal(vec![], 1, 1, genesis_qc.clone(), &node.signer); let block_skip_round = Block::new_proposal(vec![], 2, 2, genesis_qc.clone(), &node.signer); timed_block_on(&mut runtime, async { let bad_proposal = ProposalMsg::new( block_skip_round, SyncInfo::new(genesis_qc.clone(), genesis_qc.clone(), None), ); assert!(node .round_manager .process_proposal_msg(bad_proposal) .await .is_err()); let good_proposal = ProposalMsg::new( correct_block.clone(), SyncInfo::new(genesis_qc.clone(), genesis_qc.clone(), None), ); node.round_manager .process_proposal_msg(good_proposal) .await .unwrap(); }); } #[test] /// Ensure that after the vote messages are broadcasted upon timeout, the receivers /// have the highest quorum certificate (carried by the SyncInfo of the vote message) fn sync_info_carried_on_timeout_vote() { let mut runtime = consensus_runtime(); let mut playground = NetworkPlayground::new(runtime.handle().clone()); let mut nodes = NodeSetup::create_nodes(&mut playground, runtime.handle().clone(), 1); let mut node = nodes.pop().unwrap(); timed_block_on(&mut runtime, async { let proposal_msg = node.next_proposal().await; let block_0 = proposal_msg.proposal().clone(); node.round_manager .process_proposal_msg(proposal_msg) .await .unwrap(); node.next_vote().await; let parent_block_info = block_0.quorum_cert().certified_block(); // Populate block_0 and a quorum certificate for block_0 on non_proposer let block_0_quorum_cert = gen_test_certificate( vec![&node.signer], // Follow MockStateComputer implementation block_0.gen_block_info( parent_block_info.executed_state_id(), parent_block_info.version(), parent_block_info.next_epoch_state().cloned(), ), parent_block_info.clone(), None, ); node.block_store .insert_single_quorum_cert(block_0_quorum_cert.clone()) .unwrap(); node.round_manager .process_local_timeout(1) .await .unwrap_err(); let vote_msg_on_timeout = node.next_vote().await; assert!(vote_msg_on_timeout.vote().is_timeout()); assert_eq!( *vote_msg_on_timeout.sync_info().highest_quorum_cert(), block_0_quorum_cert ); }); } #[test] /// We don't vote for proposals that comes from proposers that are not valid proposers for round fn no_vote_on_invalid_proposer() { let mut runtime = consensus_runtime(); let mut playground = NetworkPlayground::new(runtime.handle().clone()); // In order to observe the votes we're going to check proposal processing on the non-proposer // node (which will send the votes to the proposer). let mut nodes = NodeSetup::create_nodes(&mut playground, runtime.handle().clone(), 2); let incorrect_proposer = nodes.pop().unwrap(); let mut node = nodes.pop().unwrap(); let genesis_qc = certificate_for_genesis(); let correct_block = Block::new_proposal(vec![], 1, 1, genesis_qc.clone(), &node.signer); let block_incorrect_proposer = Block::new_proposal(vec![], 1, 1, genesis_qc.clone(), &incorrect_proposer.signer); timed_block_on(&mut runtime, async { let bad_proposal = ProposalMsg::new( block_incorrect_proposer, SyncInfo::new(genesis_qc.clone(), genesis_qc.clone(), None), ); assert!(node .round_manager .process_proposal_msg(bad_proposal) .await .is_err()); let good_proposal = ProposalMsg::new( correct_block.clone(), SyncInfo::new(genesis_qc.clone(), genesis_qc.clone(), None), ); node.round_manager .process_proposal_msg(good_proposal.clone()) .await .unwrap(); }); } #[test] /// We allow to 'skip' round if proposal carries timeout certificate for next round fn new_round_on_timeout_certificate() { let mut runtime = consensus_runtime(); let mut playground = NetworkPlayground::new(runtime.handle().clone()); // In order to observe the votes we're going to check proposal processing on the non-proposer // node (which will send the votes to the proposer). let mut node = NodeSetup::create_nodes(&mut playground, runtime.handle().clone(), 1) .pop() .unwrap(); let genesis_qc = certificate_for_genesis(); let correct_block = Block::new_proposal(vec![], 1, 1, genesis_qc.clone(), &node.signer); let block_skip_round = Block::new_proposal(vec![], 2, 2, genesis_qc.clone(), &node.signer); let timeout = Timeout::new(1, 1); let timeout_signature = timeout.sign(&node.signer); let mut tc = TimeoutCertificate::new(timeout); tc.add_signature(node.signer.author(), timeout_signature); timed_block_on(&mut runtime, async { let skip_round_proposal = ProposalMsg::new( block_skip_round, SyncInfo::new(genesis_qc.clone(), genesis_qc.clone(), Some(tc)), ); node.round_manager .process_proposal_msg(skip_round_proposal) .await .unwrap(); let old_good_proposal = ProposalMsg::new( correct_block.clone(), SyncInfo::new(genesis_qc.clone(), genesis_qc.clone(), None), ); assert!(node .round_manager .process_proposal_msg(old_good_proposal) .await .is_err()); }); } #[test] fn response_on_block_retrieval() { let mut runtime = consensus_runtime(); let mut playground = NetworkPlayground::new(runtime.handle().clone()); let mut node = NodeSetup::create_nodes(&mut playground, runtime.handle().clone(), 1) .pop() .unwrap(); let genesis_qc = certificate_for_genesis(); let block = Block::new_proposal(vec![], 1, 1, genesis_qc.clone(), &node.signer); let block_id = block.id(); let proposal = ProposalMsg::new(block, SyncInfo::new(genesis_qc.clone(), genesis_qc, None)); timed_block_on(&mut runtime, async { node.round_manager .process_proposal_msg(proposal) .await .unwrap(); // first verify that we can retrieve the block if it's in the tree let (tx1, rx1) = oneshot::channel(); let single_block_request = IncomingBlockRetrievalRequest { req: BlockRetrievalRequest::new(block_id, 1), response_sender: tx1, }; node.round_manager .process_block_retrieval(single_block_request) .await .unwrap(); match rx1.await { Ok(Ok(bytes)) => { let response = match bcs::from_bytes(&bytes) { Ok(ConsensusMsg::BlockRetrievalResponse(resp)) => *resp, _ => panic!("block retrieval failure"), }; assert_eq!(response.status(), BlockRetrievalStatus::Succeeded); assert_eq!(response.blocks().get(0).unwrap().id(), block_id); } _ => panic!("block retrieval failure"), } // verify that if a block is not there, return ID_NOT_FOUND let (tx2, rx2) = oneshot::channel(); let missing_block_request = IncomingBlockRetrievalRequest { req: BlockRetrievalRequest::new(HashValue::random(), 1), response_sender: tx2, }; node.round_manager .process_block_retrieval(missing_block_request) .await .unwrap(); match rx2.await { Ok(Ok(bytes)) => { let response = match bcs::from_bytes(&bytes) { Ok(ConsensusMsg::BlockRetrievalResponse(resp)) => *resp, _ => panic!("block retrieval failure"), }; assert_eq!(response.status(), BlockRetrievalStatus::IdNotFound); assert!(response.blocks().is_empty()); } _ => panic!("block retrieval failure"), } // if asked for many blocks, return NOT_ENOUGH_BLOCKS let (tx3, rx3) = oneshot::channel(); let many_block_request = IncomingBlockRetrievalRequest { req: BlockRetrievalRequest::new(block_id, 3), response_sender: tx3, }; node.round_manager .process_block_retrieval(many_block_request) .await .unwrap(); match rx3.await { Ok(Ok(bytes)) => { let response = match bcs::from_bytes(&bytes) { Ok(ConsensusMsg::BlockRetrievalResponse(resp)) => *resp, _ => panic!("block retrieval failure"), }; assert_eq!(response.status(), BlockRetrievalStatus::NotEnoughBlocks); assert_eq!(block_id, response.blocks().get(0).unwrap().id()); assert_eq!( node.block_store.root().id(), response.blocks().get(1).unwrap().id() ); } _ => panic!("block retrieval failure"), } }); } #[test] /// rebuild a node from previous storage without violating safety guarantees. fn recover_on_restart() { let mut runtime = consensus_runtime(); let mut playground = NetworkPlayground::new(runtime.handle().clone()); let mut node = NodeSetup::create_nodes(&mut playground, runtime.handle().clone(), 1) .pop() .unwrap(); let inserter = TreeInserter::new_with_store(node.signer.clone(), node.block_store.clone()); let genesis_qc = certificate_for_genesis(); let mut data = Vec::new(); let num_proposals = 100; // insert a few successful proposals for i in 1..=num_proposals { let proposal = inserter.create_block_with_qc(genesis_qc.clone(), i, i, vec![]); let timeout = Timeout::new(1, i - 1); let mut tc = TimeoutCertificate::new(timeout.clone()); tc.add_signature(inserter.signer().author(), inserter.signer().sign(&timeout)); data.push((proposal, tc)); } timed_block_on(&mut runtime, async { for (proposal, tc) in &data { let proposal_msg = ProposalMsg::new( proposal.clone(), SyncInfo::new( proposal.quorum_cert().clone(), genesis_qc.clone(), Some(tc.clone()), ), ); node.round_manager .process_proposal_msg(proposal_msg) .await .unwrap(); } }); // verify after restart we recover the data node = node.restart(&mut playground, runtime.handle().clone()); let consensus_state = node.round_manager.consensus_state(); assert_eq!(consensus_state.epoch(), 1); assert_eq!(consensus_state.last_voted_round(), num_proposals); assert_eq!(consensus_state.preferred_round(), 0); assert_eq!(consensus_state.in_validator_set(), true); for (block, _) in data { assert_eq!(node.block_store.block_exists(block.id()), true); } } #[test] /// Generate a NIL vote extending HQC upon timeout if no votes have been sent in the round. fn nil_vote_on_timeout() { let mut runtime = consensus_runtime(); let mut playground = NetworkPlayground::new(runtime.handle().clone()); let mut nodes = NodeSetup::create_nodes(&mut playground, runtime.handle().clone(), 1); let node = &mut nodes[0]; let genesis = node.block_store.root(); timed_block_on(&mut runtime, async { node.next_proposal().await; // Process the outgoing vote message and verify that it contains a round signature // and that the vote extends genesis. node.round_manager .process_local_timeout(1) .await .unwrap_err(); let vote_msg = node.next_vote().await; let vote = vote_msg.vote(); assert!(vote.is_timeout()); // NIL block doesn't change timestamp assert_eq!( vote.vote_data().proposed().timestamp_usecs(), genesis.timestamp_usecs() ); assert_eq!(vote.vote_data().proposed().round(), 1); assert_eq!(vote.vote_data().parent().id(), node.block_store.root().id()); }); } #[test] /// If the node votes in a round, upon timeout the same vote is re-sent with a timeout signature. fn vote_resent_on_timeout() { let mut runtime = consensus_runtime(); let mut playground = NetworkPlayground::new(runtime.handle().clone()); let mut nodes = NodeSetup::create_nodes(&mut playground, runtime.handle().clone(), 1); let node = &mut nodes[0]; timed_block_on(&mut runtime, async { let proposal_msg = node.next_proposal().await; let id = proposal_msg.proposal().id(); node.round_manager .process_proposal_msg(proposal_msg) .await .unwrap(); let vote_msg = node.next_vote().await; let vote = vote_msg.vote(); assert!(!vote.is_timeout()); assert_eq!(vote.vote_data().proposed().id(), id); // Process the outgoing vote message and verify that it contains a round signature // and that the vote is the same as above. node.round_manager .process_local_timeout(1) .await .unwrap_err(); let timeout_vote_msg = node.next_vote().await; let timeout_vote = timeout_vote_msg.vote(); assert!(timeout_vote.is_timeout()); assert_eq!(timeout_vote.vote_data(), vote.vote_data()); }); } #[test] fn sync_info_sent_on_stale_sync_info() { let mut runtime = consensus_runtime(); let mut playground = NetworkPlayground::new(runtime.handle().clone()); let mut nodes = NodeSetup::create_nodes(&mut playground, runtime.handle().clone(), 2); runtime.spawn(playground.start()); let genesis_qc = certificate_for_genesis(); let block_0 = Block::new_proposal(vec![], 1, 1, genesis_qc, &nodes[0].signer); let parent_block_info = block_0.quorum_cert().certified_block(); let block_0_quorum_cert = gen_test_certificate( vec![&nodes[0].signer, &nodes[1].signer], // Follow MockStateComputer implementation block_0.gen_block_info( parent_block_info.executed_state_id(), parent_block_info.version(), parent_block_info.next_epoch_state().cloned(), ), parent_block_info.clone(), None, ); let mut behind_node = nodes.pop().unwrap(); let mut ahead_node = nodes.pop().unwrap(); // ahead node has one more block ahead_node .block_store .execute_and_insert_block(block_0) .unwrap(); ahead_node .block_store .insert_single_quorum_cert(block_0_quorum_cert.clone()) .unwrap(); timed_block_on(&mut runtime, async { ahead_node.next_proposal().await; behind_node.next_proposal().await; // broadcast timeout behind_node .round_manager .process_local_timeout(1) .await .unwrap_err(); let timeout_vote_msg = behind_node.next_vote().await; assert!(timeout_vote_msg.vote().is_timeout()); // process the stale sync info carried in the vote ahead_node .round_manager .process_vote_msg(timeout_vote_msg) .await .unwrap(); let sync_info = behind_node.next_sync_info().await; assert_eq!(*sync_info.highest_quorum_cert(), block_0_quorum_cert); }); } #[test] fn sync_on_partial_newer_sync_info() { let mut runtime = consensus_runtime(); let mut playground = NetworkPlayground::new(runtime.handle().clone()); let mut nodes = NodeSetup::create_nodes(&mut playground, runtime.handle().clone(), 1); let mut node = nodes.pop().unwrap(); runtime.spawn(playground.start()); timed_block_on(&mut runtime, async { // commit block 1 after 4 rounds for _ in 1..=4 { let proposal_msg = node.next_proposal().await; node.round_manager .process_proposal_msg(proposal_msg) .await .unwrap(); let vote_msg = node.next_vote().await; // Adding vote to form a QC node.round_manager.process_vote_msg(vote_msg).await.unwrap(); } let block_4 = node.next_proposal().await; node.round_manager .process_proposal_msg(block_4.clone()) .await .unwrap(); // commit genesis and block 1 for _ in 0..2 { let _ = node.commit_cb_receiver.next().await; } let vote_msg = node.next_vote().await; let vote_data = vote_msg.vote().vote_data(); let block_4_qc = gen_test_certificate( vec![&node.signer], vote_data.proposed().clone(), vote_data.parent().clone(), None, ); // Create a sync info with newer quorum cert but older commit cert let sync_info = SyncInfo::new(block_4_qc.clone(), certificate_for_genesis(), None); node.round_manager .ensure_round_and_sync_up( sync_info.highest_round() + 1, &sync_info, node.signer.author(), true, ) .await .unwrap(); // QuorumCert added assert_eq!(*node.block_store.highest_quorum_cert(), block_4_qc); // Help remote message sent // Due to the asynchronous channel, the order of the sync info and next proposal is not fixed. // We assert one of them is the sync info we expect. let m1 = node.next_message().await; let m2 = node.next_message().await; assert!(matches!(m1, ConsensusMsg::SyncInfo(_)) || matches!(m2, ConsensusMsg::SyncInfo(_))); }); } #[test] fn safety_rules_crash() { let mut runtime = consensus_runtime(); let mut playground = NetworkPlayground::new(runtime.handle().clone()); let mut nodes = NodeSetup::create_nodes(&mut playground, runtime.handle().clone(), 1); let mut node = nodes.pop().unwrap(); runtime.spawn(playground.start()); fn reset_safety_rules(node: &mut NodeSetup) { let safety_storage = PersistentSafetyStorage::initialize( Storage::from(diem_secure_storage::InMemoryStorage::new()), node.signer.author(), node.signer.private_key().clone(), Ed25519PrivateKey::generate_for_testing(), node.round_manager.consensus_state().waypoint(), true, ); node.safety_rules_manager = SafetyRulesManager::new_local(safety_storage, false, false); let safety_rules = MetricsSafetyRules::new(node.safety_rules_manager.client(), node.storage.clone()); node.round_manager.set_safety_rules(safety_rules); }; timed_block_on(&mut runtime, async { for _ in 0..2 { let proposal_msg = node.next_proposal().await; reset_safety_rules(&mut node); // construct_and_sign_vote node.round_manager .process_proposal_msg(proposal_msg) .await .unwrap(); let vote_msg = node.next_vote().await; // sign_timeout reset_safety_rules(&mut node); let round = vote_msg.vote().vote_data().proposed().round(); node.round_manager .process_local_timeout(round) .await .unwrap_err(); let vote_msg = node.next_vote().await; // sign proposal reset_safety_rules(&mut node); node.round_manager.process_vote_msg(vote_msg).await.unwrap(); } // verify the last sign proposal happened node.next_proposal().await; }); }
38.44163
102
0.615958
e62bfed1de4e7effc09ecb9bcfb1bb9be7502075
135
#[rustfmt::skip] pub(super) mod nodes; #[rustfmt::skip] pub mod macros; #[macro_use] pub mod kind; pub use kind::*; pub use nodes::*;
13.5
21
0.666667
2997aa2be10f995d3a421e619fb11ac03d2e0aac
7,390
use super::*; use std::marker::PhantomData; use winit::event_loop::EventLoopWindowTarget; /// Represents an OpenGL [`Context`]. /// /// A [`Context`] is normally associated with a single Window, however /// [`Context`]s can be *shared* between multiple windows or be headless. /// /// If a [`Context`] is backed by a window, it will be wrapped by either /// [`RawContext<T>`] or [`WindowedContext<T>`]. /// /// # Example /// /// ```no_run /// # fn main() { /// # let el = glutin::event_loop::EventLoop::new(); /// # let wb = glutin::window::WindowBuilder::new(); /// # let some_context = glutin::ContextBuilder::new() /// # .build_windowed(wb, &el) /// # .unwrap(); /// let cb = glutin::ContextBuilder::new() /// .with_vsync(true) /// .with_multisampling(8) /// .with_shared_lists(some_context.context()); /// # } /// ``` /// /// [`WindowedContext<T>`]: type.WindowedContext.html /// [`RawContext<T>`]: type.RawContext.html /// [`Context`]: struct.Context.html #[derive(Debug)] pub struct Context<T: ContextCurrentState> { pub(crate) context: platform_impl::Context, pub(crate) phantom: PhantomData<T>, } impl<T: ContextCurrentState> Context<T> { /// See [`ContextWrapper::make_current`]. /// /// [`ContextWrapper::make_current`]: /// struct.ContextWrapper.html#method.make_current pub unsafe fn make_current( self, ) -> Result<Context<PossiblyCurrent>, (Self, ContextError)> { match self.context.make_current() { Ok(()) => Ok(Context { context: self.context, phantom: PhantomData, }), Err(err) => Err(( Context { context: self.context, phantom: PhantomData, }, err, )), } } /// See [`ContextWrapper::make_not_current`]. /// /// [`ContextWrapper::make_not_current`]: /// struct.ContextWrapper.html#method.make_not_current pub unsafe fn make_not_current( self, ) -> Result<Context<NotCurrent>, (Self, ContextError)> { match self.context.make_not_current() { Ok(()) => Ok(Context { context: self.context, phantom: PhantomData, }), Err(err) => Err(( Context { context: self.context, phantom: PhantomData, }, err, )), } } /// See [`ContextWrapper::treat_as_not_current`]. /// /// [`ContextWrapper::treat_as_not_current`]: /// struct.ContextWrapper.html#method.treat_as_not_current pub unsafe fn treat_as_not_current(self) -> Context<NotCurrent> { Context { context: self.context, phantom: PhantomData, } } /// See [`ContextWrapper::treat_as_current`]. /// /// [`ContextWrapper::treat_as_current`]: /// struct.ContextWrapper.html#method.treat_as_current pub unsafe fn treat_as_current(self) -> Context<PossiblyCurrent> { Context { context: self.context, phantom: PhantomData, } } /// See [`ContextWrapper::is_current`]. /// /// [`ContextWrapper::is_current`]: /// struct.ContextWrapper.html#method.is_current pub fn is_current(&self) -> bool { self.context.is_current() } /// See [`ContextWrapper::get_api`]. /// /// [`ContextWrapper::get_api`]: struct.ContextWrapper.html#method.get_api pub fn get_api(&self) -> Api { self.context.get_api() } } impl Context<PossiblyCurrent> { /// See [`ContextWrapper::get_proc_address`]. /// /// [`ContextWrapper::get_proc_address`]: /// struct.ContextWrapper.html#method.get_proc_address pub fn get_proc_address(&self, addr: &str) -> *const core::ffi::c_void { self.context.get_proc_address(addr) } } impl<'a, T: ContextCurrentState> ContextBuilder<'a, T> { /// Builds the given GL context. /// /// When on a unix operating system, prefer [`build_surfaceless`]. If both /// [`build_surfaceless`] and `build_headless` fail, try using a hidden /// window, or [`build_osmesa`]. Please note that if you choose to use a /// hidden window, you must still handle the events it generates on the /// events loop. /// /// Errors can occur in two scenarios: /// - If the window could not be created (via permission denied, /// incompatible system, out of memory, etc.). This should be very rare. /// - If the OpenGL [`Context`] could not be created. This generally /// happens /// because the underlying platform doesn't support a requested feature. /// /// [`Context`]: struct.Context.html #[cfg_attr( not(any( target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd", )), doc = "\ [`build_surfaceless`]: os/index.html [`build_osmesa`]: os/index.html " )] #[cfg_attr( any( target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd", ), doc = "\ [`build_surfaceless`]: os/unix/trait.HeadlessContextExt.html#tymethod.build_surfaceless [`build_osmesa`]: os/unix/trait.HeadlessContextExt.html#tymethod.build_osmesa " )] pub fn build_headless<TE>( self, el: &EventLoopWindowTarget<TE>, size: dpi::PhysicalSize, ) -> Result<Context<NotCurrent>, CreationError> { let ContextBuilder { pf_reqs, gl_attr } = self; let gl_attr = gl_attr.map_sharing(|ctx| &ctx.context); platform_impl::Context::new_headless(el, &pf_reqs, &gl_attr, size).map( |context| Context { context, phantom: PhantomData, }, ) } } // This is nightly only: // impl !Send for Context<PossiblyCurrent> {} // impl !Sync for Context<PossiblyCurrent> {} // // Instead we add a phantom type to PossiblyCurrent /// A type that [`Context`]s which might possibly be currently current on some /// thread take as a generic. /// /// See [`ContextWrapper::make_current`] for more details. /// /// [`ContextWrapper::make_current`]: /// struct.ContextWrapper.html#method.make_current /// [`Context`]: struct.Context.html #[derive(Debug, Clone, Copy)] pub struct PossiblyCurrent { phantom: PhantomData<*mut ()>, } /// A type that [`Context`]s which are not currently current on any thread take /// as a generic. /// /// See [`ContextWrapper::make_current`] for more details. /// /// [`ContextWrapper::make_current`]: /// struct.ContextWrapper.html#method.make_current /// [`Context`]: struct.Context.html #[derive(Debug, Clone, Copy)] pub enum NotCurrent {} /// A trait implemented on both [`NotCurrent`] and /// [`PossiblyCurrent`]. /// /// [`NotCurrent`]: enum.NotCurrent.html /// [`PossiblyCurrent`]: struct.PossiblyCurrent.html pub trait ContextCurrentState: std::fmt::Debug + Clone {} impl ContextCurrentState for PossiblyCurrent {} impl ContextCurrentState for NotCurrent {} trait FailToCompileIfNotSendSync where Self: Send + Sync, { } impl FailToCompileIfNotSendSync for Context<NotCurrent> {}
31.181435
91
0.601624
7ab9fa6f3f6008de42a8eca5d1c7d027e1851fde
5,766
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use crate::{gen::global_options::GlobalOptions, i_set, s_map, s_set}; const DEFAULT: GlobalOptions<'_> = GlobalOptions { tco_experimental_features: s_set::SSet::empty(), tco_migration_flags: s_set::SSet::empty(), tco_dynamic_view: false, tco_num_local_workers: None, tco_parallel_type_checking_threshold: 10, tco_max_typechecker_worker_memory_mb: None, tco_defer_class_declaration_threshold: None, tco_defer_class_memory_mb_threshold: None, tco_max_times_to_defer_type_checking: None, tco_prefetch_deferred_files: false, tco_remote_type_check_threshold: None, tco_remote_type_check: false, tco_remote_worker_key: None, tco_remote_check_id: None, tco_remote_max_batch_size: 8000, tco_remote_min_batch_size: 5000, tco_num_remote_workers: 0, so_remote_version_specifier: None, so_remote_worker_vfs_checkout_threshold: 0, so_naming_sqlite_path: None, po_auto_namespace_map: &[], po_codegen: false, po_deregister_php_stdlib: false, po_disallow_toplevel_requires: false, po_disable_nontoplevel_declarations: false, po_allow_unstable_features: false, tco_log_inference_constraints: false, tco_disallow_array_typehint: false, tco_disallow_array_literal: false, tco_language_feature_logging: false, tco_disallow_scrutinee_case_value_type_mismatch: false, tco_timeout: 0, tco_disallow_invalid_arraykey: false, tco_disallow_byref_dynamic_calls: false, tco_disallow_byref_calls: true, allowed_fixme_codes_strict: i_set::ISet::empty(), allowed_fixme_codes_partial: i_set::ISet::empty(), codes_not_raised_partial: i_set::ISet::empty(), log_levels: s_map::SMap::empty(), po_disable_lval_as_an_expression: false, tco_shallow_class_decl: false, po_rust_parser_errors: false, tco_like_type_hints: false, tco_union_intersection_type_hints: false, tco_coeffects: true, tco_coeffects_local: true, tco_strict_contexts: true, tco_like_casts: false, tco_simple_pessimize: 0.0, tco_complex_coercion: false, tco_disable_partially_abstract_typeconsts: false, tco_disallow_partially_abstract_typeconst_definitions: false, error_codes_treated_strictly: i_set::ISet::empty(), tco_check_xhp_attribute: false, tco_check_redundant_generics: false, tco_disallow_unresolved_type_variables: false, tco_disallow_trait_reuse: false, tco_disallow_invalid_arraykey_constraint: false, po_enable_class_level_where_clauses: false, po_disable_legacy_soft_typehints: true, po_allowed_decl_fixme_codes: i_set::ISet::empty(), po_allow_new_attribute_syntax: false, tco_global_inference: false, tco_gi_reinfer_types: &[], tco_ordered_solving: false, tco_const_static_props: false, po_disable_legacy_attribute_syntax: false, tco_const_attribute: false, po_const_default_func_args: false, po_const_default_lambda_args: false, po_disallow_silence: false, po_abstract_static_props: false, po_disable_unset_class_const: false, po_parser_errors_only: false, tco_check_attribute_locations: true, po_disallow_func_ptrs_in_constants: false, tco_error_php_lambdas: false, tco_disallow_discarded_nullable_awaitables: false, po_enable_xhp_class_modifier: false, po_disable_xhp_element_mangling: false, po_disable_xhp_children_declarations: false, glean_service: "", glean_hostname: "", glean_port: 0, glean_reponame: "", symbol_write_root_path: "", symbol_write_hhi_path: "", symbol_write_ignore_paths: &[], symbol_write_index_paths: &[], symbol_write_index_paths_file: None, symbol_write_include_hhi: true, symbol_write_index_paths_file_output: None, po_enable_enum_classes: true, po_disable_modes: false, po_disable_hh_ignore_error: false, po_disable_array: false, po_disable_array_typehint: false, tco_enable_systemlib_annotations: false, tco_higher_kinded_types: false, tco_method_call_inference: false, tco_report_pos_from_reason: false, tco_typecheck_sample_rate: 1.0, tco_enable_sound_dynamic: false, po_disallow_hash_comments: false, po_disallow_fun_and_cls_meth_pseudo_funcs: false, po_disallow_inst_meth: false, po_escape_brace: false, tco_use_direct_decl_parser: false, tco_ifc_enabled: &[], po_enable_enum_supertyping: false, po_hack_arr_dv_arrs: false, po_interpret_soft_types_as_like_types: false, tco_enable_strict_string_concat_interp: false, tco_ignore_unsafe_cast: false, tco_readonly: false, tco_enable_expression_trees: false, tco_allowed_expression_tree_visitors: &[], tco_math_new_code: false, tco_typeconst_concrete_concrete_error: false, tco_meth_caller_only_public_visibility: true, tco_require_extends_implements_ancestors: false, tco_strict_value_equality: false, }; impl GlobalOptions<'static> { pub const DEFAULT: &'static Self = &DEFAULT; pub const fn default_ref() -> &'static Self { Self::DEFAULT } } impl Default for &GlobalOptions<'_> { fn default() -> Self { GlobalOptions::default_ref() } } impl Eq for GlobalOptions<'_> {} impl std::hash::Hash for GlobalOptions<'_> { fn hash<H>(&self, _: &mut H) { unimplemented!() } } impl no_pos_hash::NoPosHash for GlobalOptions<'_> { fn hash<H>(&self, _: &mut H) { unimplemented!() } } impl Ord for GlobalOptions<'_> { fn cmp(&self, _: &Self) -> std::cmp::Ordering { unimplemented!() } }
34.73494
69
0.754422
50dd22ee90831e7d4e50235994e6a8a30488a629
1,324
// Copyright (c) 2018-2020 MobileCoin Inc. #![cfg_attr(not(any(test, feature = "log")), no_std)] #![feature(optin_builtin_traits)] #![warn(unused_extern_crates)] extern crate alloc; use sha3::Digest; mod hasher_builder; mod node_id; mod responder_id; pub mod lru; pub use lru::LruCache; pub use node_id::NodeID; pub use responder_id::{ResponderId, ResponderIdParseError}; // A HashMap that replaces the default hasher with an implementation that relies on mcrand for // randomess. pub type HashMap<K, V> = hashbrown::HashMap<K, V, hasher_builder::HasherBuilder>; pub type HashSet<K> = hashbrown::HashSet<K, hasher_builder::HasherBuilder>; pub type Hash = [u8; 32]; /// Note: This is only used by servers, for logging (maybe to anonymize logs?) /// Please don't use it in e.g. transaction validation math, or actual hashing of /// the blocks in the blockchain, where you should be specific about what hash you are using. pub fn fast_hash(data: &[u8]) -> Hash { let hash = sha3::Sha3_256::digest(data); let mut output = [0u8; 32]; output.copy_from_slice(hash.as_slice()); output } // Logging related functionality cfg_if::cfg_if! { if #[cfg(feature="log")] { mod panic_handler; pub mod logger; pub mod sentry; pub use panic_handler::setup_panic_handler; } }
27.020408
94
0.705438
e4c6694ebf98c691db1912b00d1981677751161d
4,152
use std::ffi::CString; use std::future::Future; use std::io::Result; use std::os::unix::io::RawFd; use std::path::Path; use std::pin::Pin; use std::task::{Context, Poll}; use io_uring::opcode::OpenAt; use io_uring::types::Fd; use libc::{c_int, mode_t}; use crate::cqe_ext::EntryExt; use crate::helper::path_to_c_string; use crate::Driver; #[derive(Debug)] pub struct Open { path: Option<CString>, flags: c_int, mode: mode_t, user_data: Option<u64>, driver: Driver, } impl Open { pub fn new<P: AsRef<Path>>( path: P, flags: c_int, mode: mode_t, driver: &Driver, ) -> Result<Self> { let path = path_to_c_string(path.as_ref())?; Ok(Self::new_cstring(path, flags, mode, driver)) } pub fn new_cstring(path: CString, flags: c_int, mode: mode_t, driver: &Driver) -> Self { Self { path: Some(path), flags, mode, user_data: None, driver: driver.clone(), } } } impl Future for Open { type Output = Result<RawFd>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { if let Some(user_data) = self.user_data { let open_at_cqe = self .driver .take_cqe_with_waker(user_data, cx.waker()) .map(|cqe| cqe.ok()) .transpose() .map_err(|err| { // drop won't send useless cancel when error happened self.user_data.take(); err })?; return match open_at_cqe { None => Poll::Pending, Some(open_at_cqe) => { // drop won't send useless cancel self.user_data.take(); let fd = open_at_cqe.result(); // Safety: fd is valid Poll::Ready(Ok(fd)) } }; } let path = &*self.path.as_ref().expect("path is not init"); let open_at_sqe = OpenAt::new(Fd(libc::AT_FDCWD), path.as_ptr()) .flags(self.flags) .mode(self.mode) .build(); let user_data = self .driver .push_sqe_with_waker(open_at_sqe, cx.waker().clone())?; user_data.map(|user_data| self.user_data.replace(user_data)); Poll::Pending } } impl Drop for Open { fn drop(&mut self) { if let Some(user_data) = self.user_data { let _ = self .driver .cancel_open_at(user_data, self.path.take().expect("path is not init")); } } } #[cfg(test)] mod tests { use std::fs; use std::fs::File; use std::io::Read; use std::os::unix::io::FromRawFd; use std::sync::mpsc::SyncSender; use std::sync::{mpsc, Arc}; use futures_task::ArcWake; use super::*; struct ArcWaker { tx: SyncSender<()>, } impl ArcWake for ArcWaker { fn wake_by_ref(arc_self: &Arc<Self>) { arc_self.tx.send(()).unwrap(); } } #[test] fn test_open() { let (driver, mut reactor) = Driver::builder().build().unwrap(); let mut open = Open::new("testdata/book.txt", libc::O_RDONLY, 0, &driver).unwrap(); let (tx, rx) = mpsc::sync_channel(1); let waker = Arc::new(ArcWaker { tx }); let waker = futures_task::waker(waker); assert!(Pin::new(&mut open) .poll(&mut Context::from_waker(&waker)) .is_pending()); assert_eq!(reactor.run_at_least_one(None).unwrap(), 1); rx.recv().unwrap(); let fd = if let Poll::Ready(result) = Pin::new(&mut open).poll(&mut Context::from_waker(&waker)) { result.unwrap() } else { panic!("open is still no ready"); }; let mut file = unsafe { File::from_raw_fd(fd) }; let content = fs::read("testdata/book.txt").unwrap(); let mut buf = vec![]; file.read_to_end(&mut buf).unwrap(); assert_eq!(content, buf); } }
24.862275
92
0.518304
e24f89cdffdff8abaaf15063faac878fbecadab7
210
// run-pass #![feature(const_transmute)] use std::mem; #[repr(transparent)] struct Foo(u32); const TRANSMUTED_U32: u32 = unsafe { mem::transmute(Foo(3)) }; fn main() { assert_eq!(TRANSMUTED_U32, 3); }
14
62
0.661905
1ab77a6568b71df693e268240db145290bff21d7
4,742
#[macro_use] extern crate serde_derive; #[macro_use] extern crate log; #[macro_use] extern crate lazy_static; #[macro_use] extern crate rlink_derive; #[macro_use] extern crate anyhow; pub mod sink; pub mod source; pub(crate) mod state; pub use sink::output_format::KafkaOutputFormat; pub use source::input_format::KafkaInputFormat; use std::collections::HashMap; use rdkafka::ClientConfig; use rlink::core::element::BufferReader; use rlink::core::element::Record; use crate::source::deserializer::{ DefaultKafkaRecordDeserializer, DefaultKafkaRecordDeserializerBuilder, KafkaRecordDeserializerBuilder, }; pub const BOOTSTRAP_SERVERS: &str = "bootstrap.servers"; pub const TOPICS: &str = "topics"; pub const GROUP_ID: &str = "group.id"; pub const SOURCE_CHANNEL_SIZE: usize = 50000; pub const SINK_CHANNEL_SIZE: usize = 50000; pub static KAFKA_DATA_TYPES: [u8; 6] = [ // timestamp rlink::core::element::types::I64, // key rlink::core::element::types::BYTES, // payload rlink::core::element::types::BYTES, // topic rlink::core::element::types::BYTES, // partition rlink::core::element::types::I32, // offset rlink::core::element::types::I64, ]; pub fn build_kafka_record( timestamp: i64, key: &[u8], payload: &[u8], topic: &str, partition: i32, offset: i64, ) -> Result<Record, std::io::Error> { // 36 = 12(len(payload) + len(topic) + len(key)) + // 20(len(timestamp) + len(partition) + len(offset)) + // 4(place_holder) let capacity = payload.len() + topic.len() + key.len() + 36; let mut record = Record::with_capacity(capacity); let mut writer = record.as_writer(&KAFKA_DATA_TYPES); writer.set_i64(timestamp)?; writer.set_bytes(key)?; writer.set_bytes(payload)?; writer.set_str(topic)?; writer.set_i32(partition)?; writer.set_i64(offset)?; Ok(record) } pub struct KafkaRecord<'a, 'b> { reader: BufferReader<'a, 'b>, } impl<'a, 'b> KafkaRecord<'a, 'b> { pub fn new(record: &'a mut Record) -> Self { let reader = record.as_reader(&KAFKA_DATA_TYPES); KafkaRecord { reader } } pub fn get_kafka_timestamp(&self) -> Result<i64, std::io::Error> { self.reader.get_i64(0) } pub fn get_kafka_key(&self) -> Result<&[u8], std::io::Error> { self.reader.get_bytes(1) } pub fn get_kafka_payload(&self) -> Result<&[u8], std::io::Error> { self.reader.get_bytes(2) } pub fn get_kafka_topic(&self) -> Result<&str, std::io::Error> { self.reader.get_str(3) } pub fn get_kafka_partition(&self) -> Result<i32, std::io::Error> { self.reader.get_i32(4) } pub fn get_kafka_offset(&self) -> Result<i64, std::io::Error> { self.reader.get_i64(5) } } pub fn field(field_name: &str) -> String { format!("KAFKA_SOURCE.{}", field_name) } // pub fn create_input_format_from_prop(properties: &Properties) -> KafkaInputFormat { // let mut conf_map = HashMap::new(); // conf_map.insert( // BOOTSTRAP_SERVERS.to_string(), // properties // .get_string(field(BOOTSTRAP_SERVERS).as_str()) // .unwrap(), // ); // // let topics = properties.get_string(field(TOPICS).as_str()).unwrap(); // let topics: Vec<&str> = topics.split(",").collect(); // let topics = topics.iter().map(|topic| topic.to_string()).collect(); // // create_input_format(conf_map, topics) // } pub fn create_input_format( conf_map: HashMap<String, String>, topics: Vec<String>, buffer_size: Option<usize>, deserializer_builder: Option<Box<dyn KafkaRecordDeserializerBuilder>>, ) -> KafkaInputFormat { let mut client_config = ClientConfig::new(); for (key, val) in conf_map { client_config.set(key.as_str(), val.as_str()); } let buffer_size = buffer_size.unwrap_or(SOURCE_CHANNEL_SIZE); let deserializer_builder = deserializer_builder.unwrap_or_else(|| { let deserializer_builder: Box<dyn KafkaRecordDeserializerBuilder> = Box::new(DefaultKafkaRecordDeserializerBuilder::< DefaultKafkaRecordDeserializer, >::new()); deserializer_builder }); KafkaInputFormat::new(client_config, topics, buffer_size, deserializer_builder) } pub fn create_output_format( conf_map: HashMap<String, String>, topic: Option<String>, buffer_size: Option<usize>, ) -> KafkaOutputFormat { let mut client_config = ClientConfig::new(); for (key, val) in conf_map { client_config.set(key.as_str(), val.as_str()); } KafkaOutputFormat::new( client_config, topic, buffer_size.unwrap_or(SINK_CHANNEL_SIZE), ) }
27.410405
86
0.650358
38786ddfa027af67cb8cb0f8aea202924f20f038
13,415
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 #[cfg(test)] mod mock_vm_test; use libra_crypto::{ed25519::Ed25519PrivateKey, PrivateKey, Uniform}; use libra_state_view::StateView; use libra_types::{ access_path::AccessPath, account_address::AccountAddress, account_config::{association_address, validator_set_address, LBR_NAME}, contract_event::ContractEvent, event::EventKey, on_chain_config::{ config_address, new_epoch_event_key, ConfigurationResource, OnChainConfig, ValidatorSet, }, transaction::{ RawTransaction, Script, SignedTransaction, Transaction, TransactionArgument, TransactionOutput, TransactionPayload, TransactionStatus, }, vm_status::{StatusCode, VMStatus}, write_set::{WriteOp, WriteSet, WriteSetMut}, }; use libra_vm::VMExecutor; use move_core_types::{language_storage::TypeTag, move_resource::MoveResource}; use once_cell::sync::Lazy; use std::collections::HashMap; #[derive(Debug)] enum MockVMTransaction { Mint { sender: AccountAddress, amount: u64, }, Payment { sender: AccountAddress, recipient: AccountAddress, amount: u64, }, Reconfiguration, } pub static KEEP_STATUS: Lazy<TransactionStatus> = Lazy::new(|| TransactionStatus::Keep(VMStatus::new(StatusCode::EXECUTED))); // We use 10 as the assertion error code for insufficient balance within the Libra coin contract. pub static DISCARD_STATUS: Lazy<TransactionStatus> = Lazy::new(|| { TransactionStatus::Discard(VMStatus::new(StatusCode::ABORTED).with_sub_status(10)) }); pub struct MockVM; impl VMExecutor for MockVM { fn execute_block( transactions: Vec<Transaction>, state_view: &dyn StateView, ) -> Result<Vec<TransactionOutput>, VMStatus> { if state_view.is_genesis() { assert_eq!( transactions.len(), 1, "Genesis block should have only one transaction." ); let output = TransactionOutput::new( gen_genesis_writeset(), // mock the validator set event vec![ContractEvent::new( new_epoch_event_key(), 0, TypeTag::Bool, lcs::to_bytes(&0).unwrap(), )], 0, KEEP_STATUS.clone(), ); return Ok(vec![output]); } // output_cache is used to store the output of transactions so they are visible to later // transactions. let mut output_cache = HashMap::new(); let mut outputs = vec![]; for txn in transactions { match decode_transaction(&txn.as_signed_user_txn().unwrap()) { MockVMTransaction::Mint { sender, amount } => { let old_balance = read_balance(&output_cache, state_view, sender); let new_balance = old_balance + amount; let old_seqnum = read_seqnum(&output_cache, state_view, sender); let new_seqnum = old_seqnum + 1; output_cache.insert(balance_ap(sender), new_balance); output_cache.insert(seqnum_ap(sender), new_seqnum); let write_set = gen_mint_writeset(sender, new_balance, new_seqnum); let events = gen_events(sender); outputs.push(TransactionOutput::new( write_set, events, 0, KEEP_STATUS.clone(), )); } MockVMTransaction::Payment { sender, recipient, amount, } => { let sender_old_balance = read_balance(&output_cache, state_view, sender); let recipient_old_balance = read_balance(&output_cache, state_view, recipient); if sender_old_balance < amount { outputs.push(TransactionOutput::new( WriteSet::default(), vec![], 0, DISCARD_STATUS.clone(), )); continue; } let sender_old_seqnum = read_seqnum(&output_cache, state_view, sender); let sender_new_seqnum = sender_old_seqnum + 1; let sender_new_balance = sender_old_balance - amount; let recipient_new_balance = recipient_old_balance + amount; output_cache.insert(balance_ap(sender), sender_new_balance); output_cache.insert(seqnum_ap(sender), sender_new_seqnum); output_cache.insert(balance_ap(recipient), recipient_new_balance); let write_set = gen_payment_writeset( sender, sender_new_balance, sender_new_seqnum, recipient, recipient_new_balance, ); let events = gen_events(sender); outputs.push(TransactionOutput::new( write_set, events, 0, TransactionStatus::Keep(VMStatus::new(StatusCode::EXECUTED)), )); } MockVMTransaction::Reconfiguration => { read_balance_from_storage(state_view, &balance_ap(validator_set_address())); read_balance_from_storage(state_view, &balance_ap(association_address())); outputs.push(TransactionOutput::new( // WriteSet cannot be empty so use genesis writeset only for testing. gen_genesis_writeset(), // mock the validator set event vec![ContractEvent::new( new_epoch_event_key(), 0, TypeTag::Bool, lcs::to_bytes(&0).unwrap(), )], 0, KEEP_STATUS.clone(), )); } } } Ok(outputs) } } fn read_balance( output_cache: &HashMap<AccessPath, u64>, state_view: &dyn StateView, account: AccountAddress, ) -> u64 { let balance_access_path = balance_ap(account); match output_cache.get(&balance_access_path) { Some(balance) => *balance, None => read_balance_from_storage(state_view, &balance_access_path), } } fn read_seqnum( output_cache: &HashMap<AccessPath, u64>, state_view: &dyn StateView, account: AccountAddress, ) -> u64 { let seqnum_access_path = seqnum_ap(account); match output_cache.get(&seqnum_access_path) { Some(seqnum) => *seqnum, None => read_seqnum_from_storage(state_view, &seqnum_access_path), } } fn read_balance_from_storage(state_view: &dyn StateView, balance_access_path: &AccessPath) -> u64 { read_u64_from_storage(state_view, &balance_access_path) } fn read_seqnum_from_storage(state_view: &dyn StateView, seqnum_access_path: &AccessPath) -> u64 { read_u64_from_storage(state_view, &seqnum_access_path) } fn read_u64_from_storage(state_view: &dyn StateView, access_path: &AccessPath) -> u64 { state_view .get(&access_path) .expect("Failed to query storage.") .map_or(0, |bytes| decode_bytes(&bytes)) } fn decode_bytes(bytes: &[u8]) -> u64 { let mut buf = [0; 8]; buf.copy_from_slice(bytes); u64::from_le_bytes(buf) } fn balance_ap(account: AccountAddress) -> AccessPath { AccessPath::new(account, b"balance".to_vec()) } fn seqnum_ap(account: AccountAddress) -> AccessPath { AccessPath::new(account, b"seqnum".to_vec()) } fn gen_genesis_writeset() -> WriteSet { let mut write_set = WriteSetMut::default(); let validator_set_ap = ValidatorSet::CONFIG_ID.access_path(); write_set.push(( validator_set_ap, WriteOp::Value(lcs::to_bytes(&ValidatorSet::new(vec![])).unwrap()), )); write_set.push(( AccessPath::new(config_address(), ConfigurationResource::resource_path()), WriteOp::Value(lcs::to_bytes(&ConfigurationResource::default()).unwrap()), )); write_set .freeze() .expect("genesis writeset should be valid") } fn gen_mint_writeset(sender: AccountAddress, balance: u64, seqnum: u64) -> WriteSet { let mut write_set = WriteSetMut::default(); write_set.push(( balance_ap(sender), WriteOp::Value(balance.to_le_bytes().to_vec()), )); write_set.push(( seqnum_ap(sender), WriteOp::Value(seqnum.to_le_bytes().to_vec()), )); write_set.freeze().expect("mint writeset should be valid") } fn gen_payment_writeset( sender: AccountAddress, sender_balance: u64, sender_seqnum: u64, recipient: AccountAddress, recipient_balance: u64, ) -> WriteSet { let mut write_set = WriteSetMut::default(); write_set.push(( balance_ap(sender), WriteOp::Value(sender_balance.to_le_bytes().to_vec()), )); write_set.push(( seqnum_ap(sender), WriteOp::Value(sender_seqnum.to_le_bytes().to_vec()), )); write_set.push(( balance_ap(recipient), WriteOp::Value(recipient_balance.to_le_bytes().to_vec()), )); write_set .freeze() .expect("payment write set should be valid") } fn gen_events(sender: AccountAddress) -> Vec<ContractEvent> { vec![ContractEvent::new( EventKey::new_from_address(&sender, 0), 0, TypeTag::Vector(Box::new(TypeTag::U8)), b"event_data".to_vec(), )] } pub fn encode_mint_program(amount: u64) -> Script { let argument = TransactionArgument::U64(amount); Script::new(vec![], vec![], vec![argument]) } pub fn encode_transfer_program(recipient: AccountAddress, amount: u64) -> Script { let argument1 = TransactionArgument::Address(recipient); let argument2 = TransactionArgument::U64(amount); Script::new(vec![], vec![], vec![argument1, argument2]) } pub fn encode_mint_transaction(sender: AccountAddress, amount: u64) -> Transaction { encode_transaction(sender, encode_mint_program(amount)) } pub fn encode_transfer_transaction( sender: AccountAddress, recipient: AccountAddress, amount: u64, ) -> Transaction { encode_transaction(sender, encode_transfer_program(recipient, amount)) } fn encode_transaction(sender: AccountAddress, program: Script) -> Transaction { let raw_transaction = RawTransaction::new_script( sender, 0, program, 0, 0, LBR_NAME.to_owned(), std::time::Duration::from_secs(0), ); let privkey = Ed25519PrivateKey::generate_for_testing(); Transaction::UserTransaction( raw_transaction .sign(&privkey, privkey.public_key()) .expect("Failed to sign raw transaction.") .into_inner(), ) } pub fn encode_reconfiguration_transaction(sender: AccountAddress) -> Transaction { let raw_transaction = RawTransaction::new_write_set(sender, 0, WriteSet::default()); let privkey = Ed25519PrivateKey::generate_for_testing(); Transaction::UserTransaction( raw_transaction .sign(&privkey, privkey.public_key()) .expect("Failed to sign raw transaction.") .into_inner(), ) } fn decode_transaction(txn: &SignedTransaction) -> MockVMTransaction { let sender = txn.sender(); match txn.payload() { TransactionPayload::Script(script) => { assert!(script.code().is_empty(), "Code should be empty."); match script.args().len() { 1 => match script.args()[0] { TransactionArgument::U64(amount) => MockVMTransaction::Mint { sender, amount }, _ => unimplemented!( "Only one integer argument is allowed for mint transactions." ), }, 2 => match (&script.args()[0], &script.args()[1]) { (TransactionArgument::Address(recipient), TransactionArgument::U64(amount)) => { MockVMTransaction::Payment { sender, recipient: *recipient, amount: *amount, } } _ => unimplemented!( "The first argument for payment transaction must be recipient address \ and the second argument must be amount." ), }, _ => unimplemented!("Transaction must have one or two arguments."), } } TransactionPayload::WriteSet(_) => { // Use WriteSet for reconfig only for testing. MockVMTransaction::Reconfiguration } TransactionPayload::Module(_) => { unimplemented!("MockVM does not support Module transaction payload.") } } }
35.489418
100
0.579128
bbf0cebd7110b18bd1871880d9b584f5f999c933
247
#![allow(missing_docs)] use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct AssetPlatform { pub id: String, pub chain_identifier: Option<i64>, pub name: String, pub shortname: String, }
22.454545
47
0.700405
48f9c460c5dc5cb407d3563e3b4ee499523f0cee
1,594
use crate::graphics::GCore; #[cfg(target_os="windows")] use crate::windows::OpenGraphicsLibrary; use core::mem::transmute; const VIEWPORT:u32=0x0BA2; const MAX_VIEWPORT_DIMS:u32=0x0D3A; pub struct Viewport{ glViewport:usize, } impl Viewport{ pub const fn new()->Viewport{ Self{ glViewport:0, } } #[cfg(target_os="windows")] pub fn load(&mut self,library:&OpenGraphicsLibrary){ unsafe{ self.glViewport=transmute(library.get_proc_address("glViewport\0")) } } } impl Viewport{ #[inline(always)] pub unsafe fn set(&self,[x,y,widht,height]:[i32;4]){ transmute::<usize,fn(i32,i32,i32,i32)>(self.glViewport)(x,y,widht,height) } } impl Viewport{ #[inline(always)] pub fn get(&self)->[i32;4]{ unsafe{ let mut viewport=[0i32;4]; GCore.get_integer_v(VIEWPORT,viewport.get_unchecked_mut(0)); viewport } } #[inline(always)] pub fn write(&self,viewport:&mut [i32;4]){ unsafe{ GCore.get_integer_v(VIEWPORT,viewport.get_unchecked_mut(0)); } } #[inline(always)] pub fn get_max_dimensions(&self)->[i32;2]{ unsafe{ let mut dimensions=[0i32;2]; GCore.get_integer_v(MAX_VIEWPORT_DIMS,dimensions.get_unchecked_mut(0)); dimensions } } #[inline(always)] pub fn write_max_dimensions(&self,dimensions:&mut [i32;2]){ unsafe{ GCore.get_integer_v(MAX_VIEWPORT_DIMS,dimensions.get_unchecked_mut(0)); } } }
23.101449
83
0.601004
29b47499df99b482971ef3af7870de14c266ba00
2,832
use snarkvm_algorithms::SignatureScheme; use snarkvm_dpc::Network; use snarkvm_utilities::FromBytes; use super::{Keys, KeysError}; // TODO: this needs to coincide with the Aleo parameters for each network type. // I'm assuming these are constant but this needs to be confirmed. const SRS: &str = "aleo_signature"; /// A set of keys for signing and verifying messages in the Aleo signature /// scheme. pub struct AleoKeys<N: Network> { priv_key: <<N as Network>::AccountSignatureScheme as SignatureScheme>::PrivateKey, pub_key: <<N as Network>::AccountSignatureScheme as SignatureScheme>::PublicKey, scheme: <N as Network>::AccountSignatureScheme, } impl<N: Network> Keys for AleoKeys<N> { type M = Vec<u8>; type S = <<N as Network>::AccountSignatureScheme as SignatureScheme>::Signature; fn import_private_key(bytes: &[u8]) -> Result<Self, KeysError> { let scheme = <N as Network>::AccountSignatureScheme::setup(SRS); let priv_key = <<N as Network>::AccountSignatureScheme as SignatureScheme>::PrivateKey::from_bytes_le( bytes, ) .map_err(|_| KeysError::InvalidPrivateKeyBytes)?; let pub_key = scheme.generate_public_key(&priv_key); Ok(Self { priv_key, pub_key, scheme, }) } fn sign(&self, message: &Self::M) -> Result<Self::S, KeysError> { let mut rng = rand::thread_rng(); self.scheme .sign(&self.priv_key, message, &mut rng) .map_err(|e| KeysError::SignatureFailed(format!("{:?}", e))) } fn verify(&self, message: &Self::M, signature: &Self::S) -> Result<bool, KeysError> { self.scheme .verify(&self.pub_key, message, signature) .map_err(|_| KeysError::InvalidSignature) } } #[cfg(test)] mod tests { use rand::Rng; use snarkvm_dpc::testnet2::Testnet2; use snarkvm_utilities::ToBytes; use super::*; #[test] fn import() { let sk = <<Testnet2 as Network>::AccountSignatureScheme as SignatureScheme>::setup(SRS) .generate_private_key(&mut rand::thread_rng()); let bytes = sk.to_bytes_le().unwrap(); assert!(AleoKeys::<Testnet2>::import_private_key(&bytes).is_ok()); } #[test] fn sign_verify() { let sk = <<Testnet2 as Network>::AccountSignatureScheme as SignatureScheme>::setup(SRS) .generate_private_key(&mut rand::thread_rng()); let bytes = sk.to_bytes_le().unwrap(); let keys = AleoKeys::<Testnet2>::import_private_key(&bytes).unwrap(); let message = (0..32) .map(|_| rand::thread_rng().gen::<u8>()) .collect::<Vec<u8>>(); let sig = keys.sign(&message).unwrap(); assert!(keys.verify(&message, &sig).unwrap()); } }
34.536585
99
0.623941
5b365ae60364769622bea826ac1aa85194dc338f
3,988
use bracket_lib::prelude::*; use std::sync::{Arc, Mutex}; pub struct UiRect { rect: Rect, ui: Ui, } impl DrawUi for UiRect { fn draw(&self, ctx: &mut DrawContext) { ctx.bterm.draw_box( self.rect.position.x, self.rect.position.y, self.rect.width - 1, self.rect.height - 1, GREEN, DARK_GREEN, ); self.ui.draw(ctx); } } pub struct UiPrint { color: (u8, u8, u8), rect: Rect, text: String, } impl DrawUi for UiPrint { fn draw(&self, ctx: &mut DrawContext) { ctx.bterm.print_color( self.rect.position.x, self.rect.position.y, self.color, BLACK, &self.text, ); } } pub trait DrawUi { fn draw(&self, ctx: &mut DrawContext); } #[derive(Clone)] pub struct Rect { pub position: Point, pub width: i32, pub height: i32, } pub struct DrawContext<'a> { pub bterm: &'a mut BTerm, } pub struct Ui { pub mouse_point: Point, pub mouse_click: bool, pub offset: Point, pub rect: Rect, pub drawables: Vec<Box<dyn DrawUi>>, } impl Ui { pub fn new(ctx: &BTerm, rect: Rect) -> Self { Self { mouse_point: ctx.mouse_point(), mouse_click: INPUT.lock().is_mouse_button_pressed(0) && ctx.left_click, offset: Point::new(0, 0), rect, drawables: Vec::new(), } } pub fn sub(&self, width: i32, height: i32, offset: Point) -> Ui { Ui { mouse_point: self.mouse_point, mouse_click: self.mouse_click, rect: Rect { position: self.rect.position + self.offset.clone(), width, height, }, offset, drawables: Vec::new(), } } pub fn get_rect(&self) -> Rect { Rect { position: self.rect.position + self.offset, width: self.rect.width, height: self.rect.height, } } pub fn set_offset(&mut self, offset: Point) { self.offset = offset; } pub fn offset(&mut self, offset: Point) { self.offset = self.offset + offset; } pub fn rect(&mut self, width: i32, height: i32, mut f: impl FnMut(&mut Ui)) { let mut ui = self.sub(width, height, Point::new(1, 1)); f(&mut ui); self.drawables.push(Box::new(UiRect { rect: ui.rect.clone(), ui, })); self.offset(Point::new(0, height)); } pub fn print(&mut self, text: impl Into<String>) { self.drawables.push(Box::new(UiPrint { color: GREEN, rect: self.get_rect(), text: text.into(), })); self.offset(Point::new(0, 1)); } pub fn print_color(&mut self, color: (u8, u8, u8), text: impl Into<String>) { self.drawables.push(Box::new(UiPrint { color, rect: self.get_rect(), text: text.into(), })); self.offset(Point::new(0, 1)); } pub fn text(&mut self, text: impl Into<String>, mut f: impl FnMut(&Ui)) { let text = text.into(); let ui = self.sub(text.len() as i32, 1, Point::new(0, 0)); f(&ui); self.drawables.push(Box::new(UiPrint { color: GREEN, rect: self.get_rect(), text: text, })); self.offset(Point::new(0, 1)); } pub fn clicked(&self) -> bool { self.mouse_click && self.mouse_point.x >= self.rect.position.x && self.mouse_point.x <= self.rect.position.x + self.rect.width && self.mouse_point.y >= self.rect.position.y && self.mouse_point.y <= self.rect.position.y + self.rect.height } } impl DrawUi for Ui { fn draw(&self, ctx: &mut DrawContext) { for drawable in &self.drawables { drawable.draw(ctx); } } }
24.024096
83
0.512538
01510cdc92ba6be7e4c8109c34e0afed2b67ef1b
30,826
/// Manage binding state in the VM. /// /// Bindings associate variables in the VM with constraints or values. use std::collections::{HashMap, HashSet}; use crate::{ error::{PolarResult, RuntimeError}, folder::{fold_list, fold_term, Folder}, terms::{has_rest_var, Operation, Operator, Symbol, Term, Value}, vm::Goal, }; #[derive(Clone, Debug)] pub struct Binding(pub Symbol, pub Term); // TODO This is only public for debugger and inverter. // Eventually this should be an internal interface. pub type BindingStack = Vec<Binding>; pub type Bindings = HashMap<Symbol, Term>; pub type Bsp = Bsps; pub type FollowerId = usize; /// Bsps represents bsps of a binding manager and its followers as a tree. #[derive(Clone, Debug, Default, PartialEq)] pub struct Bsps { /// Index into `bindings` array bindings_index: usize, /// Store bsps of followers (and their followers) by follower id. followers: HashMap<FollowerId, Bsps>, } /// Variable binding state. /// /// A variable is Unbound if it is not bound to a concrete value. /// A variable is Bound if it is bound to a ground value (not another variable). /// A variable is Partial if it is bound to other variables, or constrained. #[derive(Clone, Debug, PartialEq, Eq)] pub enum VariableState { Unbound, Bound(Term), Partial, } struct Derefer<'a> { binding_manager: &'a BindingManager, seen: HashSet<u64>, } impl<'a> Derefer<'a> { fn new(binding_manager: &'a BindingManager) -> Self { Self { binding_manager, seen: HashSet::new(), } } } impl<'a> Folder for Derefer<'a> { fn fold_list(&mut self, list: Vec<Term>) -> Vec<Term> { let has_rest = has_rest_var(&list); let mut list = fold_list(list, self); if has_rest { let last = list.pop().unwrap(); if let Value::List(rest) = last.value() { list.append(&mut rest.clone()); } else { list.push(last); } } list } fn fold_term(&mut self, t: Term) -> Term { match t.value() { Value::Expression(_) => t, Value::Variable(v) | Value::RestVariable(v) => { let hash = t.hash_value(); if self.seen.contains(&hash) { t } else { self.seen.insert(hash); let t = self.binding_manager.lookup(v).unwrap_or(t); let t = fold_term(t, self); self.seen.remove(&hash); t } } _ => fold_term(t, self), } } } /// Represent each binding in a cycle as a unification constraint. // TODO(gj): put this in an impl block on VariableState? fn cycle_constraints(cycle: Vec<Symbol>) -> Operation { let mut constraints = op!(And); for (x, y) in cycle.iter().zip(cycle.iter().skip(1)) { constraints.add_constraint(op!(Unify, term!(x.clone()), term!(y.clone()))); } constraints } impl From<BindingManagerVariableState<'_>> for VariableState { fn from(other: BindingManagerVariableState) -> Self { use BindingManagerVariableState::*; // We represent Cycles as a Partial VariableState. This information is not // needed in the VM, so unbound could be an acceptable representation as well. // The partial representation does not slow down the VM since grounding happens // within BindingManager::bind. The fast path of `bind_variables` is still taken // instead of running Operation::ground. match other { Unbound => Self::Unbound, Bound(b) => Self::Bound(b), Cycle(_) => Self::Partial, Partial(_) => Self::Partial, } } } /// Internal variable binding state. /// /// Includes the Cycle representation in addition to VariableState. #[derive(Clone, Debug, PartialEq, Eq)] enum BindingManagerVariableState<'a> { Unbound, Bound(Term), Cycle(Vec<Symbol>), Partial(&'a Operation), } /// The `BindingManager` maintains associations between variables and values, /// and constraints. /// /// A variable may be: /// - unbound /// - bound /// - constrained /// /// Variables may also be bound together such that their values or constraints /// will be the same. /// /// A binding is created with the `bind` method. /// /// The constraints or value associated with a variable is retrieved with `variable_state`. #[derive(Clone, Debug, Default)] pub struct BindingManager { bindings: BindingStack, followers: HashMap<FollowerId, BindingManager>, next_follower_id: FollowerId, } // Public interface. impl BindingManager { pub fn new() -> Self { Self::default() } /// Bind `var` to `val` in the expression `partial`. /// /// If the binding succeeds, the new expression is returned as a goal. Otherwise, /// an error is returned. fn partial_bind(&mut self, partial: Operation, var: &Symbol, val: Term) -> PolarResult<Goal> { match partial.ground(var, val.clone()) { None => Err(RuntimeError::IncompatibleBindings { msg: "Grounding failed A".into(), } .into()), Some(grounded) => { self.add_binding(var, val); Ok(Goal::Query { term: grounded.into(), }) } } } // **** State Mutation *** /// Bind `var` to `val`. /// /// If the binding succeeds, Ok with an optional goal is returned. The goal will be /// present if the binding replaces a partial, which then needs to be reevaluated /// to ensure compatibility. /// /// If the binding is *incompatible* an error is returned. A binding is considered /// *incompatible* if either: /// /// 1. `var` is already bound to some value (rebindings are not allowed, even if the /// rebinding is to the same value). /// 2. `var` is constrained, and the new binding of `val` is not compatible with those /// constraints (as determined by `Operation::ground()`) /// /// If a binding is compatible, it is recorded. If the binding was to a ground value, /// subsequent calls to `variable_state` or `deep_deref` will return that value. /// /// If the binding was between two variables, the two will always have the same value /// or constraints going forward. Further, a unification constraint is recorded between /// the two variables. /// /// If either variable is bound in the future, both will be bound to that value /// (`variable_state` and `deref` will return the same value). /// /// If a binding between two variables is made, and one is bound and the other unbound, the /// unbound variable will take the value of the bound one. pub fn bind(&mut self, var: &Symbol, val: Term) -> PolarResult<Option<Goal>> { use BindingManagerVariableState::*; let mut goal = None; if let Ok(symbol) = val.as_symbol() { goal = self.bind_variables(var, symbol)?; } else { match self._variable_state(var) { Partial(p) => { let p = p.clone(); let val = val.clone(); goal = Some(self.partial_bind(p, var, val)?) } Bound(_) => { return Err(RuntimeError::IncompatibleBindings { msg: format!("Cannot rebind {:?}", var), } .into()) } _ => self.add_binding(var, val.clone()), } } // If the main binding succeeded, the follower binding must succeed. self.do_followers(|_, follower| { follower.bind(var, val.clone())?; Ok(()) }) .unwrap(); Ok(goal) } /// Rebind `var` to `val`, regardless of compatibility. /// /// A rebinding is only allowed if a variable is unbound, or already bound. /// /// Constrained variables, or variables that have been bound with other variables /// cannot be rebound. /// /// Note: Rebinding a variable that has been previously bound to other variables will place the /// BindingManager in an invalid state. For this reason, rebinding should be used with care. /// /// (The only current usage is for replacing default values with call ids). pub fn unsafe_rebind(&mut self, var: &Symbol, val: Term) { use BindingManagerVariableState::*; assert!(matches!(self._variable_state(var), Unbound | Bound(_))); self.add_binding(var, val); } /// Add a constraint. Constraints are represented as term expressions. /// /// `term` must be an expression`. /// /// An error is returned if the constraint is incompatible with existing constraints. pub fn add_constraint(&mut self, term: &Term) -> PolarResult<()> { use BindingManagerVariableState::*; self.do_followers(|_, follower| follower.add_constraint(term))?; assert!(term.as_expression().is_ok()); let mut op = op!(And, term.clone()); // include all constraints applying to any of its variables. for var in op.variables().iter().rev() { match self._variable_state(var) { Cycle(c) => op = cycle_constraints(c).merge_constraints(op), Partial(e) => op = e.clone().merge_constraints(op), _ => {} } } let vars = op.variables(); let mut varset = vars.iter().collect::<HashSet<_>>(); // replace any bound variables with their values. for var in vars.iter() { if let Bound(val) = self._variable_state(var) { varset.remove(var); match op.ground(var, val) { Some(o) => op = o, None => { return Err(RuntimeError::IncompatibleBindings { msg: "Grounding failed B".into(), } .into()) } } } } // apply the new constraint to every remaining variable. for var in varset { self.add_binding(var, op.clone().into()) } Ok(()) } /// Reset the state of `BindingManager` to what it was at `to`. pub fn backtrack(&mut self, to: &Bsp) { self.do_followers(|follower_id, follower| { if let Some(follower_to) = to.followers.get(&follower_id) { follower.backtrack(follower_to); } else { follower.backtrack(&Bsp::default()); } Ok(()) }) .unwrap(); self.bindings.truncate(to.bindings_index) } // *** Binding Inspection *** /// Dereference all variables in term, including within nested structures like /// lists and dictionaries. pub fn deep_deref(&self, term: &Term) -> Term { Derefer::new(self).fold_term(term.clone()) } /// Get constraints on variable `variable`. If the variable is in a cycle, /// the cycle is expressed as a partial. pub fn get_constraints(&self, variable: &Symbol) -> Operation { use BindingManagerVariableState::*; match self._variable_state(variable) { Unbound => op!(And), Bound(val) => op!(And, term!(op!(Unify, term!(variable.clone()), val))), Partial(expr) => expr.clone(), Cycle(c) => cycle_constraints(c), } } pub fn variable_state(&self, variable: &Symbol) -> VariableState { self.variable_state_at_point(variable, &self.bsp()) } pub fn variable_state_at_point(&self, variable: &Symbol, bsp: &Bsp) -> VariableState { let index = bsp.bindings_index; let mut next = variable; while let Some(value) = self.value(next, index) { match value.value() { Value::Expression(_) => return VariableState::Partial, Value::Variable(v) | Value::RestVariable(v) => { if v == variable { return VariableState::Partial; } else { next = v; } } _ => return VariableState::Bound(value.clone()), } } VariableState::Unbound } /// Return all variables used in this binding manager. pub fn variables(&self) -> HashSet<Symbol> { self.bindings .iter() .map(|Binding(v, _)| v.clone()) .collect() } /// Retrieve an opaque value representing the current state of `BindingManager`. /// Can be used to reset state with `backtrack`. pub fn bsp(&self) -> Bsp { let follower_bsps = self .followers .iter() .map(|(id, f)| (*id, f.bsp())) .collect::<HashMap<_, _>>(); Bsps { bindings_index: self.bindings.len(), followers: follower_bsps, } } pub fn bindings(&self, include_temps: bool) -> Bindings { self.bindings_after(include_temps, &Bsp::default()) } pub fn bindings_after(&self, include_temps: bool, after: &Bsp) -> Bindings { let mut bindings = HashMap::new(); for Binding(var, value) in &self.bindings[after.bindings_index..] { if !include_temps && var.is_temporary_var() { continue; } bindings.insert(var.clone(), self.deep_deref(value)); } bindings } pub fn variable_bindings(&self, variables: &HashSet<Symbol>) -> Bindings { let mut bindings = HashMap::new(); for var in variables.iter() { let value = self.value(var, self.bsp().bindings_index); if let Some(value) = value { bindings.insert(var.clone(), self.deep_deref(value)); } } bindings } /// Get the bindings stack *for debugging purposes only*. pub fn bindings_debug(&self) -> &BindingStack { &self.bindings } // *** Followers *** pub fn add_follower(&mut self, follower: BindingManager) -> FollowerId { let follower_id = self.next_follower_id; self.followers.insert(follower_id, follower); self.next_follower_id += 1; follower_id } pub fn remove_follower(&mut self, follower_id: &FollowerId) -> Option<BindingManager> { self.followers.remove(follower_id) } } // Private impls. impl BindingManager { /// Bind two variables together. fn bind_variables(&mut self, left: &Symbol, right: &Symbol) -> PolarResult<Option<Goal>> { use BindingManagerVariableState::*; match ( // rebinding the variable with its state makes it possible // to handle symmetric cases in one branch (left, self._variable_state(left)), (right, self._variable_state(right)), ) { // same variables, do nothing _ if left == right => Ok(None), // free / cycle cases -- variables are unbound or bound only bound // to other variables // free x free -- create a pair of bindings var -> var ((_, Unbound), (_, Unbound)) => { self.add_binding(left, term!(right.clone())); self.add_binding(right, term!(left.clone())); Ok(None) } // free x cycle, cycle x free -- create a pair of bindings var -> var ((var, Unbound), (cvar, Cycle(cycle))) | ((cvar, Cycle(cycle)), (var, Unbound)) => { let last = cycle.last().unwrap(); assert_ne!(last, cvar); self.add_binding(last, term!(var.clone())); self.add_binding(var, term!(cvar.clone())); Ok(None) } // cycle x cycle -- two cases ((_, Cycle(left_cycle)), (_, Cycle(right_cycle))) => { let iter_left = left_cycle.iter().collect::<HashSet<&Symbol>>(); let iter_right = right_cycle.iter().collect::<HashSet<&Symbol>>(); // already the same cycle? then do nothing if iter_left.intersection(&iter_right).next().is_some() { assert_eq!(iter_left, iter_right); // else join them with a pair of bindings var -> var } else { let last_left = left_cycle.last().unwrap(); let last_right = right_cycle.last().unwrap(); assert_ne!(last_left, left); assert_ne!(last_right, right); self.add_binding(last_left, term!(right.clone())); self.add_binding(last_right, term!(left.clone())); } Ok(None) } // bound / partial cases -- at least one variable has a value // or constraint // // bound x free , free x bound, bound x cycle , cycle x bound -- // create a binding var -> val ((var, Unbound), (_, Bound(val))) | ((_, Bound(val)), (var, Unbound)) | ((var, Cycle(_)), (_, Bound(val))) | ((_, Bound(val)), (var, Cycle(_))) => { self.add_binding(var, val); Ok(None) } // partial x free, free x partial, partial x cycle, cycle x partial -- // extend partials ((_, Partial(_)), (_, Unbound)) | ((_, Unbound), (_, Partial(_))) | ((_, Partial(_)), (_, Cycle(_))) | ((_, Cycle(_)), (_, Partial(_))) => { self.add_constraint(&op!(Unify, term!(left.clone()), term!(right.clone())).into())?; Ok(None) } // bound x bound to different values : binding fails // (this error usually gets caught and turned into a backtrack) ((_, Bound(l)), (_, Bound(r))) => { if l == r { Ok(None) } else { Err(RuntimeError::IncompatibleBindings { msg: format!("{} and {} are both bound", left, right), } .into()) } } // bound x partial , partial x bound -- ground and requery ((_, Bound(val)), (var, Partial(p))) | ((var, Partial(p)), (_, Bound(val))) => { let p = p.clone(); Ok(Some(self.partial_bind(p, var, val)?)) } // partial x partial -- if they already overlap, do nothing. // else rebind vars as a 2-cycle & requery ((lv, Partial(lp)), (rv, Partial(rp))) => { if rp.variables().contains(left) { Ok(None) } else { // Merge the two partials. let merged = lp.clone().merge_constraints(rp.clone()); // Express the partial in terms of lv (bind rv to lv, replacing all rv in partial with lv). let goal = self.partial_bind(merged, rv, term!(lv.clone()))?; // Unification from lv = rv (remember that vars are equal so that the // simplifier can later choose the correct one). We do this // after the partial bind so that we don't recursively query the unification. let unify = term!(op!(Unify, term!(lv.clone()), term!(rv.clone()))); self.add_constraint(&unify)?; Ok(Some(goal)) } } } } fn add_binding(&mut self, var: &Symbol, val: Term) { self.bindings.push(Binding(var.clone(), val)); } fn lookup(&self, var: &Symbol) -> Option<Term> { match self.variable_state(var) { VariableState::Bound(val) => Some(val), _ => None, } } /// Look up a variable in the bindings stack and return /// a reference to its value if it's bound. fn value(&self, variable: &Symbol, bsp: usize) -> Option<&Term> { self.bindings[..bsp] .iter() .rev() .find(|Binding(var, _)| var == variable) .map(|Binding(_, val)| val) } fn _variable_state(&self, variable: &Symbol) -> BindingManagerVariableState { self._variable_state_at_point(variable, &self.bsp()) } /// Check the state of `variable` at `bsp`. fn _variable_state_at_point( &self, variable: &Symbol, bsp: &Bsp, ) -> BindingManagerVariableState { use BindingManagerVariableState::*; let index = bsp.bindings_index; let mut path = vec![variable]; while let Some(value) = self.value(path.last().unwrap(), index) { match value.value() { Value::Expression(e) => return Partial(e), Value::Variable(v) | Value::RestVariable(v) => { if v == variable { return Cycle(path.into_iter().cloned().collect()); } else { path.push(v); } } _ => return Bound(value.clone()), } } Unbound } fn do_followers<F>(&mut self, mut func: F) -> PolarResult<()> where F: FnMut(FollowerId, &mut BindingManager) -> PolarResult<()>, { for (id, follower) in self.followers.iter_mut() { func(*id, follower)? } Ok(()) } } #[cfg(test)] mod test { use super::*; #[test] fn variable_state() { let mut bindings = BindingManager::new(); let x = sym!("x"); let y = sym!("y"); let z = sym!("z"); // Unbound. assert_eq!( bindings._variable_state(&x), BindingManagerVariableState::Unbound ); // Bound. bindings.add_binding(&x, term!(1)); assert_eq!( bindings._variable_state(&x), BindingManagerVariableState::Bound(term!(1)) ); bindings.add_binding(&x, term!(x.clone())); assert_eq!( bindings._variable_state(&x), BindingManagerVariableState::Cycle(vec![x.clone()]) ); // 2-cycle. bindings.add_binding(&x, term!(y.clone())); bindings.add_binding(&y, term!(x.clone())); assert_eq!( bindings._variable_state(&x), BindingManagerVariableState::Cycle(vec![x.clone(), y.clone()]) ); assert_eq!( bindings._variable_state(&y), BindingManagerVariableState::Cycle(vec![y.clone(), x.clone()]) ); // 3-cycle. bindings.add_binding(&x, term!(y.clone())); bindings.add_binding(&y, term!(z.clone())); bindings.add_binding(&z, term!(x.clone())); assert_eq!( bindings._variable_state(&x), BindingManagerVariableState::Cycle(vec![x.clone(), y.clone(), z.clone()]) ); assert_eq!( bindings._variable_state(&y), BindingManagerVariableState::Cycle(vec![y.clone(), z.clone(), x.clone()]) ); assert_eq!( bindings._variable_state(&z), BindingManagerVariableState::Cycle(vec![z.clone(), x.clone(), y]) ); // Expression. bindings.add_binding(&x, term!(op!(And))); assert_eq!( bindings._variable_state(&x), BindingManagerVariableState::Partial(&op!(And)) ); } #[test] fn test_followers() { // Regular bindings let mut b1 = BindingManager::new(); b1.bind(&sym!("x"), term!(1)).unwrap(); b1.bind(&sym!("y"), term!(2)).unwrap(); assert_eq!( b1._variable_state(&sym!("x")), BindingManagerVariableState::Bound(term!(1)) ); assert_eq!( b1._variable_state(&sym!("y")), BindingManagerVariableState::Bound(term!(2)) ); let b2 = BindingManager::new(); let b2_id = b1.add_follower(b2); b1.bind(&sym!("z"), term!(3)).unwrap(); assert_eq!( b1._variable_state(&sym!("x")), BindingManagerVariableState::Bound(term!(1)) ); assert_eq!( b1._variable_state(&sym!("y")), BindingManagerVariableState::Bound(term!(2)) ); assert_eq!( b1._variable_state(&sym!("z")), BindingManagerVariableState::Bound(term!(3)) ); let b2 = b1.remove_follower(&b2_id).unwrap(); assert_eq!( b2._variable_state(&sym!("x")), BindingManagerVariableState::Unbound ); assert_eq!( b2._variable_state(&sym!("y")), BindingManagerVariableState::Unbound ); assert_eq!( b2._variable_state(&sym!("z")), BindingManagerVariableState::Bound(term!(3)) ); // Extending cycle. let mut b1 = BindingManager::new(); b1.bind(&sym!("x"), term!(sym!("y"))).unwrap(); b1.bind(&sym!("x"), term!(sym!("z"))).unwrap(); let b2 = BindingManager::new(); let b2_id = b1.add_follower(b2); assert!(matches!( b1._variable_state(&sym!("x")), BindingManagerVariableState::Cycle(_) )); assert!(matches!( b1._variable_state(&sym!("y")), BindingManagerVariableState::Cycle(_) )); assert!(matches!( b1._variable_state(&sym!("z")), BindingManagerVariableState::Cycle(_) )); b1.bind(&sym!("x"), term!(sym!("a"))).unwrap(); if let BindingManagerVariableState::Cycle(c) = b1._variable_state(&sym!("a")) { assert_eq!( c, vec![sym!("a"), sym!("x"), sym!("y"), sym!("z")], "c was {:?}", c ); } let b2 = b1.remove_follower(&b2_id).unwrap(); if let BindingManagerVariableState::Cycle(c) = b2._variable_state(&sym!("a")) { assert_eq!(c, vec![sym!("a"), sym!("x")], "c was {:?}", c); } else { panic!("unexpected"); } if let BindingManagerVariableState::Cycle(c) = b2._variable_state(&sym!("x")) { assert_eq!(c, vec![sym!("x"), sym!("a")], "c was {:?}", c); } else { panic!("unexpected"); } // Adding constraints to cycles. let mut b1 = BindingManager::new(); b1.bind(&sym!("x"), term!(sym!("y"))).unwrap(); b1.bind(&sym!("x"), term!(sym!("z"))).unwrap(); let b2 = BindingManager::new(); let b2_id = b1.add_follower(b2); assert!(matches!( b1._variable_state(&sym!("x")), BindingManagerVariableState::Cycle(_) )); assert!(matches!( b1._variable_state(&sym!("y")), BindingManagerVariableState::Cycle(_) )); assert!(matches!( b1._variable_state(&sym!("z")), BindingManagerVariableState::Cycle(_) )); b1.add_constraint(&term!(op!(Gt, term!(sym!("x")), term!(sym!("y"))))) .unwrap(); let b2 = b1.remove_follower(&b2_id).unwrap(); if let BindingManagerVariableState::Partial(p) = b1._variable_state(&sym!("x")) { assert_eq!(p.to_string(), "x = y and y = z and z = x and x > y"); } else { panic!("unexpected"); } if let BindingManagerVariableState::Partial(p) = b2._variable_state(&sym!("x")) { assert_eq!(p.to_string(), "x > y"); } else { panic!("unexpected"); } } #[test] fn old_deref() { let mut bm = BindingManager::default(); let value = term!(1); let x = sym!("x"); let y = sym!("y"); let term_x = term!(x.clone()); let term_y = term!(y.clone()); // unbound var assert_eq!(bm.deep_deref(&term_x), term_x); // unbound var -> unbound var bm.bind(&x, term_y.clone()).unwrap(); assert_eq!(bm.deep_deref(&term_x), term_x); // value assert_eq!(bm.deep_deref(&value), value.clone()); // unbound var -> value let mut bm = BindingManager::default(); bm.bind(&x, value.clone()).unwrap(); assert_eq!(bm.deep_deref(&term_x), value); // unbound var -> unbound var -> value let mut bm = BindingManager::default(); bm.bind(&x, term_y).unwrap(); bm.bind(&y, value.clone()).unwrap(); assert_eq!(bm.deep_deref(&term_x), value); } #[test] fn deep_deref() { let mut bm = BindingManager::default(); let one = term!(1); let two = term!(1); let one_var = sym!("one"); let two_var = sym!("two"); bm.bind(&one_var, one.clone()).unwrap(); bm.bind(&two_var, two.clone()).unwrap(); let dict = btreemap! { sym!("x") => term!(one_var), sym!("y") => term!(two_var), }; let list = term!([dict]); assert_eq!( bm.deep_deref(&list).value().clone(), Value::List(vec![term!(btreemap! { sym!("x") => one, sym!("y") => two, })]) ); } #[test] fn bind() { let x = sym!("x"); let y = sym!("y"); let zero = term!(0); let mut bm = BindingManager::default(); bm.bind(&x, zero.clone()).unwrap(); assert_eq!(bm.variable_state(&x), VariableState::Bound(zero)); assert_eq!(bm.variable_state(&y), VariableState::Unbound); } #[test] fn test_backtrack_followers() { // Regular bindings let mut b1 = BindingManager::new(); b1.bind(&sym!("x"), term!(sym!("y"))).unwrap(); b1.bind(&sym!("z"), term!(sym!("x"))).unwrap(); let b2 = BindingManager::new(); let b2_id = b1.add_follower(b2); b1.add_constraint(&term!(op!(Gt, term!(sym!("x")), term!(1)))) .unwrap(); let bsp = b1.bsp(); b1.bind(&sym!("a"), term!(sym!("x"))).unwrap(); assert!(matches!( b1.variable_state(&sym!("a")), VariableState::Partial )); b1.backtrack(&bsp); let b2 = b1.remove_follower(&b2_id).unwrap(); assert!(matches!( b2.variable_state(&sym!("a")), VariableState::Unbound )); } }
34.213097
111
0.52991
7284a19c8ded5aa7d98305f5faf0dfebea6d8cf6
3,184
#[doc = "Register `se_aes_0_key_2` reader"] pub struct R(crate::R<SE_AES_0_KEY_2_SPEC>); impl core::ops::Deref for R { type Target = crate::R<SE_AES_0_KEY_2_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<SE_AES_0_KEY_2_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<SE_AES_0_KEY_2_SPEC>) -> Self { R(reader) } } #[doc = "Register `se_aes_0_key_2` writer"] pub struct W(crate::W<SE_AES_0_KEY_2_SPEC>); impl core::ops::Deref for W { type Target = crate::W<SE_AES_0_KEY_2_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for W { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<crate::W<SE_AES_0_KEY_2_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<SE_AES_0_KEY_2_SPEC>) -> Self { W(writer) } } #[doc = "Field `se_aes_0_key_2` reader - "] pub struct SE_AES_0_KEY_2_R(crate::FieldReader<u32, u32>); impl SE_AES_0_KEY_2_R { #[inline(always)] pub(crate) fn new(bits: u32) -> Self { SE_AES_0_KEY_2_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for SE_AES_0_KEY_2_R { type Target = crate::FieldReader<u32, u32>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `se_aes_0_key_2` writer - "] pub struct SE_AES_0_KEY_2_W<'a> { w: &'a mut W, } impl<'a> SE_AES_0_KEY_2_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u32) -> &'a mut W { self.w.bits = value; self.w } } impl R { #[doc = "Bits 0:31"] #[inline(always)] pub fn se_aes_0_key_2(&self) -> SE_AES_0_KEY_2_R { SE_AES_0_KEY_2_R::new(self.bits) } } impl W { #[doc = "Bits 0:31"] #[inline(always)] pub fn se_aes_0_key_2(&mut self) -> SE_AES_0_KEY_2_W { SE_AES_0_KEY_2_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.0.bits(bits); self } } #[doc = "se_aes_0_key_2.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [se_aes_0_key_2](index.html) module"] pub struct SE_AES_0_KEY_2_SPEC; impl crate::RegisterSpec for SE_AES_0_KEY_2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [se_aes_0_key_2::R](R) reader structure"] impl crate::Readable for SE_AES_0_KEY_2_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [se_aes_0_key_2::W](W) writer structure"] impl crate::Writable for SE_AES_0_KEY_2_SPEC { type Writer = W; } #[doc = "`reset()` method sets se_aes_0_key_2 to value 0"] impl crate::Resettable for SE_AES_0_KEY_2_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
30.615385
410
0.627513
08a09c03864a33339e998b6c382748751a909602
7,447
#[cfg(test)] #[path = "../../../tests/unit/models/common/domain_test.rs"] mod domain_test; use crate::models::common::{Duration, Timestamp}; use hashbrown::HashMap; use rosomaxa::prelude::compare_floats; use std::any::Any; use std::cmp::Ordering; use std::hash::{Hash, Hasher}; use std::sync::Arc; /// Specifies location type. pub type Location = usize; /// Represents a routing profile. #[derive(Clone, Debug)] pub struct Profile { /// An unique index. pub index: usize, /// A duration scale factor. pub scale: f64, } impl Profile { /// Creates a new instance of `Profile`. pub fn new(index: usize, scale: Option<f64>) -> Profile { Self { index, scale: scale.unwrap_or(1.) } } } impl Default for Profile { fn default() -> Self { Self { index: 0, scale: 1. } } } /// Specifies cost value. pub type Cost = f64; /// Represents a time window. #[derive(Clone, Debug)] pub struct TimeWindow { /// Start of time window. pub start: Timestamp, /// End of time window. pub end: Timestamp, } /// Represents a time offset. #[derive(Clone, Debug)] pub struct TimeOffset { /// Offset value to start time. pub start: Timestamp, /// Offset value to end time. pub end: Timestamp, } /// A enum for various time definitions. #[derive(Clone, Debug)] pub enum TimeSpan { /// A time window variant. Window(TimeWindow), /// A time offset variant. Offset(TimeOffset), } /// Specifies a flexible time interval. #[derive(Clone, Debug, Default)] pub struct TimeInterval { /// Earliest possible time to start. pub earliest: Option<Timestamp>, /// Latest possible time to stop. pub latest: Option<Timestamp>, } impl TimeWindow { /// Creates a new [`TimeWindow`]. pub fn new(start: Timestamp, end: Timestamp) -> Self { Self { start, end } } /// Returns unlimited time window. pub fn max() -> Self { Self { start: 0., end: f64::MAX } } /// Checks whether time window has intersection with another one (inclusive). pub fn intersects(&self, other: &Self) -> bool { compare_floats(self.start, other.end) != Ordering::Greater && compare_floats(other.start, self.end) != Ordering::Greater } /// Checks whether time window contains given time. pub fn contains(&self, time: Timestamp) -> bool { compare_floats(time, self.start) != Ordering::Less && compare_floats(time, self.end) != Ordering::Greater } /// Returns distance between two time windows. pub fn distance(&self, other: &Self) -> Timestamp { if self.intersects(other) { 0. } else { // [other.s other.e] [self.s self.e] if self.start > other.start { self.start - other.end } else { // [self.s self.e] [other.s other.e] other.start - self.end } } } /// Returns a new overlapping time window. pub fn overlapping(&self, other: &Self) -> Option<TimeWindow> { if self.intersects(other) { let start = self.start.max(other.start); let end = self.end.min(other.end); Some(TimeWindow::new(start, end)) } else { None } } /// Returns duration of time window. pub fn duration(&self) -> Duration { self.end - self.start } } impl PartialEq<TimeWindow> for TimeWindow { fn eq(&self, other: &TimeWindow) -> bool { compare_floats(self.start, other.start) == Ordering::Equal && compare_floats(self.end, other.end) == Ordering::Equal } } impl Eq for TimeWindow {} impl Hash for TimeWindow { fn hash<H: Hasher>(&self, state: &mut H) { let start = self.start.to_bits() as i64; let end = self.end.to_bits() as i64; start.hash(state); end.hash(state); } } impl TimeOffset { /// Creates a new [`TimeOffset`]. pub fn new(start: Timestamp, end: Timestamp) -> Self { Self { start, end } } } impl TimeSpan { /// Converts given time span into time window. pub fn to_time_window(&self, date: Timestamp) -> TimeWindow { match &self { TimeSpan::Window(window) => window.clone(), TimeSpan::Offset(offset) => TimeWindow::new(date + offset.start, date + offset.end), } } /// Checks that this time span intersects with given time windows. pub fn intersects(&self, date: Timestamp, other: &TimeWindow) -> bool { self.to_time_window(date).intersects(other) } /// If time span is time window, then return it. Otherwise, return None. pub fn as_time_window(&self) -> Option<TimeWindow> { match &self { TimeSpan::Window(window) => Some(window.clone()), _ => None, } } } impl TimeInterval { /// Converts time interval to time window. pub fn to_time_window(&self) -> TimeWindow { TimeWindow { start: self.earliest.unwrap_or(0.), end: self.latest.unwrap_or(f64::MAX) } } } /// Represents a schedule. #[derive(Clone, Debug)] pub struct Schedule { /// Arrival time. pub arrival: Timestamp, /// Departure time. pub departure: Timestamp, } impl Schedule { /// Creates a new instance of `Schedule`. pub fn new(arrival: Timestamp, departure: Timestamp) -> Self { Self { arrival, departure } } } impl PartialEq<Schedule> for Schedule { fn eq(&self, other: &Schedule) -> bool { compare_floats(self.arrival, other.arrival) == Ordering::Equal && compare_floats(self.departure, other.departure) == Ordering::Equal } } impl Eq for Schedule {} /// Multiple named dimensions which can contain anything: /// * unit of measure, e.g. volume, mass, size, etc. /// * set of skills /// * tag. pub type Dimensions = HashMap<String, Arc<dyn Any + Send + Sync>>; /// A trait to return arbitrary typed value by its key. pub trait ValueDimension { /// Gets value from dimension with given key. fn get_value<T: 'static>(&self, key: &str) -> Option<&T>; /// Sets value in dimension with given key and value. fn set_value<T: 'static + Sync + Send>(&mut self, key: &str, value: T); } impl ValueDimension for Dimensions { fn get_value<T: 'static>(&self, key: &str) -> Option<&T> { self.get(key).and_then(|any| any.downcast_ref::<T>()) } fn set_value<T: 'static + Sync + Send>(&mut self, key: &str, value: T) { self.insert(key.to_owned(), Arc::new(value)); } } /// A trait to get or set id. pub trait IdDimension { /// Sets value as id. fn set_id(&mut self, id: &str) -> &mut Self; /// Gets id value if present. fn get_id(&self) -> Option<&String>; } impl IdDimension for Dimensions { fn set_id(&mut self, id: &str) -> &mut Self { self.set_value("id", id.to_string()); self } fn get_id(&self) -> Option<&String> { self.get_value("id") } } impl Hash for TimeInterval { fn hash<H: Hasher>(&self, state: &mut H) { let earliest = self.earliest.unwrap_or(0.).to_bits() as i64; let latest = self.latest.unwrap_or(f64::MAX).to_bits() as i64; earliest.hash(state); latest.hash(state); } } impl Eq for TimeInterval {} impl PartialEq for TimeInterval { fn eq(&self, other: &Self) -> bool { self.earliest == other.earliest && self.latest == other.latest } }
27.278388
113
0.606016
e9a20e59f010957541f9ba9c75044bec1b731ca5
838
use std::pin::Pin; use core::task::{Context, Poll}; use futures::{Stream}; use tokio_rustls::server::TlsStream; use tokio::{net::TcpStream}; /*time::Duration,*/ // type BoxFut = Box<Future<Item=Response<Body>, Error=hyper::Error> + Send>; pub struct HyperTlsAcceptor<'a> { pub acceptor: Pin<Box<dyn Stream<Item = Result<TlsStream<TcpStream>, std::io::Error>> + Send + 'a>>, } impl hyper::server::accept::Accept for HyperTlsAcceptor<'_> { type Conn = TlsStream<TcpStream>; type Error = std::io::Error; fn poll_accept( mut self: Pin<&mut Self>, cx: &mut Context, ) -> Poll<Option<Result<Self::Conn, Self::Error>>> { match Pin::new(&mut self.acceptor).poll_next(cx) { Poll::Ready(Some(Err(_e))) => Poll::from(None), p => p, } } }
29.928571
105
0.593079
ddeed1d9dbed06f67e52313e7bae39b772c2fd58
350
// lib/input/ffi/unix/destroy.rs // Graphical Software Packager // Copyright 2017 (c) Aldaron's Tech // Copyright 2017 (c) Jeron Lau // Licensed under the MIT LICENSE extern { fn close(fd: i32) -> i32; } pub fn joystick(fd: i32) -> () { let failure = unsafe { close(fd) == -1 }; if failure { panic!("Failed to disconnect joystick."); } }
17.5
43
0.645714
64a980d7361136fc22859cdb99a80fa0479924b9
1,726
use crate::{Capacity, CellOutput, JsonBytes, OutPoint, Script}; use ckb_types::{ core::cell::{CellMeta, CellStatus}, prelude::Unpack, H256, }; use serde_derive::{Deserialize, Serialize}; // This is used as return value of get_cells_by_lock_hash RPC: // it contains both OutPoint data used for referencing a cell, as well as // cell's own data such as lock and capacity #[derive(Debug, Serialize, Deserialize)] pub struct CellOutputWithOutPoint { pub out_point: OutPoint, pub block_hash: H256, pub capacity: Capacity, pub lock: Script, } #[derive(Debug, Serialize, Deserialize)] pub struct CellWithStatus { pub cell: Option<CellInfo>, pub status: String, } #[derive(Debug, Serialize, Deserialize)] pub struct CellInfo { pub output: CellOutput, pub data: Option<CellData>, } #[derive(Debug, Serialize, Deserialize)] pub struct CellData { pub content: JsonBytes, pub hash: H256, } impl From<CellMeta> for CellInfo { fn from(cell_meta: CellMeta) -> Self { CellInfo { output: cell_meta.cell_output.into(), data: cell_meta.mem_cell_data.map(|(data, hash)| CellData { content: JsonBytes::from_bytes(data), hash: hash.unpack(), }), } } } impl From<CellStatus> for CellWithStatus { fn from(status: CellStatus) -> Self { let (cell, status) = match status { CellStatus::Live(cell_meta) => (Some(cell_meta), "live"), CellStatus::Dead => (None, "dead"), CellStatus::Unknown => (None, "unknown"), }; Self { cell: cell.map(|cell_meta| (*cell_meta).into()), status: status.to_string(), } } }
27.396825
73
0.625724
ccb21e849ec3bd92fe182ea9ce411061a9987e15
24,214
// Copyright 2018 Parity Technologies (UK) Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. mod event; pub mod peer; pub use event::{NetworkEvent, IncomingConnectionEvent}; pub use peer::Peer; use crate::{ ConnectedPoint, Executor, Multiaddr, PeerId, address_translation, connection::{ ConnectionId, ConnectionLimit, ConnectionHandler, ConnectionInfo, IntoConnectionHandler, IncomingInfo, OutgoingInfo, ListenersEvent, ListenerId, ListenersStream, PendingConnectionError, Substream, pool::{Pool, PoolEvent, PoolLimits}, }, muxing::StreamMuxer, transport::{Transport, TransportError}, }; use fnv::{FnvHashMap}; use futures::{prelude::*, future}; use std::{ collections::hash_map, convert::TryFrom as _, error, fmt, hash::Hash, pin::Pin, task::{Context, Poll}, }; /// Implementation of `Stream` that handles the nodes. pub struct Network<TTrans, TInEvent, TOutEvent, THandler, TConnInfo = PeerId, TPeerId = PeerId> where TTrans: Transport, THandler: IntoConnectionHandler<TConnInfo>, { /// The local peer ID. local_peer_id: TPeerId, /// Listeners for incoming connections. listeners: ListenersStream<TTrans>, /// The nodes currently active. pool: Pool<TInEvent, TOutEvent, THandler, TTrans::Error, <THandler::Handler as ConnectionHandler>::Error, TConnInfo, TPeerId>, /// The ongoing dialing attempts. /// /// The `Network` enforces a single ongoing dialing attempt per peer, /// even if multiple (established) connections per peer are allowed. /// However, a single dialing attempt operates on a list of addresses /// to connect to, which can be extended with new addresses while /// the connection attempt is still in progress. Thereby each /// dialing attempt is associated with a new connection and hence a new /// connection ID. /// /// > **Note**: `dialing` must be consistent with the pending outgoing /// > connections in `pool`. That is, for every entry in `dialing` /// > there must exist a pending outgoing connection in `pool` with /// > the same connection ID. This is ensured by the implementation of /// > `Network` (see `dial_peer_impl` and `on_connection_failed`) /// > together with the implementation of `DialingConnection::abort`. dialing: FnvHashMap<TPeerId, peer::DialingAttempt>, } impl<TTrans, TInEvent, TOutEvent, THandler, TConnInfo, TPeerId> fmt::Debug for Network<TTrans, TInEvent, TOutEvent, THandler, TConnInfo, TPeerId> where TTrans: fmt::Debug + Transport, THandler: fmt::Debug + ConnectionHandler, TConnInfo: fmt::Debug, TPeerId: fmt::Debug + Eq + Hash, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { f.debug_struct("ReachAttempts") .field("local_peer_id", &self.local_peer_id) .field("listeners", &self.listeners) .field("peers", &self.pool) .field("dialing", &self.dialing) .finish() } } impl<TTrans, TInEvent, TOutEvent, THandler, TConnInfo, TPeerId> Unpin for Network<TTrans, TInEvent, TOutEvent, THandler, TConnInfo, TPeerId> where TTrans: Transport, THandler: IntoConnectionHandler<TConnInfo>, { } impl<TTrans, TInEvent, TOutEvent, THandler, TConnInfo, TPeerId> Network<TTrans, TInEvent, TOutEvent, THandler, TConnInfo, TPeerId> where TTrans: Transport, THandler: IntoConnectionHandler<TConnInfo>, TConnInfo: ConnectionInfo<PeerId = TPeerId>, TPeerId: Eq + Hash + Clone, { fn disconnect(&mut self, peer: &TPeerId) { self.pool.disconnect(peer); self.dialing.remove(peer); } } impl<TTrans, TInEvent, TOutEvent, TMuxer, THandler, TConnInfo, TPeerId> Network<TTrans, TInEvent, TOutEvent, THandler, TConnInfo, TPeerId> where TTrans: Transport + Clone, TMuxer: StreamMuxer, THandler: IntoConnectionHandler<TConnInfo> + Send + 'static, THandler::Handler: ConnectionHandler<Substream = Substream<TMuxer>, InEvent = TInEvent, OutEvent = TOutEvent> + Send + 'static, <THandler::Handler as ConnectionHandler>::OutboundOpenInfo: Send + 'static, // TODO: shouldn't be necessary <THandler::Handler as ConnectionHandler>::Error: error::Error + Send + 'static, TConnInfo: fmt::Debug + ConnectionInfo<PeerId = TPeerId> + Send + 'static, TPeerId: Eq + Hash + Clone, { /// Creates a new node events stream. pub fn new( transport: TTrans, local_peer_id: TPeerId, config: NetworkConfig, ) -> Self { let pool_local_id = local_peer_id.clone(); Network { local_peer_id, listeners: ListenersStream::new(transport), pool: Pool::new(pool_local_id, config.executor, config.pool_limits), dialing: Default::default(), } } /// Returns the transport passed when building this object. pub fn transport(&self) -> &TTrans { self.listeners.transport() } /// Start listening on the given multiaddress. pub fn listen_on(&mut self, addr: Multiaddr) -> Result<ListenerId, TransportError<TTrans::Error>> { self.listeners.listen_on(addr) } /// Remove a previously added listener. /// /// Returns `Ok(())` if a listener with this ID was in the list. pub fn remove_listener(&mut self, id: ListenerId) -> Result<(), ()> { self.listeners.remove_listener(id) } /// Returns an iterator that produces the list of addresses we are listening on. pub fn listen_addrs(&self) -> impl Iterator<Item = &Multiaddr> { self.listeners.listen_addrs() } /// Call this function in order to know which address remotes should dial to /// access your local node. /// /// When receiving an observed address on a tcp connection that we initiated, the observed /// address contains our tcp dial port, not our tcp listen port. We know which port we are /// listening on, thereby we can replace the port within the observed address. /// /// When receiving an observed address on a tcp connection that we did **not** initiated, the /// observed address should contain our listening port. In case it differs from our listening /// port there might be a proxy along the path. /// /// # Arguments /// /// * `observed_addr` - should be an address a remote observes you as, which can be obtained for /// example with the identify protocol. /// pub fn address_translation<'a>(&'a self, observed_addr: &'a Multiaddr) -> impl Iterator<Item = Multiaddr> + 'a where TMuxer: 'a, THandler: 'a, { self.listen_addrs().flat_map(move |server| address_translation(server, observed_addr)) } /// Returns the peer id of the local node. pub fn local_peer_id(&self) -> &TPeerId { &self.local_peer_id } /// Dials a multiaddress without expecting a particular remote peer ID. /// /// The given `handler` will be used to create the /// [`Connection`](crate::connection::Connection) upon success and the /// connection ID is returned. pub fn dial(&mut self, address: &Multiaddr, handler: THandler) -> Result<ConnectionId, ConnectionLimit> where TTrans: Transport<Output = (TConnInfo, TMuxer)>, TTrans::Error: Send + 'static, TTrans::Dial: Send + 'static, TMuxer: Send + Sync + 'static, TMuxer::OutboundSubstream: Send, TInEvent: Send + 'static, TOutEvent: Send + 'static, TConnInfo: Send + 'static, TPeerId: Send + 'static, { let info = OutgoingInfo { address, peer_id: None }; match self.transport().clone().dial(address.clone()) { Ok(f) => { let f = f.map_err(|err| PendingConnectionError::Transport(TransportError::Other(err))); self.pool.add_outgoing(f, handler, info) } Err(err) => { let f = future::err(PendingConnectionError::Transport(err)); self.pool.add_outgoing(f, handler, info) } } } /// Returns information about the state of the `Network`. pub fn info(&self) -> NetworkInfo { let num_connections_established = self.pool.num_established(); let num_connections_pending = self.pool.num_pending(); let num_connections = num_connections_established + num_connections_pending; let num_peers = self.pool.num_connected(); NetworkInfo { num_peers, num_connections, num_connections_established, num_connections_pending, } } /// Returns an iterator for information on all pending incoming connections. pub fn incoming_info(&self) -> impl Iterator<Item = IncomingInfo<'_>> { self.pool.iter_pending_incoming() } /// Returns the list of addresses we're currently dialing without knowing the `PeerId` of. pub fn unknown_dials(&self) -> impl Iterator<Item = &Multiaddr> { self.pool.iter_pending_outgoing() .filter_map(|info| { if info.peer_id.is_none() { Some(info.address) } else { None } }) } /// Returns a list of all connected peers, i.e. peers to whom the `Network` /// has at least one established connection. pub fn connected_peers(&self) -> impl Iterator<Item = &TPeerId> { self.pool.iter_connected() } /// Checks whether the network has an established connection to a peer. pub fn is_connected(&self, peer: &TPeerId) -> bool { self.pool.is_connected(peer) } /// Checks whether the network has an ongoing dialing attempt to a peer. pub fn is_dialing(&self, peer: &TPeerId) -> bool { self.dialing.contains_key(peer) } /// Checks whether the network has neither an ongoing dialing attempt, /// nor an established connection to a peer. pub fn is_disconnected(&self, peer: &TPeerId) -> bool { !self.is_connected(peer) && !self.is_dialing(peer) } /// Returns a list of all the peers to whom a new outgoing connection /// is currently being established. pub fn dialing_peers(&self) -> impl Iterator<Item = &TPeerId> { self.dialing.keys() } /// Gets the configured limit on pending incoming connections, /// i.e. concurrent incoming connection attempts. pub fn incoming_limit(&self) -> Option<usize> { self.pool.limits().max_incoming } /// The total number of established connections in the `Network`. pub fn num_connections_established(&self) -> usize { self.pool.num_established() } /// The total number of pending connections in the `Network`. pub fn num_connections_pending(&self) -> usize { self.pool.num_pending() } /// Obtains a view of a [`Peer`] with the given ID in the network. pub fn peer(&mut self, peer_id: TPeerId) -> Peer<'_, TTrans, TInEvent, TOutEvent, THandler, TConnInfo, TPeerId> { Peer::new(self, peer_id) } /// Provides an API similar to `Stream`, except that it cannot error. pub fn poll<'a>(&'a mut self, cx: &mut Context) -> Poll<NetworkEvent<'a, TTrans, TInEvent, TOutEvent, THandler, TConnInfo, TPeerId>> where TTrans: Transport<Output = (TConnInfo, TMuxer)>, TTrans::Error: Send + 'static, TTrans::Dial: Send + 'static, TTrans::ListenerUpgrade: Send + 'static, TMuxer: Send + Sync + 'static, TMuxer::OutboundSubstream: Send, TInEvent: Send + 'static, TOutEvent: Send + 'static, THandler: IntoConnectionHandler<TConnInfo> + Send + 'static, THandler::Handler: ConnectionHandler<Substream = Substream<TMuxer>, InEvent = TInEvent, OutEvent = TOutEvent> + Send + 'static, <THandler::Handler as ConnectionHandler>::Error: error::Error + Send + 'static, TConnInfo: Clone, TPeerId: Send + 'static, { // Poll the listener(s) for new connections. match ListenersStream::poll(Pin::new(&mut self.listeners), cx) { Poll::Pending => (), Poll::Ready(ListenersEvent::Incoming { listener_id, upgrade, local_addr, send_back_addr }) => { return Poll::Ready(NetworkEvent::IncomingConnection( IncomingConnectionEvent { listener_id, upgrade, local_addr, send_back_addr, pool: &mut self.pool, })) } Poll::Ready(ListenersEvent::NewAddress { listener_id, listen_addr }) => { return Poll::Ready(NetworkEvent::NewListenerAddress { listener_id, listen_addr }) } Poll::Ready(ListenersEvent::AddressExpired { listener_id, listen_addr }) => { return Poll::Ready(NetworkEvent::ExpiredListenerAddress { listener_id, listen_addr }) } Poll::Ready(ListenersEvent::Closed { listener_id, addresses, reason }) => { return Poll::Ready(NetworkEvent::ListenerClosed { listener_id, addresses, reason }) } Poll::Ready(ListenersEvent::Error { listener_id, error }) => { return Poll::Ready(NetworkEvent::ListenerError { listener_id, error }) } } // Poll the known peers. let event = match self.pool.poll(cx) { Poll::Pending => return Poll::Pending, Poll::Ready(PoolEvent::ConnectionEstablished { connection, num_established }) => { match self.dialing.entry(connection.peer_id().clone()) { hash_map::Entry::Occupied(e) if e.get().id == connection.id() => { e.remove(); }, _ => {} } NetworkEvent::ConnectionEstablished { connection, num_established, } } Poll::Ready(PoolEvent::PendingConnectionError { id, endpoint, error, handler, pool, .. }) => { let dialing = &mut self.dialing; let (next, event) = on_connection_failed(dialing, id, endpoint, error, handler); if let Some(dial) = next { let transport = self.listeners.transport().clone(); if let Err(e) = dial_peer_impl(transport, pool, dialing, dial) { log::warn!("Dialing aborted: {:?}", e); } } event } Poll::Ready(PoolEvent::ConnectionError { id, connected, error, num_established, .. }) => { NetworkEvent::ConnectionError { id, connected, error, num_established, } } Poll::Ready(PoolEvent::ConnectionEvent { connection, event }) => { NetworkEvent::ConnectionEvent { connection, event } } }; Poll::Ready(event) } /// Initiates a connection attempt to a known peer. fn dial_peer(&mut self, opts: DialingOpts<TPeerId, THandler>) -> Result<ConnectionId, ConnectionLimit> where TTrans: Transport<Output = (TConnInfo, TMuxer)>, TTrans::Dial: Send + 'static, TTrans::Error: Send + 'static, TMuxer: Send + Sync + 'static, TMuxer::OutboundSubstream: Send, TInEvent: Send + 'static, TOutEvent: Send + 'static, TPeerId: Send + 'static, { dial_peer_impl(self.transport().clone(), &mut self.pool, &mut self.dialing, opts) } } /// Options for a dialing attempt (i.e. repeated connection attempt /// via a list of address) to a peer. struct DialingOpts<TPeerId, THandler> { peer: TPeerId, handler: THandler, address: Multiaddr, remaining: Vec<Multiaddr>, } /// Standalone implementation of `Network::dial_peer` for more granular borrowing. fn dial_peer_impl<TMuxer, TInEvent, TOutEvent, THandler, TTrans, TConnInfo, TPeerId>( transport: TTrans, pool: &mut Pool<TInEvent, TOutEvent, THandler, TTrans::Error, <THandler::Handler as ConnectionHandler>::Error, TConnInfo, TPeerId>, dialing: &mut FnvHashMap<TPeerId, peer::DialingAttempt>, opts: DialingOpts<TPeerId, THandler> ) -> Result<ConnectionId, ConnectionLimit> where THandler: IntoConnectionHandler<TConnInfo> + Send + 'static, <THandler::Handler as ConnectionHandler>::Error: error::Error + Send + 'static, <THandler::Handler as ConnectionHandler>::OutboundOpenInfo: Send + 'static, THandler::Handler: ConnectionHandler< Substream = Substream<TMuxer>, InEvent = TInEvent, OutEvent = TOutEvent, > + Send + 'static, TTrans: Transport<Output = (TConnInfo, TMuxer)>, TTrans::Dial: Send + 'static, TTrans::Error: error::Error + Send + 'static, TMuxer: StreamMuxer + Send + Sync + 'static, TMuxer::OutboundSubstream: Send + 'static, TInEvent: Send + 'static, TOutEvent: Send + 'static, TPeerId: Eq + Hash + Send + Clone + 'static, TConnInfo: ConnectionInfo<PeerId = TPeerId> + Send + 'static, { let result = match transport.dial(opts.address.clone()) { Ok(fut) => { let fut = fut.map_err(|e| PendingConnectionError::Transport(TransportError::Other(e))); let info = OutgoingInfo { address: &opts.address, peer_id: Some(&opts.peer) }; pool.add_outgoing(fut, opts.handler, info) }, Err(err) => { let fut = future::err(PendingConnectionError::Transport(err)); let info = OutgoingInfo { address: &opts.address, peer_id: Some(&opts.peer) }; pool.add_outgoing(fut, opts.handler, info) }, }; if let Ok(id) = &result { let former = dialing.insert(opts.peer, peer::DialingAttempt { id: *id, current: opts.address, next: opts.remaining, }, ); debug_assert!(former.is_none()); } result } /// Callback for handling a failed connection attempt, returning an /// event to emit from the `Network`. /// /// If the failed connection attempt was a dialing attempt and there /// are more addresses to try, new `DialingOpts` are returned. fn on_connection_failed<'a, TTrans, TInEvent, TOutEvent, THandler, TConnInfo, TPeerId>( dialing: &mut FnvHashMap<TPeerId, peer::DialingAttempt>, id: ConnectionId, endpoint: ConnectedPoint, error: PendingConnectionError<TTrans::Error>, handler: Option<THandler>, ) -> (Option<DialingOpts<TPeerId, THandler>>, NetworkEvent<'a, TTrans, TInEvent, TOutEvent, THandler, TConnInfo, TPeerId>) where TTrans: Transport, THandler: IntoConnectionHandler<TConnInfo>, TConnInfo: ConnectionInfo<PeerId = TPeerId> + Send + 'static, TPeerId: Eq + Hash + Clone, { // Check if the failed connection is associated with a dialing attempt. // TODO: could be more optimal than iterating over everything let dialing_peer = dialing.iter() // (1) .find(|(_, a)| a.id == id) .map(|(p, _)| p.clone()); if let Some(peer_id) = dialing_peer { // A pending outgoing connection to a known peer failed. let mut attempt = dialing.remove(&peer_id).expect("by (1)"); let num_remain = u32::try_from(attempt.next.len()).unwrap(); let failed_addr = attempt.current.clone(); let (opts, attempts_remaining) = if num_remain > 0 { if let Some(handler) = handler { let next_attempt = attempt.next.remove(0); let opts = DialingOpts { peer: peer_id.clone(), handler, address: next_attempt, remaining: attempt.next }; (Some(opts), num_remain) } else { // The error is "fatal" for the dialing attempt, since // the handler was already consumed. All potential // remaining connection attempts are thus void. (None, 0) } } else { (None, 0) }; (opts, NetworkEvent::DialError { attempts_remaining, peer_id, multiaddr: failed_addr, error, }) } else { // A pending incoming connection or outgoing connection to an unknown peer failed. match endpoint { ConnectedPoint::Dialer { address } => (None, NetworkEvent::UnknownPeerDialError { multiaddr: address, error, }), ConnectedPoint::Listener { local_addr, send_back_addr } => (None, NetworkEvent::IncomingConnectionError { local_addr, send_back_addr, error }) } } } /// Information about the network obtained by [`Network::info()`]. #[derive(Clone, Debug)] pub struct NetworkInfo { pub num_peers: usize, pub num_connections: usize, pub num_connections_pending: usize, pub num_connections_established: usize, } /// The (optional) configuration for a [`Network`]. /// /// The default configuration specifies no dedicated task executor /// and no connection limits. #[derive(Default)] pub struct NetworkConfig { executor: Option<Box<dyn Executor + Send>>, pool_limits: PoolLimits, } impl NetworkConfig { pub fn set_executor(&mut self, e: Box<dyn Executor + Send>) -> &mut Self { self.executor = Some(e); self } /// Shortcut for calling `executor` with an object that calls the given closure. pub fn set_executor_fn(mut self, f: impl Fn(Pin<Box<dyn Future<Output = ()> + Send>>) + Send + 'static) -> Self { struct SpawnImpl<F>(F); impl<F: Fn(Pin<Box<dyn Future<Output = ()> + Send>>)> Executor for SpawnImpl<F> { fn exec(&self, f: Pin<Box<dyn Future<Output = ()> + Send>>) { (self.0)(f) } } self.set_executor(Box::new(SpawnImpl(f))); self } pub fn executor(&self) -> Option<&Box<dyn Executor + Send>> { self.executor.as_ref() } pub fn set_incoming_limit(&mut self, n: usize) -> &mut Self { self.pool_limits.max_incoming = Some(n); self } pub fn set_outgoing_limit(&mut self, n: usize) -> &mut Self { self.pool_limits.max_outgoing = Some(n); self } pub fn set_established_per_peer_limit(&mut self, n: usize) -> &mut Self { self.pool_limits.max_established_per_peer = Some(n); self } }
38.012559
136
0.61068
64c570c3c7af79e0c9fec72d596c5acf0d8c3344
1,014
use ethers::{prelude::*, utils::Anvil}; use eyre::Result; use std::convert::TryFrom; #[tokio::main] async fn main() -> Result<()> { let anvil = Anvil::new().spawn(); let wallet: LocalWallet = anvil.keys()[0].clone().into(); let wallet2: LocalWallet = anvil.keys()[1].clone().into(); // connect to the network let provider = Provider::<Http>::try_from(anvil.endpoint())?; // connect the wallet to the provider let client = SignerMiddleware::new(provider, wallet); // craft the transaction let tx = TransactionRequest::new().to(wallet2.address()).value(10000); // send it! let pending_tx = client.send_transaction(tx, None).await?; // get the mined tx let receipt = pending_tx.await?.ok_or_else(|| eyre::format_err!("tx dropped from mempool"))?; let tx = client.get_transaction(receipt.transaction_hash).await?; println!("Sent tx: {}\n", serde_json::to_string(&tx)?); println!("Tx receipt: {}", serde_json::to_string(&receipt)?); Ok(()) }
30.727273
97
0.647929
4b1bdd63dd732f5117882b01dbd5e5921e8f898c
39,621
// Copyright 2012-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. #![allow(non_upper_case_globals)] use llvm; use llvm::{SequentiallyConsistent, Acquire, Release, AtomicXchg, ValueRef, TypeKind}; use middle::subst; use middle::subst::FnSpace; use trans::adt; use trans::base::*; use trans::build::*; use trans::callee; use trans::cleanup; use trans::cleanup::CleanupMethods; use trans::common::*; use trans::datum::*; use trans::debuginfo::DebugLoc; use trans::expr; use trans::glue; use trans::type_of::*; use trans::type_of; use trans::machine; use trans::machine::llsize_of; use trans::type_::Type; use middle::ty::{self, Ty}; use syntax::abi::RustIntrinsic; use syntax::ast; use syntax::parse::token; use util::ppaux::{Repr, ty_to_string}; pub fn get_simple_intrinsic(ccx: &CrateContext, item: &ast::ForeignItem) -> Option<ValueRef> { let name = match &token::get_ident(item.ident)[..] { "sqrtf32" => "llvm.sqrt.f32", "sqrtf64" => "llvm.sqrt.f64", "powif32" => "llvm.powi.f32", "powif64" => "llvm.powi.f64", "sinf32" => "llvm.sin.f32", "sinf64" => "llvm.sin.f64", "cosf32" => "llvm.cos.f32", "cosf64" => "llvm.cos.f64", "powf32" => "llvm.pow.f32", "powf64" => "llvm.pow.f64", "expf32" => "llvm.exp.f32", "expf64" => "llvm.exp.f64", "exp2f32" => "llvm.exp2.f32", "exp2f64" => "llvm.exp2.f64", "logf32" => "llvm.log.f32", "logf64" => "llvm.log.f64", "log10f32" => "llvm.log10.f32", "log10f64" => "llvm.log10.f64", "log2f32" => "llvm.log2.f32", "log2f64" => "llvm.log2.f64", "fmaf32" => "llvm.fma.f32", "fmaf64" => "llvm.fma.f64", "fabsf32" => "llvm.fabs.f32", "fabsf64" => "llvm.fabs.f64", "copysignf32" => "llvm.copysign.f32", "copysignf64" => "llvm.copysign.f64", "floorf32" => "llvm.floor.f32", "floorf64" => "llvm.floor.f64", "ceilf32" => "llvm.ceil.f32", "ceilf64" => "llvm.ceil.f64", "truncf32" => "llvm.trunc.f32", "truncf64" => "llvm.trunc.f64", "rintf32" => "llvm.rint.f32", "rintf64" => "llvm.rint.f64", "nearbyintf32" => "llvm.nearbyint.f32", "nearbyintf64" => "llvm.nearbyint.f64", "roundf32" => "llvm.round.f32", "roundf64" => "llvm.round.f64", "ctpop8" => "llvm.ctpop.i8", "ctpop16" => "llvm.ctpop.i16", "ctpop32" => "llvm.ctpop.i32", "ctpop64" => "llvm.ctpop.i64", "bswap16" => "llvm.bswap.i16", "bswap32" => "llvm.bswap.i32", "bswap64" => "llvm.bswap.i64", "assume" => "llvm.assume", _ => return None }; Some(ccx.get_intrinsic(&name)) } /// Performs late verification that intrinsics are used correctly. At present, /// the only intrinsic that needs such verification is `transmute`. pub fn check_intrinsics(ccx: &CrateContext) { let mut last_failing_id = None; for transmute_restriction in &*ccx.tcx().transmute_restrictions.borrow() { // Sometimes, a single call to transmute will push multiple // type pairs to test in order to exhaustively test the // possibility around a type parameter. If one of those fails, // there is no sense reporting errors on the others. if last_failing_id == Some(transmute_restriction.id) { continue; } debug!("transmute_restriction: {}", transmute_restriction.repr(ccx.tcx())); assert!(!ty::type_has_params(transmute_restriction.substituted_from)); assert!(!ty::type_has_params(transmute_restriction.substituted_to)); let llfromtype = type_of::sizing_type_of(ccx, transmute_restriction.substituted_from); let lltotype = type_of::sizing_type_of(ccx, transmute_restriction.substituted_to); let from_type_size = machine::llbitsize_of_real(ccx, llfromtype); let to_type_size = machine::llbitsize_of_real(ccx, lltotype); if from_type_size != to_type_size { last_failing_id = Some(transmute_restriction.id); if transmute_restriction.original_from != transmute_restriction.substituted_from { ccx.sess().span_err( transmute_restriction.span, &format!("transmute called on types with potentially different sizes: \ {} (could be {} bit{}) to {} (could be {} bit{})", ty_to_string(ccx.tcx(), transmute_restriction.original_from), from_type_size as usize, if from_type_size == 1 {""} else {"s"}, ty_to_string(ccx.tcx(), transmute_restriction.original_to), to_type_size as usize, if to_type_size == 1 {""} else {"s"})); } else { ccx.sess().span_err( transmute_restriction.span, &format!("transmute called on types with different sizes: \ {} ({} bit{}) to {} ({} bit{})", ty_to_string(ccx.tcx(), transmute_restriction.original_from), from_type_size as usize, if from_type_size == 1 {""} else {"s"}, ty_to_string(ccx.tcx(), transmute_restriction.original_to), to_type_size as usize, if to_type_size == 1 {""} else {"s"})); } } } ccx.sess().abort_if_errors(); } /// Remember to add all intrinsics here, in librustc_typeck/check/mod.rs, /// and in libcore/intrinsics.rs; if you need access to any llvm intrinsics, /// add them to librustc_trans/trans/context.rs pub fn trans_intrinsic_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, node: ast::NodeId, callee_ty: Ty<'tcx>, cleanup_scope: cleanup::CustomScopeIndex, args: callee::CallArgs<'a, 'tcx>, dest: expr::Dest, substs: subst::Substs<'tcx>, call_info: NodeIdAndSpan) -> Result<'blk, 'tcx> { let fcx = bcx.fcx; let ccx = fcx.ccx; let tcx = bcx.tcx(); let _icx = push_ctxt("trans_intrinsic_call"); let ret_ty = match callee_ty.sty { ty::ty_bare_fn(_, ref f) => { ty::erase_late_bound_regions(bcx.tcx(), &f.sig.output()) } _ => panic!("expected bare_fn in trans_intrinsic_call") }; let foreign_item = tcx.map.expect_foreign_item(node); let name = token::get_ident(foreign_item.ident); // For `transmute` we can just trans the input expr directly into dest if &name[..] == "transmute" { let llret_ty = type_of::type_of(ccx, ret_ty.unwrap()); match args { callee::ArgExprs(arg_exprs) => { assert_eq!(arg_exprs.len(), 1); let (in_type, out_type) = (*substs.types.get(FnSpace, 0), *substs.types.get(FnSpace, 1)); let llintype = type_of::type_of(ccx, in_type); let llouttype = type_of::type_of(ccx, out_type); let in_type_size = machine::llbitsize_of_real(ccx, llintype); let out_type_size = machine::llbitsize_of_real(ccx, llouttype); // This should be caught by the intrinsicck pass assert_eq!(in_type_size, out_type_size); let nonpointer_nonaggregate = |llkind: TypeKind| -> bool { use llvm::TypeKind::*; match llkind { Half | Float | Double | X86_FP80 | FP128 | PPC_FP128 | Integer | Vector | X86_MMX => true, _ => false } }; // An approximation to which types can be directly cast via // LLVM's bitcast. This doesn't cover pointer -> pointer casts, // but does, importantly, cover SIMD types. let in_kind = llintype.kind(); let ret_kind = llret_ty.kind(); let bitcast_compatible = (nonpointer_nonaggregate(in_kind) && nonpointer_nonaggregate(ret_kind)) || { in_kind == TypeKind::Pointer && ret_kind == TypeKind::Pointer }; let dest = if bitcast_compatible { // if we're here, the type is scalar-like (a primitive, a // SIMD type or a pointer), and so can be handled as a // by-value ValueRef and can also be directly bitcast to the // target type. Doing this special case makes conversions // like `u32x4` -> `u64x2` much nicer for LLVM and so more // efficient (these are done efficiently implicitly in C // with the `__m128i` type and so this means Rust doesn't // lose out there). let expr = &*arg_exprs[0]; let datum = unpack_datum!(bcx, expr::trans(bcx, expr)); let datum = unpack_datum!(bcx, datum.to_rvalue_datum(bcx, "transmute_temp")); let val = if datum.kind.is_by_ref() { load_ty(bcx, datum.val, datum.ty) } else { datum.val }; let cast_val = BitCast(bcx, val, llret_ty); match dest { expr::SaveIn(d) => { // this often occurs in a sequence like `Store(val, // d); val2 = Load(d)`, so disappears easily. Store(bcx, cast_val, d); } expr::Ignore => {} } dest } else { // The types are too complicated to do with a by-value // bitcast, so pointer cast instead. We need to cast the // dest so the types work out. let dest = match dest { expr::SaveIn(d) => expr::SaveIn(PointerCast(bcx, d, llintype.ptr_to())), expr::Ignore => expr::Ignore }; bcx = expr::trans_into(bcx, &*arg_exprs[0], dest); dest }; fcx.scopes.borrow_mut().last_mut().unwrap().drop_non_lifetime_clean(); fcx.pop_and_trans_custom_cleanup_scope(bcx, cleanup_scope); return match dest { expr::SaveIn(d) => Result::new(bcx, d), expr::Ignore => Result::new(bcx, C_undef(llret_ty.ptr_to())) }; } _ => { ccx.sess().bug("expected expr as argument for transmute"); } } } // Push the arguments. let mut llargs = Vec::new(); bcx = callee::trans_args(bcx, args, callee_ty, &mut llargs, cleanup::CustomScope(cleanup_scope), false, RustIntrinsic); fcx.scopes.borrow_mut().last_mut().unwrap().drop_non_lifetime_clean(); let call_debug_location = DebugLoc::At(call_info.id, call_info.span); // These are the only intrinsic functions that diverge. if &name[..] == "abort" { let llfn = ccx.get_intrinsic(&("llvm.trap")); Call(bcx, llfn, &[], None, call_debug_location); fcx.pop_and_trans_custom_cleanup_scope(bcx, cleanup_scope); Unreachable(bcx); return Result::new(bcx, C_undef(Type::nil(ccx).ptr_to())); } else if &name[..] == "unreachable" { fcx.pop_and_trans_custom_cleanup_scope(bcx, cleanup_scope); Unreachable(bcx); return Result::new(bcx, C_nil(ccx)); } let ret_ty = match ret_ty { ty::FnConverging(ret_ty) => ret_ty, ty::FnDiverging => unreachable!() }; let llret_ty = type_of::type_of(ccx, ret_ty); // Get location to store the result. If the user does // not care about the result, just make a stack slot let llresult = match dest { expr::SaveIn(d) => d, expr::Ignore => { if !type_is_zero_size(ccx, ret_ty) { alloc_ty(bcx, ret_ty, "intrinsic_result") } else { C_undef(llret_ty.ptr_to()) } } }; let simple = get_simple_intrinsic(ccx, &*foreign_item); let llval = match (simple, &name[..]) { (Some(llfn), _) => { Call(bcx, llfn, &llargs, None, call_debug_location) } (_, "breakpoint") => { let llfn = ccx.get_intrinsic(&("llvm.debugtrap")); Call(bcx, llfn, &[], None, call_debug_location) } (_, "size_of") => { let tp_ty = *substs.types.get(FnSpace, 0); let lltp_ty = type_of::type_of(ccx, tp_ty); C_uint(ccx, machine::llsize_of_alloc(ccx, lltp_ty)) } (_, "min_align_of") => { let tp_ty = *substs.types.get(FnSpace, 0); C_uint(ccx, type_of::align_of(ccx, tp_ty)) } (_, "pref_align_of") => { let tp_ty = *substs.types.get(FnSpace, 0); let lltp_ty = type_of::type_of(ccx, tp_ty); C_uint(ccx, machine::llalign_of_pref(ccx, lltp_ty)) } (_, "move_val_init") => { // Create a datum reflecting the value being moved. // Use `appropriate_mode` so that the datum is by ref // if the value is non-immediate. Note that, with // intrinsics, there are no argument cleanups to // concern ourselves with, so we can use an rvalue datum. let tp_ty = *substs.types.get(FnSpace, 0); let mode = appropriate_rvalue_mode(ccx, tp_ty); let src = Datum { val: llargs[1], ty: tp_ty, kind: Rvalue::new(mode) }; bcx = src.store_to(bcx, llargs[0]); C_nil(ccx) } (_, "type_name") => { let tp_ty = *substs.types.get(FnSpace, 0); let ty_name = token::intern_and_get_ident(&ty_to_string(ccx.tcx(), tp_ty)); C_str_slice(ccx, ty_name) } (_, "type_id") => { let hash = ty::hash_crate_independent( ccx.tcx(), *substs.types.get(FnSpace, 0), &ccx.link_meta().crate_hash); C_u64(ccx, hash) } (_, "init_dropped") => { let tp_ty = *substs.types.get(FnSpace, 0); if !return_type_is_void(ccx, tp_ty) { drop_done_fill_mem(bcx, llresult, tp_ty); } C_nil(ccx) } (_, "init") => { let tp_ty = *substs.types.get(FnSpace, 0); if !return_type_is_void(ccx, tp_ty) { // Just zero out the stack slot. (See comment on base::memzero for explanation) init_zero_mem(bcx, llresult, tp_ty); } C_nil(ccx) } // Effectively no-ops (_, "uninit") | (_, "forget") => { C_nil(ccx) } (_, "needs_drop") => { let tp_ty = *substs.types.get(FnSpace, 0); C_bool(ccx, bcx.fcx.type_needs_drop(tp_ty)) } (_, "offset") => { let ptr = llargs[0]; let offset = llargs[1]; InBoundsGEP(bcx, ptr, &[offset]) } (_, "copy_nonoverlapping") => { copy_intrinsic(bcx, false, false, *substs.types.get(FnSpace, 0), llargs[1], llargs[0], llargs[2], call_debug_location) } (_, "copy") => { copy_intrinsic(bcx, true, false, *substs.types.get(FnSpace, 0), llargs[1], llargs[0], llargs[2], call_debug_location) } (_, "write_bytes") => { memset_intrinsic(bcx, false, *substs.types.get(FnSpace, 0), llargs[0], llargs[1], llargs[2], call_debug_location) } (_, "volatile_copy_nonoverlapping_memory") => { copy_intrinsic(bcx, false, true, *substs.types.get(FnSpace, 0), llargs[0], llargs[1], llargs[2], call_debug_location) } (_, "volatile_copy_memory") => { copy_intrinsic(bcx, true, true, *substs.types.get(FnSpace, 0), llargs[0], llargs[1], llargs[2], call_debug_location) } (_, "volatile_set_memory") => { memset_intrinsic(bcx, true, *substs.types.get(FnSpace, 0), llargs[0], llargs[1], llargs[2], call_debug_location) } (_, "volatile_load") => { let tp_ty = *substs.types.get(FnSpace, 0); let ptr = to_arg_ty_ptr(bcx, llargs[0], tp_ty); let load = VolatileLoad(bcx, ptr); unsafe { llvm::LLVMSetAlignment(load, type_of::align_of(ccx, tp_ty)); } from_arg_ty(bcx, load, tp_ty) }, (_, "volatile_store") => { let tp_ty = *substs.types.get(FnSpace, 0); let ptr = to_arg_ty_ptr(bcx, llargs[0], tp_ty); let val = to_arg_ty(bcx, llargs[1], tp_ty); let store = VolatileStore(bcx, val, ptr); unsafe { llvm::LLVMSetAlignment(store, type_of::align_of(ccx, tp_ty)); } C_nil(ccx) }, (_, "ctlz8") => count_zeros_intrinsic(bcx, "llvm.ctlz.i8", llargs[0], call_debug_location), (_, "ctlz16") => count_zeros_intrinsic(bcx, "llvm.ctlz.i16", llargs[0], call_debug_location), (_, "ctlz32") => count_zeros_intrinsic(bcx, "llvm.ctlz.i32", llargs[0], call_debug_location), (_, "ctlz64") => count_zeros_intrinsic(bcx, "llvm.ctlz.i64", llargs[0], call_debug_location), (_, "cttz8") => count_zeros_intrinsic(bcx, "llvm.cttz.i8", llargs[0], call_debug_location), (_, "cttz16") => count_zeros_intrinsic(bcx, "llvm.cttz.i16", llargs[0], call_debug_location), (_, "cttz32") => count_zeros_intrinsic(bcx, "llvm.cttz.i32", llargs[0], call_debug_location), (_, "cttz64") => count_zeros_intrinsic(bcx, "llvm.cttz.i64", llargs[0], call_debug_location), (_, "i8_add_with_overflow") => with_overflow_intrinsic(bcx, "llvm.sadd.with.overflow.i8", ret_ty, llargs[0], llargs[1], call_debug_location), (_, "i16_add_with_overflow") => with_overflow_intrinsic(bcx, "llvm.sadd.with.overflow.i16", ret_ty, llargs[0], llargs[1], call_debug_location), (_, "i32_add_with_overflow") => with_overflow_intrinsic(bcx, "llvm.sadd.with.overflow.i32", ret_ty, llargs[0], llargs[1], call_debug_location), (_, "i64_add_with_overflow") => with_overflow_intrinsic(bcx, "llvm.sadd.with.overflow.i64", ret_ty, llargs[0], llargs[1], call_debug_location), (_, "u8_add_with_overflow") => with_overflow_intrinsic(bcx, "llvm.uadd.with.overflow.i8", ret_ty, llargs[0], llargs[1], call_debug_location), (_, "u16_add_with_overflow") => with_overflow_intrinsic(bcx, "llvm.uadd.with.overflow.i16", ret_ty, llargs[0], llargs[1], call_debug_location), (_, "u32_add_with_overflow") => with_overflow_intrinsic(bcx, "llvm.uadd.with.overflow.i32", ret_ty, llargs[0], llargs[1], call_debug_location), (_, "u64_add_with_overflow") => with_overflow_intrinsic(bcx, "llvm.uadd.with.overflow.i64", ret_ty, llargs[0], llargs[1], call_debug_location), (_, "i8_sub_with_overflow") => with_overflow_intrinsic(bcx, "llvm.ssub.with.overflow.i8", ret_ty, llargs[0], llargs[1], call_debug_location), (_, "i16_sub_with_overflow") => with_overflow_intrinsic(bcx, "llvm.ssub.with.overflow.i16", ret_ty, llargs[0], llargs[1], call_debug_location), (_, "i32_sub_with_overflow") => with_overflow_intrinsic(bcx, "llvm.ssub.with.overflow.i32", ret_ty, llargs[0], llargs[1], call_debug_location), (_, "i64_sub_with_overflow") => with_overflow_intrinsic(bcx, "llvm.ssub.with.overflow.i64", ret_ty, llargs[0], llargs[1], call_debug_location), (_, "u8_sub_with_overflow") => with_overflow_intrinsic(bcx, "llvm.usub.with.overflow.i8", ret_ty, llargs[0], llargs[1], call_debug_location), (_, "u16_sub_with_overflow") => with_overflow_intrinsic(bcx, "llvm.usub.with.overflow.i16", ret_ty, llargs[0], llargs[1], call_debug_location), (_, "u32_sub_with_overflow") => with_overflow_intrinsic(bcx, "llvm.usub.with.overflow.i32", ret_ty, llargs[0], llargs[1], call_debug_location), (_, "u64_sub_with_overflow") => with_overflow_intrinsic(bcx, "llvm.usub.with.overflow.i64", ret_ty, llargs[0], llargs[1], call_debug_location), (_, "i8_mul_with_overflow") => with_overflow_intrinsic(bcx, "llvm.smul.with.overflow.i8", ret_ty, llargs[0], llargs[1], call_debug_location), (_, "i16_mul_with_overflow") => with_overflow_intrinsic(bcx, "llvm.smul.with.overflow.i16", ret_ty, llargs[0], llargs[1], call_debug_location), (_, "i32_mul_with_overflow") => with_overflow_intrinsic(bcx, "llvm.smul.with.overflow.i32", ret_ty, llargs[0], llargs[1], call_debug_location), (_, "i64_mul_with_overflow") => with_overflow_intrinsic(bcx, "llvm.smul.with.overflow.i64", ret_ty, llargs[0], llargs[1], call_debug_location), (_, "u8_mul_with_overflow") => with_overflow_intrinsic(bcx, "llvm.umul.with.overflow.i8", ret_ty, llargs[0], llargs[1], call_debug_location), (_, "u16_mul_with_overflow") => with_overflow_intrinsic(bcx, "llvm.umul.with.overflow.i16", ret_ty, llargs[0], llargs[1], call_debug_location), (_, "u32_mul_with_overflow") => with_overflow_intrinsic(bcx, "llvm.umul.with.overflow.i32", ret_ty, llargs[0], llargs[1], call_debug_location), (_, "u64_mul_with_overflow") => with_overflow_intrinsic(bcx, "llvm.umul.with.overflow.i64", ret_ty, llargs[0], llargs[1], call_debug_location), (_, "unchecked_udiv") => UDiv(bcx, llargs[0], llargs[1], call_debug_location), (_, "unchecked_sdiv") => SDiv(bcx, llargs[0], llargs[1], call_debug_location), (_, "unchecked_urem") => URem(bcx, llargs[0], llargs[1], call_debug_location), (_, "unchecked_srem") => SRem(bcx, llargs[0], llargs[1], call_debug_location), (_, "overflowing_add") => Add(bcx, llargs[0], llargs[1], call_debug_location), (_, "overflowing_sub") => Sub(bcx, llargs[0], llargs[1], call_debug_location), (_, "overflowing_mul") => Mul(bcx, llargs[0], llargs[1], call_debug_location), (_, "return_address") => { if !fcx.caller_expects_out_pointer { tcx.sess.span_err(call_info.span, "invalid use of `return_address` intrinsic: function \ does not use out pointer"); C_null(Type::i8p(ccx)) } else { PointerCast(bcx, llvm::get_param(fcx.llfn, 0), Type::i8p(ccx)) } } (_, "discriminant_value") => { let val_ty = substs.types.get(FnSpace, 0); match val_ty.sty { ty::ty_enum(..) => { let repr = adt::represent_type(ccx, *val_ty); adt::trans_get_discr(bcx, &*repr, llargs[0], Some(llret_ty)) } _ => C_null(llret_ty) } } // This requires that atomic intrinsics follow a specific naming pattern: // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst (_, name) if name.starts_with("atomic_") => { let split: Vec<&str> = name.split('_').collect(); assert!(split.len() >= 2, "Atomic intrinsic not correct format"); let order = if split.len() == 2 { llvm::SequentiallyConsistent } else { match split[2] { "unordered" => llvm::Unordered, "relaxed" => llvm::Monotonic, "acq" => llvm::Acquire, "rel" => llvm::Release, "acqrel" => llvm::AcquireRelease, _ => ccx.sess().fatal("unknown ordering in atomic intrinsic") } }; match split[1] { "cxchg" => { // See include/llvm/IR/Instructions.h for their implementation // of this, I assume that it's good enough for us to use for // now. let strongest_failure_ordering = match order { llvm::NotAtomic | llvm::Unordered => ccx.sess().fatal("cmpxchg must be atomic"), llvm::Monotonic | llvm::Release => llvm::Monotonic, llvm::Acquire | llvm::AcquireRelease => llvm::Acquire, llvm::SequentiallyConsistent => llvm::SequentiallyConsistent }; let tp_ty = *substs.types.get(FnSpace, 0); let ptr = to_arg_ty_ptr(bcx, llargs[0], tp_ty); let cmp = to_arg_ty(bcx, llargs[1], tp_ty); let src = to_arg_ty(bcx, llargs[2], tp_ty); let res = AtomicCmpXchg(bcx, ptr, cmp, src, order, strongest_failure_ordering); ExtractValue(bcx, res, 0) } "load" => { let tp_ty = *substs.types.get(FnSpace, 0); let ptr = to_arg_ty_ptr(bcx, llargs[0], tp_ty); from_arg_ty(bcx, AtomicLoad(bcx, ptr, order), tp_ty) } "store" => { let tp_ty = *substs.types.get(FnSpace, 0); let ptr = to_arg_ty_ptr(bcx, llargs[0], tp_ty); let val = to_arg_ty(bcx, llargs[1], tp_ty); AtomicStore(bcx, val, ptr, order); C_nil(ccx) } "fence" => { AtomicFence(bcx, order, llvm::CrossThread); C_nil(ccx) } "singlethreadfence" => { AtomicFence(bcx, order, llvm::SingleThread); C_nil(ccx) } // These are all AtomicRMW ops op => { let atom_op = match op { "xchg" => llvm::AtomicXchg, "xadd" => llvm::AtomicAdd, "xsub" => llvm::AtomicSub, "and" => llvm::AtomicAnd, "nand" => llvm::AtomicNand, "or" => llvm::AtomicOr, "xor" => llvm::AtomicXor, "max" => llvm::AtomicMax, "min" => llvm::AtomicMin, "umax" => llvm::AtomicUMax, "umin" => llvm::AtomicUMin, _ => ccx.sess().fatal("unknown atomic operation") }; let tp_ty = *substs.types.get(FnSpace, 0); let ptr = to_arg_ty_ptr(bcx, llargs[0], tp_ty); let val = to_arg_ty(bcx, llargs[1], tp_ty); AtomicRMW(bcx, atom_op, ptr, val, order) } } } (_, _) => ccx.sess().span_bug(foreign_item.span, "unknown intrinsic") }; if val_ty(llval) != Type::void(ccx) && machine::llsize_of_alloc(ccx, val_ty(llval)) != 0 { store_ty(bcx, llval, llresult, ret_ty); } // If we made a temporary stack slot, let's clean it up match dest { expr::Ignore => { bcx = glue::drop_ty(bcx, llresult, ret_ty, call_debug_location); } expr::SaveIn(_) => {} } fcx.pop_and_trans_custom_cleanup_scope(bcx, cleanup_scope); Result::new(bcx, llresult) } fn copy_intrinsic<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, allow_overlap: bool, volatile: bool, tp_ty: Ty<'tcx>, dst: ValueRef, src: ValueRef, count: ValueRef, call_debug_location: DebugLoc) -> ValueRef { let ccx = bcx.ccx(); let lltp_ty = type_of::type_of(ccx, tp_ty); let align = C_i32(ccx, type_of::align_of(ccx, tp_ty) as i32); let size = machine::llsize_of(ccx, lltp_ty); let int_size = machine::llbitsize_of_real(ccx, ccx.int_type()); let name = if allow_overlap { if int_size == 32 { "llvm.memmove.p0i8.p0i8.i32" } else { "llvm.memmove.p0i8.p0i8.i64" } } else { if int_size == 32 { "llvm.memcpy.p0i8.p0i8.i32" } else { "llvm.memcpy.p0i8.p0i8.i64" } }; let dst_ptr = PointerCast(bcx, dst, Type::i8p(ccx)); let src_ptr = PointerCast(bcx, src, Type::i8p(ccx)); let llfn = ccx.get_intrinsic(&name); Call(bcx, llfn, &[dst_ptr, src_ptr, Mul(bcx, size, count, DebugLoc::None), align, C_bool(ccx, volatile)], None, call_debug_location) } fn memset_intrinsic<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, volatile: bool, tp_ty: Ty<'tcx>, dst: ValueRef, val: ValueRef, count: ValueRef, call_debug_location: DebugLoc) -> ValueRef { let ccx = bcx.ccx(); let lltp_ty = type_of::type_of(ccx, tp_ty); let align = C_i32(ccx, type_of::align_of(ccx, tp_ty) as i32); let size = machine::llsize_of(ccx, lltp_ty); let name = if machine::llbitsize_of_real(ccx, ccx.int_type()) == 32 { "llvm.memset.p0i8.i32" } else { "llvm.memset.p0i8.i64" }; let dst_ptr = PointerCast(bcx, dst, Type::i8p(ccx)); let llfn = ccx.get_intrinsic(&name); Call(bcx, llfn, &[dst_ptr, val, Mul(bcx, size, count, DebugLoc::None), align, C_bool(ccx, volatile)], None, call_debug_location) } fn count_zeros_intrinsic(bcx: Block, name: &'static str, val: ValueRef, call_debug_location: DebugLoc) -> ValueRef { let y = C_bool(bcx.ccx(), false); let llfn = bcx.ccx().get_intrinsic(&name); Call(bcx, llfn, &[val, y], None, call_debug_location) } fn with_overflow_intrinsic<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, name: &'static str, t: Ty<'tcx>, a: ValueRef, b: ValueRef, call_debug_location: DebugLoc) -> ValueRef { let llfn = bcx.ccx().get_intrinsic(&name); // Convert `i1` to a `bool`, and write it to the out parameter let val = Call(bcx, llfn, &[a, b], None, call_debug_location); let result = ExtractValue(bcx, val, 0); let overflow = ZExt(bcx, ExtractValue(bcx, val, 1), Type::bool(bcx.ccx())); let ret = C_undef(type_of::type_of(bcx.ccx(), t)); let ret = InsertValue(bcx, ret, result, 0); let ret = InsertValue(bcx, ret, overflow, 1); if type_is_immediate(bcx.ccx(), t) { let tmp = alloc_ty(bcx, t, "tmp"); Store(bcx, ret, tmp); load_ty(bcx, tmp, t) } else { ret } }
42.375401
97
0.437975
1a8f004cb088612183d9bac9e9b63dee9d7bda58
1,546
use crate::Type; use blake2::Digest; macro_rules! hash_type { ($x: ident) => { #[derive(Debug, Clone, PartialEq)] pub struct $x(pub Vec<u8>); impl AsRef<[u8]> for $x { fn as_ref(&self) -> &[u8] { self.0.as_ref() } } impl Type for $x { fn encode_bin<W: std::io::Write>(&self, w: &mut W) -> std::io::Result<usize> { w.write_all(&self.0)?; Ok(Self::size()) } fn decode_bin<R: std::io::Read>(r: &mut R) -> std::io::Result<Self> { let mut data = vec![0u8; Self::size()]; r.read_exact(data.as_mut_slice())?; Ok($x(data)) } } }; } hash_type!(Blake2b); hash_type!(Sha1); pub trait Hash: Type + Clone + Sized + PartialEq { fn size() -> usize; fn name() -> &'static str; fn hash(x: impl AsRef<[u8]>) -> Self; } impl Hash for Blake2b { fn size() -> usize { 64 } fn name() -> &'static str { "blake2b" } fn hash(s: impl AsRef<[u8]>) -> Self { let digest = blake2::Blake2b::digest(s.as_ref()); Blake2b(digest.as_slice().to_vec()) } } impl Hash for Sha1 { fn size() -> usize { 20 } fn name() -> &'static str { "sha1" } fn hash(s: impl AsRef<[u8]>) -> Self { let mut hash = sha1::Sha1::default(); hash.update(s.as_ref()); let digest = hash.digest(); Sha1(digest.bytes().to_vec()) } }
21.472222
90
0.466365
87fdb451aa0121e948f7acc74d491af7d327b84b
1,310
use solana_program::program_error::ProgramError; use std::convert::TryInto; use crate::error::CustomError::InvalidInstruction; pub enum TokenSaleInstruction { InitTokenSale { swap_sol_amount: u64, swap_token_amount: u64, }, BuyToken {}, EndTokenSale {} } //function of enum impl TokenSaleInstruction { pub fn unpack(input: &[u8]) -> Result<Self, ProgramError> { //check instruction type let (tag, rest) = input.split_first().ok_or(InvalidInstruction)?; //unpack the rest data for each instruction return match tag { 0 => Ok(Self::InitTokenSale { swap_sol_amount: Self::unpack_byte(rest, 0)?, swap_token_amount: Self::unpack_byte(rest, 1)?, }), 1 => Ok(Self::BuyToken {}), 2 => Ok(Self::EndTokenSale {}), _ => Err(InvalidInstruction.into()), }; } fn unpack_byte(input: &[u8], byte_index: usize) -> Result<u64, ProgramError> { let start_bit = byte_index * 8; let end_bit = start_bit + 8; let data = input .get(start_bit..end_bit) .and_then(|slice| slice.try_into().ok()) .map(u64::from_le_bytes) .ok_or(InvalidInstruction)?; return Ok(data); } }
29.111111
82
0.581679
4b28b3e82bcaec3d116c97cddd3aedc6fad7a716
1,179
#[doc = "Reader of register DAR0"] pub type R = crate::R<u32, super::DAR0>; #[doc = "Writer for register DAR0"] pub type W = crate::W<u32, super::DAR0>; #[doc = "Register DAR0 `reset()`'s with value 0"] impl crate::ResetValue for super::DAR0 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `DAR`"] pub type DAR_R = crate::R<u32, u32>; #[doc = "Write proxy for field `DAR`"] pub struct DAR_W<'a> { w: &'a mut W, } impl<'a> DAR_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u32) -> &'a mut W { self.w.bits = (self.w.bits & !0xffff_ffff) | ((value as u32) & 0xffff_ffff); self.w } } impl R { #[doc = "Bits 0:31 - Each DAR contains the byte address used by the DMA controller to write data"] #[inline(always)] pub fn dar(&self) -> DAR_R { DAR_R::new((self.bits & 0xffff_ffff) as u32) } } impl W { #[doc = "Bits 0:31 - Each DAR contains the byte address used by the DMA controller to write data"] #[inline(always)] pub fn dar(&mut self) -> DAR_W { DAR_W { w: self } } }
28.756098
102
0.583545
08ab8b9b533f437af27baaba3b246cb99403ebf1
161
#[cfg_attr(crux, crux_test)] fn crux_test() -> bool { let s = format!("a{}c", 'β'); &s == "aβc" } pub fn main() { println!("{:?}", crux_test()); }
14.636364
34
0.484472
c100e0f4b368e3928cc076582e0a376a3953348b
295,608
/// Represents a hardware accelerator type. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum AcceleratorType { /// Unspecified accelerator type, which means no accelerator. Unspecified = 0, /// Nvidia Tesla K80 GPU. NvidiaTeslaK80 = 1, /// Nvidia Tesla P100 GPU. NvidiaTeslaP100 = 2, /// Nvidia Tesla V100 GPU. NvidiaTeslaV100 = 3, /// Nvidia Tesla P4 GPU. NvidiaTeslaP4 = 4, /// Nvidia Tesla T4 GPU. NvidiaTeslaT4 = 5, /// TPU v2. TpuV2 = 6, /// TPU v3. TpuV3 = 7, } /// References an API call. It contains more information about long running /// operation and Jobs that are triggered by the API call. #[derive(Clone, PartialEq, ::prost::Message)] pub struct UserActionReference { /// The method name of the API call. For example, /// "/google.cloud.aiplatform.v1alpha1.DatasetService.CreateDataset" #[prost(string, tag = "3")] pub method: ::prost::alloc::string::String, #[prost(oneof = "user_action_reference::Reference", tags = "1, 2")] pub reference: ::core::option::Option<user_action_reference::Reference>, } /// Nested message and enum types in `UserActionReference`. pub mod user_action_reference { #[derive(Clone, PartialEq, ::prost::Oneof)] pub enum Reference { /// For API calls that return a long running operation. /// Resource name of the long running operation. /// Format: /// 'projects/{project}/locations/{location}/operations/{operation}' #[prost(string, tag = "1")] Operation(::prost::alloc::string::String), /// For API calls that start a LabelingJob. /// Resource name of the LabelingJob. /// Format: /// /// 'projects/{project}/locations/{location}/dataLabelingJobs/{data_labeling_job}' #[prost(string, tag = "2")] DataLabelingJob(::prost::alloc::string::String), } } /// Used to assign specific AnnotationSpec to a particular area of a DataItem or /// the whole part of the DataItem. #[derive(Clone, PartialEq, ::prost::Message)] pub struct Annotation { /// Output only. Resource name of the Annotation. #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, /// Required. Google Cloud Storage URI points to a YAML file describing [payload][google.cloud.aiplatform.v1.Annotation.payload]. The /// schema is defined as an /// [OpenAPI 3.0.2 Schema Object](https://tinyurl.com/y538mdwt). /// The schema files that can be used here are found in /// gs://google-cloud-aiplatform/schema/dataset/annotation/, note that the /// chosen schema must be consistent with the parent Dataset's /// [metadata][google.cloud.aiplatform.v1.Dataset.metadata_schema_uri]. #[prost(string, tag = "2")] pub payload_schema_uri: ::prost::alloc::string::String, /// Required. The schema of the payload can be found in /// [payload_schema][google.cloud.aiplatform.v1.Annotation.payload_schema_uri]. #[prost(message, optional, tag = "3")] pub payload: ::core::option::Option<::prost_types::Value>, /// Output only. Timestamp when this Annotation was created. #[prost(message, optional, tag = "4")] pub create_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. Timestamp when this Annotation was last updated. #[prost(message, optional, tag = "7")] pub update_time: ::core::option::Option<::prost_types::Timestamp>, /// Optional. Used to perform consistent read-modify-write updates. If not set, a blind /// "overwrite" update happens. #[prost(string, tag = "8")] pub etag: ::prost::alloc::string::String, /// Output only. The source of the Annotation. #[prost(message, optional, tag = "5")] pub annotation_source: ::core::option::Option<UserActionReference>, /// Optional. The labels with user-defined metadata to organize your Annotations. /// /// Label keys and values can be no longer than 64 characters /// (Unicode codepoints), can only contain lowercase letters, numeric /// characters, underscores and dashes. International characters are allowed. /// No more than 64 user labels can be associated with one Annotation(System /// labels are excluded). /// /// See https://goo.gl/xmQnxf for more information and examples of labels. /// System reserved label keys are prefixed with "aiplatform.googleapis.com/" /// and are immutable. Following system labels exist for each Annotation: /// /// * "aiplatform.googleapis.com/annotation_set_name": /// optional, name of the UI's annotation set this Annotation belongs to. /// If not set, the Annotation is not visible in the UI. /// /// * "aiplatform.googleapis.com/payload_schema": /// output only, its value is the [payload_schema's][google.cloud.aiplatform.v1.Annotation.payload_schema_uri] /// title. #[prost(map = "string, string", tag = "6")] pub labels: ::std::collections::HashMap<::prost::alloc::string::String, ::prost::alloc::string::String>, } /// Identifies a concept with which DataItems may be annotated with. #[derive(Clone, PartialEq, ::prost::Message)] pub struct AnnotationSpec { /// Output only. Resource name of the AnnotationSpec. #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, /// Required. The user-defined name of the AnnotationSpec. /// The name can be up to 128 characters long and can be consist of any UTF-8 /// characters. #[prost(string, tag = "2")] pub display_name: ::prost::alloc::string::String, /// Output only. Timestamp when this AnnotationSpec was created. #[prost(message, optional, tag = "3")] pub create_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. Timestamp when AnnotationSpec was last updated. #[prost(message, optional, tag = "4")] pub update_time: ::core::option::Option<::prost_types::Timestamp>, /// Optional. Used to perform consistent read-modify-write updates. If not set, a blind /// "overwrite" update happens. #[prost(string, tag = "5")] pub etag: ::prost::alloc::string::String, } /// Success and error statistics of processing multiple entities /// (for example, DataItems or structured data rows) in batch. #[derive(Clone, PartialEq, ::prost::Message)] pub struct CompletionStats { /// Output only. The number of entities that had been processed successfully. #[prost(int64, tag = "1")] pub successful_count: i64, /// Output only. The number of entities for which any error was encountered. #[prost(int64, tag = "2")] pub failed_count: i64, /// Output only. In cases when enough errors are encountered a job, pipeline, or operation /// may be failed as a whole. Below is the number of entities for which the /// processing had not been finished (either in successful or failed state). /// Set to -1 if the number is unknown (for example, the operation failed /// before the total entity number could be collected). #[prost(int64, tag = "3")] pub incomplete_count: i64, } /// Represents a customer-managed encryption key spec that can be applied to /// a top-level resource. #[derive(Clone, PartialEq, ::prost::Message)] pub struct EncryptionSpec { /// Required. The Cloud KMS resource identifier of the customer managed encryption key /// used to protect a resource. Has the form: /// `projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key`. /// The key needs to be in the same region as where the compute resource is /// created. #[prost(string, tag = "1")] pub kms_key_name: ::prost::alloc::string::String, } /// The Google Cloud Storage location for the input content. #[derive(Clone, PartialEq, ::prost::Message)] pub struct GcsSource { /// Required. Google Cloud Storage URI(-s) to the input file(s). May contain /// wildcards. For more information on wildcards, see /// https://cloud.google.com/storage/docs/gsutil/addlhelp/WildcardNames. #[prost(string, repeated, tag = "1")] pub uris: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, } /// The Google Cloud Storage location where the output is to be written to. #[derive(Clone, PartialEq, ::prost::Message)] pub struct GcsDestination { /// Required. Google Cloud Storage URI to output directory. If the uri doesn't end with /// '/', a '/' will be automatically appended. The directory is created if it /// doesn't exist. #[prost(string, tag = "1")] pub output_uri_prefix: ::prost::alloc::string::String, } /// The BigQuery location for the input content. #[derive(Clone, PartialEq, ::prost::Message)] pub struct BigQuerySource { /// Required. BigQuery URI to a table, up to 2000 characters long. /// Accepted forms: /// /// * BigQuery path. For example: `bq://projectId.bqDatasetId.bqTableId`. #[prost(string, tag = "1")] pub input_uri: ::prost::alloc::string::String, } /// The BigQuery location for the output content. #[derive(Clone, PartialEq, ::prost::Message)] pub struct BigQueryDestination { /// Required. BigQuery URI to a project or table, up to 2000 characters long. /// /// When only the project is specified, the Dataset and Table are created. /// When the full table reference is specified, the Dataset must exist and table must /// not exist. /// /// Accepted forms: /// /// * BigQuery path. For example: /// `bq://projectId` or `bq://projectId.bqDatasetId.bqTableId`. #[prost(string, tag = "1")] pub output_uri: ::prost::alloc::string::String, } /// The Container Registry location for the container image. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ContainerRegistryDestination { /// Required. Container Registry URI of a container image. /// Only Google Container Registry and Artifact Registry are supported now. /// Accepted forms: /// /// * Google Container Registry path. For example: /// `gcr.io/projectId/imageName:tag`. /// /// * Artifact Registry path. For example: /// `us-central1-docker.pkg.dev/projectId/repoName/imageName:tag`. /// /// If a tag is not specified, "latest" will be used as the default tag. #[prost(string, tag = "1")] pub output_uri: ::prost::alloc::string::String, } /// Describes the state of a job. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum JobState { /// The job state is unspecified. Unspecified = 0, /// The job has been just created or resumed and processing has not yet begun. Queued = 1, /// The service is preparing to run the job. Pending = 2, /// The job is in progress. Running = 3, /// The job completed successfully. Succeeded = 4, /// The job failed. Failed = 5, /// The job is being cancelled. From this state the job may only go to /// either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. Cancelling = 6, /// The job has been cancelled. Cancelled = 7, /// The job has been stopped, and can be resumed. Paused = 8, } /// Specification of a single machine. #[derive(Clone, PartialEq, ::prost::Message)] pub struct MachineSpec { /// Immutable. The type of the machine. For the machine types supported for prediction, /// see https://tinyurl.com/aip-docs/predictions/machine-types. /// For machine types supported for creating a custom training job, see /// https://tinyurl.com/aip-docs/training/configure-compute. /// /// For [DeployedModel][google.cloud.aiplatform.v1.DeployedModel] this field is optional, and the default /// value is `n1-standard-2`. For [BatchPredictionJob][google.cloud.aiplatform.v1.BatchPredictionJob] or as part of /// [WorkerPoolSpec][google.cloud.aiplatform.v1.WorkerPoolSpec] this field is required. #[prost(string, tag = "1")] pub machine_type: ::prost::alloc::string::String, /// Immutable. The type of accelerator(s) that may be attached to the machine as per /// [accelerator_count][google.cloud.aiplatform.v1.MachineSpec.accelerator_count]. #[prost(enumeration = "AcceleratorType", tag = "2")] pub accelerator_type: i32, /// The number of accelerators to attach to the machine. #[prost(int32, tag = "3")] pub accelerator_count: i32, } /// A description of resources that are dedicated to a DeployedModel, and /// that need a higher degree of manual configuration. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DedicatedResources { /// Required. Immutable. The specification of a single machine used by the prediction. #[prost(message, optional, tag = "1")] pub machine_spec: ::core::option::Option<MachineSpec>, /// Required. Immutable. The minimum number of machine replicas this DeployedModel will be always /// deployed on. If traffic against it increases, it may dynamically be /// deployed onto more replicas, and as traffic decreases, some of these extra /// replicas may be freed. /// Note: if [machine_spec.accelerator_count][google.cloud.aiplatform.v1.MachineSpec.accelerator_count] is /// above 0, currently the model will be always deployed precisely on /// [min_replica_count][google.cloud.aiplatform.v1.DedicatedResources.min_replica_count]. #[prost(int32, tag = "2")] pub min_replica_count: i32, /// Immutable. The maximum number of replicas this DeployedModel may be deployed on when /// the traffic against it increases. If the requested value is too large, /// the deployment will error, but if deployment succeeds then the ability /// to scale the model to that many replicas is guaranteed (barring service /// outages). If traffic against the DeployedModel increases beyond what its /// replicas at maximum may handle, a portion of the traffic will be dropped. /// If this value is not provided, will use [min_replica_count][google.cloud.aiplatform.v1.DedicatedResources.min_replica_count] as the /// default value. #[prost(int32, tag = "3")] pub max_replica_count: i32, } /// A description of resources that to large degree are decided by AI Platform, /// and require only a modest additional configuration. /// Each Model supporting these resources documents its specific guidelines. #[derive(Clone, PartialEq, ::prost::Message)] pub struct AutomaticResources { /// Immutable. The minimum number of replicas this DeployedModel will be always deployed /// on. If traffic against it increases, it may dynamically be deployed onto /// more replicas up to [max_replica_count][google.cloud.aiplatform.v1.AutomaticResources.max_replica_count], and as traffic decreases, some /// of these extra replicas may be freed. /// If the requested value is too large, the deployment will error. #[prost(int32, tag = "1")] pub min_replica_count: i32, /// Immutable. The maximum number of replicas this DeployedModel may be deployed on when /// the traffic against it increases. If the requested value is too large, /// the deployment will error, but if deployment succeeds then the ability /// to scale the model to that many replicas is guaranteed (barring service /// outages). If traffic against the DeployedModel increases beyond what its /// replicas at maximum may handle, a portion of the traffic will be dropped. /// If this value is not provided, a no upper bound for scaling under heavy /// traffic will be assume, though AI Platform may be unable to scale beyond /// certain replica number. #[prost(int32, tag = "2")] pub max_replica_count: i32, } /// A description of resources that are used for performing batch operations, are /// dedicated to a Model, and need manual configuration. #[derive(Clone, PartialEq, ::prost::Message)] pub struct BatchDedicatedResources { /// Required. Immutable. The specification of a single machine. #[prost(message, optional, tag = "1")] pub machine_spec: ::core::option::Option<MachineSpec>, /// Immutable. The number of machine replicas used at the start of the batch operation. /// If not set, AI Platform decides starting number, not greater than /// [max_replica_count][google.cloud.aiplatform.v1.BatchDedicatedResources.max_replica_count] #[prost(int32, tag = "2")] pub starting_replica_count: i32, /// Immutable. The maximum number of machine replicas the batch operation may be scaled /// to. The default value is 10. #[prost(int32, tag = "3")] pub max_replica_count: i32, } /// Statistics information about resource consumption. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ResourcesConsumed { /// Output only. The number of replica hours used. Note that many replicas may run in /// parallel, and additionally any given work may be queued for some time. /// Therefore this value is not strictly related to wall time. #[prost(double, tag = "1")] pub replica_hours: f64, } /// Represents the spec of disk options. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DiskSpec { /// Type of the boot disk (default is "pd-ssd"). /// Valid values: "pd-ssd" (Persistent Disk Solid State Drive) or /// "pd-standard" (Persistent Disk Hard Disk Drive). #[prost(string, tag = "1")] pub boot_disk_type: ::prost::alloc::string::String, /// Size in GB of the boot disk (default is 100GB). #[prost(int32, tag = "2")] pub boot_disk_size_gb: i32, } /// Manual batch tuning parameters. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ManualBatchTuningParameters { /// Immutable. The number of the records (e.g. instances) of the operation given in /// each batch to a machine replica. Machine type, and size of a single /// record should be considered when setting this parameter, higher value /// speeds up the batch operation's execution, but too high value will result /// in a whole batch not fitting in a machine's memory, and the whole /// operation will fail. /// The default value is 4. #[prost(int32, tag = "1")] pub batch_size: i32, } /// A job that uses a [Model][google.cloud.aiplatform.v1.BatchPredictionJob.model] to produce predictions /// on multiple [input instances][google.cloud.aiplatform.v1.BatchPredictionJob.input_config]. If /// predictions for significant portion of the instances fail, the job may finish /// without attempting predictions for all remaining instances. #[derive(Clone, PartialEq, ::prost::Message)] pub struct BatchPredictionJob { /// Output only. Resource name of the BatchPredictionJob. #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, /// Required. The user-defined name of this BatchPredictionJob. #[prost(string, tag = "2")] pub display_name: ::prost::alloc::string::String, /// Required. The name of the Model that produces the predictions via this job, /// must share the same ancestor Location. /// Starting this job has no impact on any existing deployments of the Model /// and their resources. #[prost(string, tag = "3")] pub model: ::prost::alloc::string::String, /// Required. Input configuration of the instances on which predictions are performed. /// The schema of any single instance may be specified via /// the [Model's][google.cloud.aiplatform.v1.BatchPredictionJob.model] /// [PredictSchemata's][google.cloud.aiplatform.v1.Model.predict_schemata] /// [instance_schema_uri][google.cloud.aiplatform.v1.PredictSchemata.instance_schema_uri]. #[prost(message, optional, tag = "4")] pub input_config: ::core::option::Option<batch_prediction_job::InputConfig>, /// The parameters that govern the predictions. The schema of the parameters /// may be specified via the [Model's][google.cloud.aiplatform.v1.BatchPredictionJob.model] /// [PredictSchemata's][google.cloud.aiplatform.v1.Model.predict_schemata] /// [parameters_schema_uri][google.cloud.aiplatform.v1.PredictSchemata.parameters_schema_uri]. #[prost(message, optional, tag = "5")] pub model_parameters: ::core::option::Option<::prost_types::Value>, /// Required. The Configuration specifying where output predictions should /// be written. /// The schema of any single prediction may be specified as a concatenation /// of [Model's][google.cloud.aiplatform.v1.BatchPredictionJob.model] /// [PredictSchemata's][google.cloud.aiplatform.v1.Model.predict_schemata] /// [instance_schema_uri][google.cloud.aiplatform.v1.PredictSchemata.instance_schema_uri] /// and /// [prediction_schema_uri][google.cloud.aiplatform.v1.PredictSchemata.prediction_schema_uri]. #[prost(message, optional, tag = "6")] pub output_config: ::core::option::Option<batch_prediction_job::OutputConfig>, /// The config of resources used by the Model during the batch prediction. If /// the Model [supports][google.cloud.aiplatform.v1.Model.supported_deployment_resources_types] /// DEDICATED_RESOURCES this config may be provided (and the job will use these /// resources), if the Model doesn't support AUTOMATIC_RESOURCES, this config /// must be provided. #[prost(message, optional, tag = "7")] pub dedicated_resources: ::core::option::Option<BatchDedicatedResources>, /// Immutable. Parameters configuring the batch behavior. Currently only applicable when /// [dedicated_resources][google.cloud.aiplatform.v1.BatchPredictionJob.dedicated_resources] are used (in other cases AI Platform does /// the tuning itself). #[prost(message, optional, tag = "8")] pub manual_batch_tuning_parameters: ::core::option::Option<ManualBatchTuningParameters>, /// Output only. Information further describing the output of this job. #[prost(message, optional, tag = "9")] pub output_info: ::core::option::Option<batch_prediction_job::OutputInfo>, /// Output only. The detailed state of the job. #[prost(enumeration = "JobState", tag = "10")] pub state: i32, /// Output only. Only populated when the job's state is JOB_STATE_FAILED or /// JOB_STATE_CANCELLED. #[prost(message, optional, tag = "11")] pub error: ::core::option::Option<super::super::super::rpc::Status>, /// Output only. Partial failures encountered. /// For example, single files that can't be read. /// This field never exceeds 20 entries. /// Status details fields contain standard GCP error details. #[prost(message, repeated, tag = "12")] pub partial_failures: ::prost::alloc::vec::Vec<super::super::super::rpc::Status>, /// Output only. Information about resources that had been consumed by this job. /// Provided in real time at best effort basis, as well as a final value /// once the job completes. /// /// Note: This field currently may be not populated for batch predictions that /// use AutoML Models. #[prost(message, optional, tag = "13")] pub resources_consumed: ::core::option::Option<ResourcesConsumed>, /// Output only. Statistics on completed and failed prediction instances. #[prost(message, optional, tag = "14")] pub completion_stats: ::core::option::Option<CompletionStats>, /// Output only. Time when the BatchPredictionJob was created. #[prost(message, optional, tag = "15")] pub create_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. Time when the BatchPredictionJob for the first time entered the /// `JOB_STATE_RUNNING` state. #[prost(message, optional, tag = "16")] pub start_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. Time when the BatchPredictionJob entered any of the following states: /// `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`. #[prost(message, optional, tag = "17")] pub end_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. Time when the BatchPredictionJob was most recently updated. #[prost(message, optional, tag = "18")] pub update_time: ::core::option::Option<::prost_types::Timestamp>, /// The labels with user-defined metadata to organize BatchPredictionJobs. /// /// Label keys and values can be no longer than 64 characters /// (Unicode codepoints), can only contain lowercase letters, numeric /// characters, underscores and dashes. International characters are allowed. /// /// See https://goo.gl/xmQnxf for more information and examples of labels. #[prost(map = "string, string", tag = "19")] pub labels: ::std::collections::HashMap<::prost::alloc::string::String, ::prost::alloc::string::String>, /// Customer-managed encryption key options for a BatchPredictionJob. If this /// is set, then all resources created by the BatchPredictionJob will be /// encrypted with the provided encryption key. #[prost(message, optional, tag = "24")] pub encryption_spec: ::core::option::Option<EncryptionSpec>, } /// Nested message and enum types in `BatchPredictionJob`. pub mod batch_prediction_job { /// Configures the input to [BatchPredictionJob][google.cloud.aiplatform.v1.BatchPredictionJob]. /// See [Model.supported_input_storage_formats][google.cloud.aiplatform.v1.Model.supported_input_storage_formats] for Model's supported input /// formats, and how instances should be expressed via any of them. #[derive(Clone, PartialEq, ::prost::Message)] pub struct InputConfig { /// Required. The format in which instances are given, must be one of the /// [Model's][google.cloud.aiplatform.v1.BatchPredictionJob.model] /// [supported_input_storage_formats][google.cloud.aiplatform.v1.Model.supported_input_storage_formats]. #[prost(string, tag = "1")] pub instances_format: ::prost::alloc::string::String, /// Required. The source of the input. #[prost(oneof = "input_config::Source", tags = "2, 3")] pub source: ::core::option::Option<input_config::Source>, } /// Nested message and enum types in `InputConfig`. pub mod input_config { /// Required. The source of the input. #[derive(Clone, PartialEq, ::prost::Oneof)] pub enum Source { /// The Cloud Storage location for the input instances. #[prost(message, tag = "2")] GcsSource(super::super::GcsSource), /// The BigQuery location of the input table. /// The schema of the table should be in the format described by the given /// context OpenAPI Schema, if one is provided. The table may contain /// additional columns that are not described by the schema, and they will /// be ignored. #[prost(message, tag = "3")] BigquerySource(super::super::BigQuerySource), } } /// Configures the output of [BatchPredictionJob][google.cloud.aiplatform.v1.BatchPredictionJob]. /// See [Model.supported_output_storage_formats][google.cloud.aiplatform.v1.Model.supported_output_storage_formats] for supported output /// formats, and how predictions are expressed via any of them. #[derive(Clone, PartialEq, ::prost::Message)] pub struct OutputConfig { /// Required. The format in which AI Platform gives the predictions, must be one of the /// [Model's][google.cloud.aiplatform.v1.BatchPredictionJob.model] /// /// [supported_output_storage_formats][google.cloud.aiplatform.v1.Model.supported_output_storage_formats]. #[prost(string, tag = "1")] pub predictions_format: ::prost::alloc::string::String, /// Required. The destination of the output. #[prost(oneof = "output_config::Destination", tags = "2, 3")] pub destination: ::core::option::Option<output_config::Destination>, } /// Nested message and enum types in `OutputConfig`. pub mod output_config { /// Required. The destination of the output. #[derive(Clone, PartialEq, ::prost::Oneof)] pub enum Destination { /// The Cloud Storage location of the directory where the output is /// to be written to. In the given directory a new directory is created. /// Its name is `prediction-<model-display-name>-<job-create-time>`, /// where timestamp is in YYYY-MM-DDThh:mm:ss.sssZ ISO-8601 format. /// Inside of it files `predictions_0001.<extension>`, /// `predictions_0002.<extension>`, ..., `predictions_N.<extension>` /// are created where `<extension>` depends on chosen /// [predictions_format][google.cloud.aiplatform.v1.BatchPredictionJob.OutputConfig.predictions_format], and N may equal 0001 and depends on the total /// number of successfully predicted instances. /// If the Model has both [instance][google.cloud.aiplatform.v1.PredictSchemata.instance_schema_uri] /// and [prediction][google.cloud.aiplatform.v1.PredictSchemata.parameters_schema_uri] schemata /// defined then each such file contains predictions as per the /// [predictions_format][google.cloud.aiplatform.v1.BatchPredictionJob.OutputConfig.predictions_format]. /// If prediction for any instance failed (partially or completely), then /// an additional `errors_0001.<extension>`, `errors_0002.<extension>`,..., /// `errors_N.<extension>` files are created (N depends on total number /// of failed predictions). These files contain the failed instances, /// as per their schema, followed by an additional `error` field which as /// value has /// [`google.rpc.Status`](Status) /// containing only `code` and `message` fields. #[prost(message, tag = "2")] GcsDestination(super::super::GcsDestination), /// The BigQuery project location where the output is to be written to. /// In the given project a new dataset is created with name /// `prediction_<model-display-name>_<job-create-time>` /// where <model-display-name> is made /// BigQuery-dataset-name compatible (for example, most special characters /// become underscores), and timestamp is in /// YYYY_MM_DDThh_mm_ss_sssZ "based on ISO-8601" format. In the dataset /// two tables will be created, `predictions`, and `errors`. /// If the Model has both [instance][google.cloud.aiplatform.v1.PredictSchemata.instance_schema_uri] /// and [prediction][google.cloud.aiplatform.v1.PredictSchemata.parameters_schema_uri] schemata /// defined then the tables have columns as follows: The `predictions` /// table contains instances for which the prediction succeeded, it /// has columns as per a concatenation of the Model's instance and /// prediction schemata. The `errors` table contains rows for which the /// prediction has failed, it has instance columns, as per the /// instance schema, followed by a single "errors" column, which as values /// has [`google.rpc.Status`](Status) /// represented as a STRUCT, and containing only `code` and `message`. #[prost(message, tag = "3")] BigqueryDestination(super::super::BigQueryDestination), } } /// Further describes this job's output. /// Supplements [output_config][google.cloud.aiplatform.v1.BatchPredictionJob.output_config]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct OutputInfo { /// The output location into which prediction output is written. #[prost(oneof = "output_info::OutputLocation", tags = "1, 2")] pub output_location: ::core::option::Option<output_info::OutputLocation>, } /// Nested message and enum types in `OutputInfo`. pub mod output_info { /// The output location into which prediction output is written. #[derive(Clone, PartialEq, ::prost::Oneof)] pub enum OutputLocation { /// Output only. The full path of the Cloud Storage directory created, into which /// the prediction output is written. #[prost(string, tag = "1")] GcsOutputDirectory(::prost::alloc::string::String), /// Output only. The path of the BigQuery dataset created, in /// `bq://projectId.bqDatasetId` /// format, into which the prediction output is written. #[prost(string, tag = "2")] BigqueryOutputDataset(::prost::alloc::string::String), } } } /// Represents an environment variable present in a Container or Python Module. #[derive(Clone, PartialEq, ::prost::Message)] pub struct EnvVar { /// Required. Name of the environment variable. Must be a valid C identifier. #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, /// Required. Variables that reference a $(VAR_NAME) are expanded /// using the previous defined environment variables in the container and /// any service environment variables. If a variable cannot be resolved, /// the reference in the input string will be unchanged. The $(VAR_NAME) /// syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped /// references will never be expanded, regardless of whether the variable /// exists or not. #[prost(string, tag = "2")] pub value: ::prost::alloc::string::String, } /// Represents a job that runs custom workloads such as a Docker container or a /// Python package. A CustomJob can have multiple worker pools and each worker /// pool can have its own machine and input spec. A CustomJob will be cleaned up /// once the job enters terminal state (failed or succeeded). #[derive(Clone, PartialEq, ::prost::Message)] pub struct CustomJob { /// Output only. Resource name of a CustomJob. #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, /// Required. The display name of the CustomJob. /// The name can be up to 128 characters long and can be consist of any UTF-8 /// characters. #[prost(string, tag = "2")] pub display_name: ::prost::alloc::string::String, /// Required. Job spec. #[prost(message, optional, tag = "4")] pub job_spec: ::core::option::Option<CustomJobSpec>, /// Output only. The detailed state of the job. #[prost(enumeration = "JobState", tag = "5")] pub state: i32, /// Output only. Time when the CustomJob was created. #[prost(message, optional, tag = "6")] pub create_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. Time when the CustomJob for the first time entered the /// `JOB_STATE_RUNNING` state. #[prost(message, optional, tag = "7")] pub start_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. Time when the CustomJob entered any of the following states: /// `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`. #[prost(message, optional, tag = "8")] pub end_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. Time when the CustomJob was most recently updated. #[prost(message, optional, tag = "9")] pub update_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. Only populated when job's state is `JOB_STATE_FAILED` or /// `JOB_STATE_CANCELLED`. #[prost(message, optional, tag = "10")] pub error: ::core::option::Option<super::super::super::rpc::Status>, /// The labels with user-defined metadata to organize CustomJobs. /// /// Label keys and values can be no longer than 64 characters /// (Unicode codepoints), can only contain lowercase letters, numeric /// characters, underscores and dashes. International characters are allowed. /// /// See https://goo.gl/xmQnxf for more information and examples of labels. #[prost(map = "string, string", tag = "11")] pub labels: ::std::collections::HashMap<::prost::alloc::string::String, ::prost::alloc::string::String>, /// Customer-managed encryption key options for a CustomJob. If this is set, /// then all resources created by the CustomJob will be encrypted with the /// provided encryption key. #[prost(message, optional, tag = "12")] pub encryption_spec: ::core::option::Option<EncryptionSpec>, } /// Represents the spec of a CustomJob. #[derive(Clone, PartialEq, ::prost::Message)] pub struct CustomJobSpec { /// Required. The spec of the worker pools including machine type and Docker image. #[prost(message, repeated, tag = "1")] pub worker_pool_specs: ::prost::alloc::vec::Vec<WorkerPoolSpec>, /// Scheduling options for a CustomJob. #[prost(message, optional, tag = "3")] pub scheduling: ::core::option::Option<Scheduling>, /// Specifies the service account for workload run-as account. /// Users submitting jobs must have act-as permission on this run-as account. /// If unspecified, the AI Platform Custom Code Service Agent for the /// CustomJob's project is used. #[prost(string, tag = "4")] pub service_account: ::prost::alloc::string::String, /// The full name of the Compute Engine /// [network](/compute/docs/networks-and-firewalls#networks) to which the Job /// should be peered. For example, `projects/12345/global/networks/myVPC`. /// [Format](/compute/docs/reference/rest/v1/networks/insert) /// is of the form `projects/{project}/global/networks/{network}`. /// Where {project} is a project number, as in `12345`, and {network} is a /// network name. /// /// Private services access must already be configured for the network. If left /// unspecified, the job is not peered with any network. #[prost(string, tag = "5")] pub network: ::prost::alloc::string::String, /// The Cloud Storage location to store the output of this CustomJob or /// HyperparameterTuningJob. For HyperparameterTuningJob, /// the baseOutputDirectory of /// each child CustomJob backing a Trial is set to a subdirectory of name /// [id][google.cloud.aiplatform.v1.Trial.id] under its parent HyperparameterTuningJob's /// baseOutputDirectory. /// /// The following AI Platform environment variables will be passed to /// containers or python modules when this field is set: /// /// For CustomJob: /// /// * AIP_MODEL_DIR = `<base_output_directory>/model/` /// * AIP_CHECKPOINT_DIR = `<base_output_directory>/checkpoints/` /// * AIP_TENSORBOARD_LOG_DIR = `<base_output_directory>/logs/` /// /// For CustomJob backing a Trial of HyperparameterTuningJob: /// /// * AIP_MODEL_DIR = `<base_output_directory>/<trial_id>/model/` /// * AIP_CHECKPOINT_DIR = `<base_output_directory>/<trial_id>/checkpoints/` /// * AIP_TENSORBOARD_LOG_DIR = `<base_output_directory>/<trial_id>/logs/` #[prost(message, optional, tag = "6")] pub base_output_directory: ::core::option::Option<GcsDestination>, } /// Represents the spec of a worker pool in a job. #[derive(Clone, PartialEq, ::prost::Message)] pub struct WorkerPoolSpec { /// Optional. Immutable. The specification of a single machine. #[prost(message, optional, tag = "1")] pub machine_spec: ::core::option::Option<MachineSpec>, /// Optional. The number of worker replicas to use for this worker pool. #[prost(int64, tag = "2")] pub replica_count: i64, /// Disk spec. #[prost(message, optional, tag = "5")] pub disk_spec: ::core::option::Option<DiskSpec>, /// The custom task to be executed in this worker pool. #[prost(oneof = "worker_pool_spec::Task", tags = "6, 7")] pub task: ::core::option::Option<worker_pool_spec::Task>, } /// Nested message and enum types in `WorkerPoolSpec`. pub mod worker_pool_spec { /// The custom task to be executed in this worker pool. #[derive(Clone, PartialEq, ::prost::Oneof)] pub enum Task { /// The custom container task. #[prost(message, tag = "6")] ContainerSpec(super::ContainerSpec), /// The Python packaged task. #[prost(message, tag = "7")] PythonPackageSpec(super::PythonPackageSpec), } } /// The spec of a Container. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ContainerSpec { /// Required. The URI of a container image in the Container Registry that is to be run on /// each worker replica. #[prost(string, tag = "1")] pub image_uri: ::prost::alloc::string::String, /// The command to be invoked when the container is started. /// It overrides the entrypoint instruction in Dockerfile when provided. #[prost(string, repeated, tag = "2")] pub command: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, /// The arguments to be passed when starting the container. #[prost(string, repeated, tag = "3")] pub args: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, /// Environment variables to be passed to the container. #[prost(message, repeated, tag = "4")] pub env: ::prost::alloc::vec::Vec<EnvVar>, } /// The spec of a Python packaged code. #[derive(Clone, PartialEq, ::prost::Message)] pub struct PythonPackageSpec { /// Required. The URI of a container image in the Container Registry that will run the /// provided python package. AI Platform provides wide range of executor images /// with pre-installed packages to meet users' various use cases. Only one of /// the provided images can be set here. #[prost(string, tag = "1")] pub executor_image_uri: ::prost::alloc::string::String, /// Required. The Google Cloud Storage location of the Python package files which are /// the training program and its dependent packages. /// The maximum number of package URIs is 100. #[prost(string, repeated, tag = "2")] pub package_uris: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, /// Required. The Python module name to run after installing the packages. #[prost(string, tag = "3")] pub python_module: ::prost::alloc::string::String, /// Command line arguments to be passed to the Python task. #[prost(string, repeated, tag = "4")] pub args: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, /// Environment variables to be passed to the python module. #[prost(message, repeated, tag = "5")] pub env: ::prost::alloc::vec::Vec<EnvVar>, } /// All parameters related to queuing and scheduling of custom jobs. #[derive(Clone, PartialEq, ::prost::Message)] pub struct Scheduling { /// The maximum job running time. The default is 7 days. #[prost(message, optional, tag = "1")] pub timeout: ::core::option::Option<::prost_types::Duration>, /// Restarts the entire CustomJob if a worker gets restarted. /// This feature can be used by distributed training jobs that are not /// resilient to workers leaving and joining a job. #[prost(bool, tag = "3")] pub restart_job_on_worker_restart: bool, } /// A piece of data in a Dataset. Could be an image, a video, a document or plain /// text. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DataItem { /// Output only. The resource name of the DataItem. #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, /// Output only. Timestamp when this DataItem was created. #[prost(message, optional, tag = "2")] pub create_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. Timestamp when this DataItem was last updated. #[prost(message, optional, tag = "6")] pub update_time: ::core::option::Option<::prost_types::Timestamp>, /// Optional. The labels with user-defined metadata to organize your DataItems. /// /// Label keys and values can be no longer than 64 characters /// (Unicode codepoints), can only contain lowercase letters, numeric /// characters, underscores and dashes. International characters are allowed. /// No more than 64 user labels can be associated with one DataItem(System /// labels are excluded). /// /// See https://goo.gl/xmQnxf for more information and examples of labels. /// System reserved label keys are prefixed with "aiplatform.googleapis.com/" /// and are immutable. #[prost(map = "string, string", tag = "3")] pub labels: ::std::collections::HashMap<::prost::alloc::string::String, ::prost::alloc::string::String>, /// Required. The data that the DataItem represents (for example, an image or a text /// snippet). The schema of the payload is stored in the parent Dataset's /// [metadata schema's][google.cloud.aiplatform.v1.Dataset.metadata_schema_uri] dataItemSchemaUri field. #[prost(message, optional, tag = "4")] pub payload: ::core::option::Option<::prost_types::Value>, /// Optional. Used to perform consistent read-modify-write updates. If not set, a blind /// "overwrite" update happens. #[prost(string, tag = "7")] pub etag: ::prost::alloc::string::String, } /// SpecialistPool represents customers' own workforce to work on their data /// labeling jobs. It includes a group of specialist managers who are responsible /// for managing the labelers in this pool as well as customers' data labeling /// jobs associated with this pool. /// Customers create specialist pool as well as start data labeling jobs on /// Cloud, managers and labelers work with the jobs using CrowdCompute console. #[derive(Clone, PartialEq, ::prost::Message)] pub struct SpecialistPool { /// Required. The resource name of the SpecialistPool. #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, /// Required. The user-defined name of the SpecialistPool. /// The name can be up to 128 characters long and can be consist of any UTF-8 /// characters. /// This field should be unique on project-level. #[prost(string, tag = "2")] pub display_name: ::prost::alloc::string::String, /// Output only. The number of Specialists in this SpecialistPool. #[prost(int32, tag = "3")] pub specialist_managers_count: i32, /// The email addresses of the specialists in the SpecialistPool. #[prost(string, repeated, tag = "4")] pub specialist_manager_emails: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, /// Output only. The resource name of the pending data labeling jobs. #[prost(string, repeated, tag = "5")] pub pending_data_labeling_jobs: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, } /// DataLabelingJob is used to trigger a human labeling job on unlabeled data /// from the following Dataset: #[derive(Clone, PartialEq, ::prost::Message)] pub struct DataLabelingJob { /// Output only. Resource name of the DataLabelingJob. #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, /// Required. The user-defined name of the DataLabelingJob. /// The name can be up to 128 characters long and can be consist of any UTF-8 /// characters. /// Display name of a DataLabelingJob. #[prost(string, tag = "2")] pub display_name: ::prost::alloc::string::String, /// Required. Dataset resource names. Right now we only support labeling from a single /// Dataset. /// Format: /// `projects/{project}/locations/{location}/datasets/{dataset}` #[prost(string, repeated, tag = "3")] pub datasets: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, /// Labels to assign to annotations generated by this DataLabelingJob. /// /// Label keys and values can be no longer than 64 characters /// (Unicode codepoints), can only contain lowercase letters, numeric /// characters, underscores and dashes. International characters are allowed. /// See https://goo.gl/xmQnxf for more information and examples of labels. /// System reserved label keys are prefixed with "aiplatform.googleapis.com/" /// and are immutable. #[prost(map = "string, string", tag = "12")] pub annotation_labels: ::std::collections::HashMap<::prost::alloc::string::String, ::prost::alloc::string::String>, /// Required. Number of labelers to work on each DataItem. #[prost(int32, tag = "4")] pub labeler_count: i32, /// Required. The Google Cloud Storage location of the instruction pdf. This pdf is /// shared with labelers, and provides detailed description on how to label /// DataItems in Datasets. #[prost(string, tag = "5")] pub instruction_uri: ::prost::alloc::string::String, /// Required. Points to a YAML file stored on Google Cloud Storage describing the /// config for a specific type of DataLabelingJob. /// The schema files that can be used here are found in the /// https://storage.googleapis.com/google-cloud-aiplatform bucket in the /// /schema/datalabelingjob/inputs/ folder. #[prost(string, tag = "6")] pub inputs_schema_uri: ::prost::alloc::string::String, /// Required. Input config parameters for the DataLabelingJob. #[prost(message, optional, tag = "7")] pub inputs: ::core::option::Option<::prost_types::Value>, /// Output only. The detailed state of the job. #[prost(enumeration = "JobState", tag = "8")] pub state: i32, /// Output only. Current labeling job progress percentage scaled in interval [0, 100], /// indicating the percentage of DataItems that has been finished. #[prost(int32, tag = "13")] pub labeling_progress: i32, /// Output only. Estimated cost(in US dollars) that the DataLabelingJob has incurred to /// date. #[prost(message, optional, tag = "14")] pub current_spend: ::core::option::Option<super::super::super::r#type::Money>, /// Output only. Timestamp when this DataLabelingJob was created. #[prost(message, optional, tag = "9")] pub create_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. Timestamp when this DataLabelingJob was updated most recently. #[prost(message, optional, tag = "10")] pub update_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. DataLabelingJob errors. It is only populated when job's state is /// `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. #[prost(message, optional, tag = "22")] pub error: ::core::option::Option<super::super::super::rpc::Status>, /// The labels with user-defined metadata to organize your DataLabelingJobs. /// /// Label keys and values can be no longer than 64 characters /// (Unicode codepoints), can only contain lowercase letters, numeric /// characters, underscores and dashes. International characters are allowed. /// /// See https://goo.gl/xmQnxf for more information and examples of labels. /// System reserved label keys are prefixed with "aiplatform.googleapis.com/" /// and are immutable. Following system labels exist for each DataLabelingJob: /// /// * "aiplatform.googleapis.com/schema": output only, its value is the /// [inputs_schema][google.cloud.aiplatform.v1.DataLabelingJob.inputs_schema_uri]'s title. #[prost(map = "string, string", tag = "11")] pub labels: ::std::collections::HashMap<::prost::alloc::string::String, ::prost::alloc::string::String>, /// The SpecialistPools' resource names associated with this job. #[prost(string, repeated, tag = "16")] pub specialist_pools: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, /// Customer-managed encryption key spec for a DataLabelingJob. If set, this /// DataLabelingJob will be secured by this key. /// /// Note: Annotations created in the DataLabelingJob are associated with /// the EncryptionSpec of the Dataset they are exported to. #[prost(message, optional, tag = "20")] pub encryption_spec: ::core::option::Option<EncryptionSpec>, /// Parameters that configure the active learning pipeline. Active learning will /// label the data incrementally via several iterations. For every iteration, /// it will select a batch of data based on the sampling strategy. #[prost(message, optional, tag = "21")] pub active_learning_config: ::core::option::Option<ActiveLearningConfig>, } /// Parameters that configure the active learning pipeline. Active learning will /// label the data incrementally by several iterations. For every iteration, it /// will select a batch of data based on the sampling strategy. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ActiveLearningConfig { /// Active learning data sampling config. For every active learning labeling /// iteration, it will select a batch of data based on the sampling strategy. #[prost(message, optional, tag = "3")] pub sample_config: ::core::option::Option<SampleConfig>, /// CMLE training config. For every active learning labeling iteration, system /// will train a machine learning model on CMLE. The trained model will be used /// by data sampling algorithm to select DataItems. #[prost(message, optional, tag = "4")] pub training_config: ::core::option::Option<TrainingConfig>, /// Required. Max human labeling DataItems. The rest part will be labeled by /// machine. #[prost(oneof = "active_learning_config::HumanLabelingBudget", tags = "1, 2")] pub human_labeling_budget: ::core::option::Option<active_learning_config::HumanLabelingBudget>, } /// Nested message and enum types in `ActiveLearningConfig`. pub mod active_learning_config { /// Required. Max human labeling DataItems. The rest part will be labeled by /// machine. #[derive(Clone, PartialEq, ::prost::Oneof)] pub enum HumanLabelingBudget { /// Max number of human labeled DataItems. #[prost(int64, tag = "1")] MaxDataItemCount(i64), /// Max percent of total DataItems for human labeling. #[prost(int32, tag = "2")] MaxDataItemPercentage(i32), } } /// Active learning data sampling config. For every active learning labeling /// iteration, it will select a batch of data based on the sampling strategy. #[derive(Clone, PartialEq, ::prost::Message)] pub struct SampleConfig { /// Field to choose sampling strategy. Sampling strategy will decide which data /// should be selected for human labeling in every batch. #[prost(enumeration = "sample_config::SampleStrategy", tag = "5")] pub sample_strategy: i32, /// Decides sample size for the initial batch. initial_batch_sample_percentage /// is used by default. #[prost(oneof = "sample_config::InitialBatchSampleSize", tags = "1")] pub initial_batch_sample_size: ::core::option::Option<sample_config::InitialBatchSampleSize>, /// Decides sample size for the following batches. /// following_batch_sample_percentage is used by default. #[prost(oneof = "sample_config::FollowingBatchSampleSize", tags = "3")] pub following_batch_sample_size: ::core::option::Option<sample_config::FollowingBatchSampleSize>, } /// Nested message and enum types in `SampleConfig`. pub mod sample_config { /// Sample strategy decides which subset of DataItems should be selected for /// human labeling in every batch. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum SampleStrategy { /// Default will be treated as UNCERTAINTY. Unspecified = 0, /// Sample the most uncertain data to label. Uncertainty = 1, } /// Decides sample size for the initial batch. initial_batch_sample_percentage /// is used by default. #[derive(Clone, PartialEq, ::prost::Oneof)] pub enum InitialBatchSampleSize { /// The percentage of data needed to be labeled in the first batch. #[prost(int32, tag = "1")] InitialBatchSamplePercentage(i32), } /// Decides sample size for the following batches. /// following_batch_sample_percentage is used by default. #[derive(Clone, PartialEq, ::prost::Oneof)] pub enum FollowingBatchSampleSize { /// The percentage of data needed to be labeled in each following batch /// (except the first batch). #[prost(int32, tag = "3")] FollowingBatchSamplePercentage(i32), } } /// CMLE training config. For every active learning labeling iteration, system /// will train a machine learning model on CMLE. The trained model will be used /// by data sampling algorithm to select DataItems. #[derive(Clone, PartialEq, ::prost::Message)] pub struct TrainingConfig { /// The timeout hours for the CMLE training job, expressed in milli hours /// i.e. 1,000 value in this field means 1 hour. #[prost(int64, tag = "1")] pub timeout_training_milli_hours: i64, } /// A collection of DataItems and Annotations on them. #[derive(Clone, PartialEq, ::prost::Message)] pub struct Dataset { /// Output only. The resource name of the Dataset. #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, /// Required. The user-defined name of the Dataset. /// The name can be up to 128 characters long and can be consist of any UTF-8 /// characters. #[prost(string, tag = "2")] pub display_name: ::prost::alloc::string::String, /// Required. Points to a YAML file stored on Google Cloud Storage describing additional /// information about the Dataset. /// The schema is defined as an OpenAPI 3.0.2 Schema Object. /// The schema files that can be used here are found in /// gs://google-cloud-aiplatform/schema/dataset/metadata/. #[prost(string, tag = "3")] pub metadata_schema_uri: ::prost::alloc::string::String, /// Required. Additional information about the Dataset. #[prost(message, optional, tag = "8")] pub metadata: ::core::option::Option<::prost_types::Value>, /// Output only. Timestamp when this Dataset was created. #[prost(message, optional, tag = "4")] pub create_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. Timestamp when this Dataset was last updated. #[prost(message, optional, tag = "5")] pub update_time: ::core::option::Option<::prost_types::Timestamp>, /// Used to perform consistent read-modify-write updates. If not set, a blind /// "overwrite" update happens. #[prost(string, tag = "6")] pub etag: ::prost::alloc::string::String, /// The labels with user-defined metadata to organize your Datasets. /// /// Label keys and values can be no longer than 64 characters /// (Unicode codepoints), can only contain lowercase letters, numeric /// characters, underscores and dashes. International characters are allowed. /// No more than 64 user labels can be associated with one Dataset (System /// labels are excluded). /// /// See https://goo.gl/xmQnxf for more information and examples of labels. /// System reserved label keys are prefixed with "aiplatform.googleapis.com/" /// and are immutable. Following system labels exist for each Dataset: /// /// * "aiplatform.googleapis.com/dataset_metadata_schema": output only, its /// value is the [metadata_schema's][google.cloud.aiplatform.v1.Dataset.metadata_schema_uri] title. #[prost(map = "string, string", tag = "7")] pub labels: ::std::collections::HashMap<::prost::alloc::string::String, ::prost::alloc::string::String>, /// Customer-managed encryption key spec for a Dataset. If set, this Dataset /// and all sub-resources of this Dataset will be secured by this key. #[prost(message, optional, tag = "11")] pub encryption_spec: ::core::option::Option<EncryptionSpec>, } /// Describes the location from where we import data into a Dataset, together /// with the labels that will be applied to the DataItems and the Annotations. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ImportDataConfig { /// Labels that will be applied to newly imported DataItems. If an identical /// DataItem as one being imported already exists in the Dataset, then these /// labels will be appended to these of the already existing one, and if labels /// with identical key is imported before, the old label value will be /// overwritten. If two DataItems are identical in the same import data /// operation, the labels will be combined and if key collision happens in this /// case, one of the values will be picked randomly. Two DataItems are /// considered identical if their content bytes are identical (e.g. image bytes /// or pdf bytes). /// These labels will be overridden by Annotation labels specified inside index /// file referenced by [import_schema_uri][google.cloud.aiplatform.v1.ImportDataConfig.import_schema_uri], e.g. jsonl file. #[prost(map = "string, string", tag = "2")] pub data_item_labels: ::std::collections::HashMap<::prost::alloc::string::String, ::prost::alloc::string::String>, /// Required. Points to a YAML file stored on Google Cloud Storage describing the import /// format. Validation will be done against the schema. The schema is defined /// as an [OpenAPI 3.0.2 Schema Object](https://tinyurl.com/y538mdwt). #[prost(string, tag = "4")] pub import_schema_uri: ::prost::alloc::string::String, /// The source of the input. #[prost(oneof = "import_data_config::Source", tags = "1")] pub source: ::core::option::Option<import_data_config::Source>, } /// Nested message and enum types in `ImportDataConfig`. pub mod import_data_config { /// The source of the input. #[derive(Clone, PartialEq, ::prost::Oneof)] pub enum Source { /// The Google Cloud Storage location for the input content. #[prost(message, tag = "1")] GcsSource(super::GcsSource), } } /// Describes what part of the Dataset is to be exported, the destination of /// the export and how to export. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ExportDataConfig { /// A filter on Annotations of the Dataset. Only Annotations on to-be-exported /// DataItems(specified by [data_items_filter][]) that match this filter will /// be exported. The filter syntax is the same as in /// [ListAnnotations][google.cloud.aiplatform.v1.DatasetService.ListAnnotations]. #[prost(string, tag = "2")] pub annotations_filter: ::prost::alloc::string::String, /// The destination of the output. #[prost(oneof = "export_data_config::Destination", tags = "1")] pub destination: ::core::option::Option<export_data_config::Destination>, } /// Nested message and enum types in `ExportDataConfig`. pub mod export_data_config { /// The destination of the output. #[derive(Clone, PartialEq, ::prost::Oneof)] pub enum Destination { /// The Google Cloud Storage location where the output is to be written to. /// In the given directory a new directory will be created with name: /// `export-data-<dataset-display-name>-<timestamp-of-export-call>` where /// timestamp is in YYYY-MM-DDThh:mm:ss.sssZ ISO-8601 format. All export /// output will be written into that directory. Inside that directory, /// annotations with the same schema will be grouped into sub directories /// which are named with the corresponding annotations' schema title. Inside /// these sub directories, a schema.yaml will be created to describe the /// output format. #[prost(message, tag = "1")] GcsDestination(super::GcsDestination), } } /// Generic Metadata shared by all operations. #[derive(Clone, PartialEq, ::prost::Message)] pub struct GenericOperationMetadata { /// Output only. Partial failures encountered. /// E.g. single files that couldn't be read. /// This field should never exceed 20 entries. /// Status details field will contain standard GCP error details. #[prost(message, repeated, tag = "1")] pub partial_failures: ::prost::alloc::vec::Vec<super::super::super::rpc::Status>, /// Output only. Time when the operation was created. #[prost(message, optional, tag = "2")] pub create_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. Time when the operation was updated for the last time. /// If the operation has finished (successfully or not), this is the finish /// time. #[prost(message, optional, tag = "3")] pub update_time: ::core::option::Option<::prost_types::Timestamp>, } /// Details of operations that perform deletes of any entities. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DeleteOperationMetadata { /// The common part of the operation metadata. #[prost(message, optional, tag = "1")] pub generic_metadata: ::core::option::Option<GenericOperationMetadata>, } /// Points to a DeployedModel. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DeployedModelRef { /// Immutable. A resource name of an Endpoint. #[prost(string, tag = "1")] pub endpoint: ::prost::alloc::string::String, /// Immutable. An ID of a DeployedModel in the above Endpoint. #[prost(string, tag = "2")] pub deployed_model_id: ::prost::alloc::string::String, } /// A trained machine learning Model. #[derive(Clone, PartialEq, ::prost::Message)] pub struct Model { /// The resource name of the Model. #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, /// Required. The display name of the Model. /// The name can be up to 128 characters long and can be consist of any UTF-8 /// characters. #[prost(string, tag = "2")] pub display_name: ::prost::alloc::string::String, /// The description of the Model. #[prost(string, tag = "3")] pub description: ::prost::alloc::string::String, /// The schemata that describe formats of the Model's predictions and /// explanations as given and returned via /// [PredictionService.Predict][google.cloud.aiplatform.v1.PredictionService.Predict] and [PredictionService.Explain][]. #[prost(message, optional, tag = "4")] pub predict_schemata: ::core::option::Option<PredictSchemata>, /// Immutable. Points to a YAML file stored on Google Cloud Storage describing additional /// information about the Model, that is specific to it. Unset if the Model /// does not have any additional information. /// The schema is defined as an OpenAPI 3.0.2 /// [Schema Object](https://tinyurl.com/y538mdwt#schema-object). /// AutoML Models always have this field populated by AI Platform, if no /// additional metadata is needed, this field is set to an empty string. /// Note: The URI given on output will be immutable and probably different, /// including the URI scheme, than the one given on input. The output URI will /// point to a location where the user only has a read access. #[prost(string, tag = "5")] pub metadata_schema_uri: ::prost::alloc::string::String, /// Immutable. An additional information about the Model; the schema of the metadata can /// be found in [metadata_schema][google.cloud.aiplatform.v1.Model.metadata_schema_uri]. /// Unset if the Model does not have any additional information. #[prost(message, optional, tag = "6")] pub metadata: ::core::option::Option<::prost_types::Value>, /// Output only. The formats in which this Model may be exported. If empty, this Model is /// not available for export. #[prost(message, repeated, tag = "20")] pub supported_export_formats: ::prost::alloc::vec::Vec<model::ExportFormat>, /// Output only. The resource name of the TrainingPipeline that uploaded this Model, if any. #[prost(string, tag = "7")] pub training_pipeline: ::prost::alloc::string::String, /// Input only. The specification of the container that is to be used when deploying /// this Model. The specification is ingested upon /// [ModelService.UploadModel][google.cloud.aiplatform.v1.ModelService.UploadModel], and all binaries it contains are copied /// and stored internally by AI Platform. /// Not present for AutoML Models. #[prost(message, optional, tag = "9")] pub container_spec: ::core::option::Option<ModelContainerSpec>, /// Immutable. The path to the directory containing the Model artifact and any of its /// supporting files. /// Not present for AutoML Models. #[prost(string, tag = "26")] pub artifact_uri: ::prost::alloc::string::String, /// Output only. When this Model is deployed, its prediction resources are described by the /// `prediction_resources` field of the [Endpoint.deployed_models][google.cloud.aiplatform.v1.Endpoint.deployed_models] object. /// Because not all Models support all resource configuration types, the /// configuration types this Model supports are listed here. If no /// configuration types are listed, the Model cannot be deployed to an /// [Endpoint][google.cloud.aiplatform.v1.Endpoint] and does not support /// online predictions ([PredictionService.Predict][google.cloud.aiplatform.v1.PredictionService.Predict] or /// [PredictionService.Explain][]). Such a Model can serve predictions by /// using a [BatchPredictionJob][google.cloud.aiplatform.v1.BatchPredictionJob], if it has at least one entry each in /// [supported_input_storage_formats][google.cloud.aiplatform.v1.Model.supported_input_storage_formats] and /// [supported_output_storage_formats][google.cloud.aiplatform.v1.Model.supported_output_storage_formats]. #[prost( enumeration = "model::DeploymentResourcesType", repeated, packed = "false", tag = "10" )] pub supported_deployment_resources_types: ::prost::alloc::vec::Vec<i32>, /// Output only. The formats this Model supports in /// [BatchPredictionJob.input_config][google.cloud.aiplatform.v1.BatchPredictionJob.input_config]. If /// [PredictSchemata.instance_schema_uri][google.cloud.aiplatform.v1.PredictSchemata.instance_schema_uri] exists, the instances /// should be given as per that schema. /// /// The possible formats are: /// /// * `jsonl` /// The JSON Lines format, where each instance is a single line. Uses /// [GcsSource][google.cloud.aiplatform.v1.BatchPredictionJob.InputConfig.gcs_source]. /// /// * `csv` /// The CSV format, where each instance is a single comma-separated line. /// The first line in the file is the header, containing comma-separated field /// names. Uses [GcsSource][google.cloud.aiplatform.v1.BatchPredictionJob.InputConfig.gcs_source]. /// /// * `tf-record` /// The TFRecord format, where each instance is a single record in tfrecord /// syntax. Uses [GcsSource][google.cloud.aiplatform.v1.BatchPredictionJob.InputConfig.gcs_source]. /// /// * `tf-record-gzip` /// Similar to `tf-record`, but the file is gzipped. Uses /// [GcsSource][google.cloud.aiplatform.v1.BatchPredictionJob.InputConfig.gcs_source]. /// /// * `bigquery` /// Each instance is a single row in BigQuery. Uses /// [BigQuerySource][google.cloud.aiplatform.v1.BatchPredictionJob.InputConfig.bigquery_source]. /// /// * `file-list` /// Each line of the file is the location of an instance to process, uses /// `gcs_source` field of the /// [InputConfig][google.cloud.aiplatform.v1.BatchPredictionJob.InputConfig] object. /// /// /// If this Model doesn't support any of these formats it means it cannot be /// used with a [BatchPredictionJob][google.cloud.aiplatform.v1.BatchPredictionJob]. However, if it has /// [supported_deployment_resources_types][google.cloud.aiplatform.v1.Model.supported_deployment_resources_types], it could serve online /// predictions by using [PredictionService.Predict][google.cloud.aiplatform.v1.PredictionService.Predict] or /// [PredictionService.Explain][]. #[prost(string, repeated, tag = "11")] pub supported_input_storage_formats: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, /// Output only. The formats this Model supports in /// [BatchPredictionJob.output_config][google.cloud.aiplatform.v1.BatchPredictionJob.output_config]. If both /// [PredictSchemata.instance_schema_uri][google.cloud.aiplatform.v1.PredictSchemata.instance_schema_uri] and /// [PredictSchemata.prediction_schema_uri][google.cloud.aiplatform.v1.PredictSchemata.prediction_schema_uri] exist, the predictions /// are returned together with their instances. In other words, the /// prediction has the original instance data first, followed /// by the actual prediction content (as per the schema). /// /// The possible formats are: /// /// * `jsonl` /// The JSON Lines format, where each prediction is a single line. Uses /// [GcsDestination][google.cloud.aiplatform.v1.BatchPredictionJob.OutputConfig.gcs_destination]. /// /// * `csv` /// The CSV format, where each prediction is a single comma-separated line. /// The first line in the file is the header, containing comma-separated field /// names. Uses /// [GcsDestination][google.cloud.aiplatform.v1.BatchPredictionJob.OutputConfig.gcs_destination]. /// /// * `bigquery` /// Each prediction is a single row in a BigQuery table, uses /// [BigQueryDestination][google.cloud.aiplatform.v1.BatchPredictionJob.OutputConfig.bigquery_destination] /// . /// /// /// If this Model doesn't support any of these formats it means it cannot be /// used with a [BatchPredictionJob][google.cloud.aiplatform.v1.BatchPredictionJob]. However, if it has /// [supported_deployment_resources_types][google.cloud.aiplatform.v1.Model.supported_deployment_resources_types], it could serve online /// predictions by using [PredictionService.Predict][google.cloud.aiplatform.v1.PredictionService.Predict] or /// [PredictionService.Explain][]. #[prost(string, repeated, tag = "12")] pub supported_output_storage_formats: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, /// Output only. Timestamp when this Model was uploaded into AI Platform. #[prost(message, optional, tag = "13")] pub create_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. Timestamp when this Model was most recently updated. #[prost(message, optional, tag = "14")] pub update_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. The pointers to DeployedModels created from this Model. Note that /// Model could have been deployed to Endpoints in different Locations. #[prost(message, repeated, tag = "15")] pub deployed_models: ::prost::alloc::vec::Vec<DeployedModelRef>, /// Used to perform consistent read-modify-write updates. If not set, a blind /// "overwrite" update happens. #[prost(string, tag = "16")] pub etag: ::prost::alloc::string::String, /// The labels with user-defined metadata to organize your Models. /// /// Label keys and values can be no longer than 64 characters /// (Unicode codepoints), can only contain lowercase letters, numeric /// characters, underscores and dashes. International characters are allowed. /// /// See https://goo.gl/xmQnxf for more information and examples of labels. #[prost(map = "string, string", tag = "17")] pub labels: ::std::collections::HashMap<::prost::alloc::string::String, ::prost::alloc::string::String>, /// Customer-managed encryption key spec for a Model. If set, this /// Model and all sub-resources of this Model will be secured by this key. #[prost(message, optional, tag = "24")] pub encryption_spec: ::core::option::Option<EncryptionSpec>, } /// Nested message and enum types in `Model`. pub mod model { /// Represents export format supported by the Model. /// All formats export to Google Cloud Storage. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ExportFormat { /// Output only. The ID of the export format. /// The possible format IDs are: /// /// * `tflite` /// Used for Android mobile devices. /// /// * `edgetpu-tflite` /// Used for [Edge TPU](https://cloud.google.com/edge-tpu/) devices. /// /// * `tf-saved-model` /// A tensorflow model in SavedModel format. /// /// * `tf-js` /// A [TensorFlow.js](https://www.tensorflow.org/js) model that can be used /// in the browser and in Node.js using JavaScript. /// /// * `core-ml` /// Used for iOS mobile devices. /// /// * `custom-trained` /// A Model that was uploaded or trained by custom code. #[prost(string, tag = "1")] pub id: ::prost::alloc::string::String, /// Output only. The content of this Model that may be exported. #[prost( enumeration = "export_format::ExportableContent", repeated, packed = "false", tag = "2" )] pub exportable_contents: ::prost::alloc::vec::Vec<i32>, } /// Nested message and enum types in `ExportFormat`. pub mod export_format { /// The Model content that can be exported. #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration, )] #[repr(i32)] pub enum ExportableContent { /// Should not be used. Unspecified = 0, /// Model artifact and any of its supported files. Will be exported to the /// location specified by the `artifactDestination` field of the /// [ExportModelRequest.output_config][google.cloud.aiplatform.v1.ExportModelRequest.output_config] object. Artifact = 1, /// The container image that is to be used when deploying this Model. Will /// be exported to the location specified by the `imageDestination` field /// of the [ExportModelRequest.output_config][google.cloud.aiplatform.v1.ExportModelRequest.output_config] object. Image = 2, } } /// Identifies a type of Model's prediction resources. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum DeploymentResourcesType { /// Should not be used. Unspecified = 0, /// Resources that are dedicated to the [DeployedModel][google.cloud.aiplatform.v1.DeployedModel], and that need a /// higher degree of manual configuration. DedicatedResources = 1, /// Resources that to large degree are decided by AI Platform, and require /// only a modest additional configuration. AutomaticResources = 2, } } /// Contains the schemata used in Model's predictions and explanations via /// [PredictionService.Predict][google.cloud.aiplatform.v1.PredictionService.Predict], [PredictionService.Explain][] and /// [BatchPredictionJob][google.cloud.aiplatform.v1.BatchPredictionJob]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct PredictSchemata { /// Immutable. Points to a YAML file stored on Google Cloud Storage describing the format /// of a single instance, which are used in [PredictRequest.instances][google.cloud.aiplatform.v1.PredictRequest.instances], /// [ExplainRequest.instances][] and /// [BatchPredictionJob.input_config][google.cloud.aiplatform.v1.BatchPredictionJob.input_config]. /// The schema is defined as an OpenAPI 3.0.2 /// [Schema Object](https://tinyurl.com/y538mdwt#schema-object). /// AutoML Models always have this field populated by AI Platform. /// Note: The URI given on output will be immutable and probably different, /// including the URI scheme, than the one given on input. The output URI will /// point to a location where the user only has a read access. #[prost(string, tag = "1")] pub instance_schema_uri: ::prost::alloc::string::String, /// Immutable. Points to a YAML file stored on Google Cloud Storage describing the /// parameters of prediction and explanation via /// [PredictRequest.parameters][google.cloud.aiplatform.v1.PredictRequest.parameters], [ExplainRequest.parameters][] and /// [BatchPredictionJob.model_parameters][google.cloud.aiplatform.v1.BatchPredictionJob.model_parameters]. /// The schema is defined as an OpenAPI 3.0.2 /// [Schema Object](https://tinyurl.com/y538mdwt#schema-object). /// AutoML Models always have this field populated by AI Platform, if no /// parameters are supported, then it is set to an empty string. /// Note: The URI given on output will be immutable and probably different, /// including the URI scheme, than the one given on input. The output URI will /// point to a location where the user only has a read access. #[prost(string, tag = "2")] pub parameters_schema_uri: ::prost::alloc::string::String, /// Immutable. Points to a YAML file stored on Google Cloud Storage describing the format /// of a single prediction produced by this Model, which are returned via /// [PredictResponse.predictions][google.cloud.aiplatform.v1.PredictResponse.predictions], [ExplainResponse.explanations][], and /// [BatchPredictionJob.output_config][google.cloud.aiplatform.v1.BatchPredictionJob.output_config]. /// The schema is defined as an OpenAPI 3.0.2 /// [Schema Object](https://tinyurl.com/y538mdwt#schema-object). /// AutoML Models always have this field populated by AI Platform. /// Note: The URI given on output will be immutable and probably different, /// including the URI scheme, than the one given on input. The output URI will /// point to a location where the user only has a read access. #[prost(string, tag = "3")] pub prediction_schema_uri: ::prost::alloc::string::String, } /// Specification of a container for serving predictions. This message is a /// subset of the Kubernetes Container v1 core /// [specification](https://tinyurl.com/k8s-io-api/v1.18/#container-v1-core). #[derive(Clone, PartialEq, ::prost::Message)] pub struct ModelContainerSpec { /// Required. Immutable. URI of the Docker image to be used as the custom container for serving /// predictions. This URI must identify an image in Artifact Registry or /// Container Registry. Learn more about the container publishing /// requirements, including permissions requirements for the AI Platform /// Service Agent, /// [here](https://tinyurl.com/cust-cont-reqs#publishing). /// /// The container image is ingested upon [ModelService.UploadModel][google.cloud.aiplatform.v1.ModelService.UploadModel], stored /// internally, and this original path is afterwards not used. /// /// To learn about the requirements for the Docker image itself, see /// [Custom container requirements](https://tinyurl.com/cust-cont-reqs). #[prost(string, tag = "1")] pub image_uri: ::prost::alloc::string::String, /// Immutable. Specifies the command that runs when the container starts. This overrides /// the container's /// [ENTRYPOINT](https://docs.docker.com/engine/reference/builder/#entrypoint). /// Specify this field as an array of executable and arguments, similar to a /// Docker `ENTRYPOINT`'s "exec" form, not its "shell" form. /// /// If you do not specify this field, then the container's `ENTRYPOINT` runs, /// in conjunction with the [args][google.cloud.aiplatform.v1.ModelContainerSpec.args] field or the /// container's [`CMD`](https://docs.docker.com/engine/reference/builder/#cmd), /// if either exists. If this field is not specified and the container does not /// have an `ENTRYPOINT`, then refer to the Docker documentation about how /// `CMD` and `ENTRYPOINT` /// [interact](https://tinyurl.com/h3kdcgs). /// /// If you specify this field, then you can also specify the `args` field to /// provide additional arguments for this command. However, if you specify this /// field, then the container's `CMD` is ignored. See the /// [Kubernetes documentation](https://tinyurl.com/y8bvllf4) about how the /// `command` and `args` fields interact with a container's `ENTRYPOINT` and /// `CMD`. /// /// In this field, you can reference environment variables /// [set by AI Platform](https://tinyurl.com/cust-cont-reqs#aip-variables) /// and environment variables set in the [env][google.cloud.aiplatform.v1.ModelContainerSpec.env] field. /// You cannot reference environment variables set in the Docker image. In /// order for environment variables to be expanded, reference them by using the /// following syntax: /// <code>$(<var>VARIABLE_NAME</var>)</code> /// Note that this differs from Bash variable expansion, which does not use /// parentheses. If a variable cannot be resolved, the reference in the input /// string is used unchanged. To avoid variable expansion, you can escape this /// syntax with `$$`; for example: /// <code>$$(<var>VARIABLE_NAME</var>)</code> /// This field corresponds to the `command` field of the Kubernetes Containers /// [v1 core API](https://tinyurl.com/k8s-io-api/v1.18/#container-v1-core). #[prost(string, repeated, tag = "2")] pub command: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, /// Immutable. Specifies arguments for the command that runs when the container starts. /// This overrides the container's /// [`CMD`](https://docs.docker.com/engine/reference/builder/#cmd). Specify /// this field as an array of executable and arguments, similar to a Docker /// `CMD`'s "default parameters" form. /// /// If you don't specify this field but do specify the /// [command][google.cloud.aiplatform.v1.ModelContainerSpec.command] field, then the command from the /// `command` field runs without any additional arguments. See the /// [Kubernetes documentation](https://tinyurl.com/y8bvllf4) about how the /// `command` and `args` fields interact with a container's `ENTRYPOINT` and /// `CMD`. /// /// If you don't specify this field and don't specify the `command` field, /// then the container's /// [`ENTRYPOINT`](https://docs.docker.com/engine/reference/builder/#cmd) and /// `CMD` determine what runs based on their default behavior. See the Docker /// documentation about how `CMD` and `ENTRYPOINT` /// [interact](https://tinyurl.com/h3kdcgs). /// /// In this field, you can reference environment variables /// [set by AI Platform](https://tinyurl.com/cust-cont-reqs#aip-variables) /// and environment variables set in the [env][google.cloud.aiplatform.v1.ModelContainerSpec.env] field. /// You cannot reference environment variables set in the Docker image. In /// order for environment variables to be expanded, reference them by using the /// following syntax: /// <code>$(<var>VARIABLE_NAME</var>)</code> /// Note that this differs from Bash variable expansion, which does not use /// parentheses. If a variable cannot be resolved, the reference in the input /// string is used unchanged. To avoid variable expansion, you can escape this /// syntax with `$$`; for example: /// <code>$$(<var>VARIABLE_NAME</var>)</code> /// This field corresponds to the `args` field of the Kubernetes Containers /// [v1 core API](https://tinyurl.com/k8s-io-api/v1.18/#container-v1-core). #[prost(string, repeated, tag = "3")] pub args: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, /// Immutable. List of environment variables to set in the container. After the container /// starts running, code running in the container can read these environment /// variables. /// /// Additionally, the [command][google.cloud.aiplatform.v1.ModelContainerSpec.command] and /// [args][google.cloud.aiplatform.v1.ModelContainerSpec.args] fields can reference these variables. Later /// entries in this list can also reference earlier entries. For example, the /// following example sets the variable `VAR_2` to have the value `foo bar`: /// /// ```json /// [ /// { /// "name": "VAR_1", /// "value": "foo" /// }, /// { /// "name": "VAR_2", /// "value": "$(VAR_1) bar" /// } /// ] /// ``` /// /// If you switch the order of the variables in the example, then the expansion /// does not occur. /// /// This field corresponds to the `env` field of the Kubernetes Containers /// [v1 core API](https://tinyurl.com/k8s-io-api/v1.18/#container-v1-core). #[prost(message, repeated, tag = "4")] pub env: ::prost::alloc::vec::Vec<EnvVar>, /// Immutable. List of ports to expose from the container. AI Platform sends any /// prediction requests that it receives to the first port on this list. AI /// Platform also sends /// [liveness and health checks](https://tinyurl.com/cust-cont-reqs#health) /// to this port. /// /// If you do not specify this field, it defaults to following value: /// /// ```json /// [ /// { /// "containerPort": 8080 /// } /// ] /// ``` /// /// AI Platform does not use ports other than the first one listed. This field /// corresponds to the `ports` field of the Kubernetes Containers /// [v1 core API](https://tinyurl.com/k8s-io-api/v1.18/#container-v1-core). #[prost(message, repeated, tag = "5")] pub ports: ::prost::alloc::vec::Vec<Port>, /// Immutable. HTTP path on the container to send prediction requests to. AI Platform /// forwards requests sent using /// [projects.locations.endpoints.predict][google.cloud.aiplatform.v1.PredictionService.Predict] to this /// path on the container's IP address and port. AI Platform then returns the /// container's response in the API response. /// /// For example, if you set this field to `/foo`, then when AI Platform /// receives a prediction request, it forwards the request body in a POST /// request to the `/foo` path on the port of your container specified by the /// first value of this `ModelContainerSpec`'s /// [ports][google.cloud.aiplatform.v1.ModelContainerSpec.ports] field. /// /// If you don't specify this field, it defaults to the following value when /// you [deploy this Model to an Endpoint][google.cloud.aiplatform.v1.EndpointService.DeployModel]: /// <code>/v1/endpoints/<var>ENDPOINT</var>/deployedModels/<var>DEPLOYED_MODEL</var>:predict</code> /// The placeholders in this value are replaced as follows: /// /// * <var>ENDPOINT</var>: The last segment (following `endpoints/`)of the /// Endpoint.name][] field of the Endpoint where this Model has been /// deployed. (AI Platform makes this value available to your container code /// as the /// [`AIP_ENDPOINT_ID`](https://tinyurl.com/cust-cont-reqs#aip-variables) /// environment variable.) /// /// * <var>DEPLOYED_MODEL</var>: [DeployedModel.id][google.cloud.aiplatform.v1.DeployedModel.id] of the `DeployedModel`. /// (AI Platform makes this value available to your container code /// as the [`AIP_DEPLOYED_MODEL_ID` environment /// variable](https://tinyurl.com/cust-cont-reqs#aip-variables).) #[prost(string, tag = "6")] pub predict_route: ::prost::alloc::string::String, /// Immutable. HTTP path on the container to send health checks to. AI Platform /// intermittently sends GET requests to this path on the container's IP /// address and port to check that the container is healthy. Read more about /// [health /// checks](https://tinyurl.com/cust-cont-reqs#checks). /// /// For example, if you set this field to `/bar`, then AI Platform /// intermittently sends a GET request to the `/bar` path on the port of your /// container specified by the first value of this `ModelContainerSpec`'s /// [ports][google.cloud.aiplatform.v1.ModelContainerSpec.ports] field. /// /// If you don't specify this field, it defaults to the following value when /// you [deploy this Model to an Endpoint][google.cloud.aiplatform.v1.EndpointService.DeployModel]: /// <code>/v1/endpoints/<var>ENDPOINT</var>/deployedModels/<var>DEPLOYED_MODEL</var>:predict</code> /// The placeholders in this value are replaced as follows: /// /// * <var>ENDPOINT</var>: The last segment (following `endpoints/`)of the /// Endpoint.name][] field of the Endpoint where this Model has been /// deployed. (AI Platform makes this value available to your container code /// as the /// [`AIP_ENDPOINT_ID`](https://tinyurl.com/cust-cont-reqs#aip-variables) /// environment variable.) /// /// * <var>DEPLOYED_MODEL</var>: [DeployedModel.id][google.cloud.aiplatform.v1.DeployedModel.id] of the `DeployedModel`. /// (AI Platform makes this value available to your container code as the /// [`AIP_DEPLOYED_MODEL_ID`](https://tinyurl.com/cust-cont-reqs#aip-variables) /// environment variable.) #[prost(string, tag = "7")] pub health_route: ::prost::alloc::string::String, } /// Represents a network port in a container. #[derive(Clone, PartialEq, ::prost::Message)] pub struct Port { /// The number of the port to expose on the pod's IP address. /// Must be a valid port number, between 1 and 65535 inclusive. #[prost(int32, tag = "3")] pub container_port: i32, } /// Describes the state of a pipeline. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum PipelineState { /// The pipeline state is unspecified. Unspecified = 0, /// The pipeline has been just created or resumed and processing has not yet /// begun. Queued = 1, /// The service is preparing to run the pipeline. Pending = 2, /// The pipeline is in progress. Running = 3, /// The pipeline completed successfully. Succeeded = 4, /// The pipeline failed. Failed = 5, /// The pipeline is being cancelled. From this state the pipeline may only go /// to either PIPELINE_STATE_SUCCEEDED, PIPELINE_STATE_FAILED or /// PIPELINE_STATE_CANCELLED. Cancelling = 6, /// The pipeline has been cancelled. Cancelled = 7, /// The pipeline has been stopped, and can be resumed. Paused = 8, } /// The TrainingPipeline orchestrates tasks associated with training a Model. It /// always executes the training task, and optionally may also /// export data from AI Platform's Dataset which becomes the training input, /// [upload][google.cloud.aiplatform.v1.ModelService.UploadModel] the Model to AI Platform, and evaluate the /// Model. #[derive(Clone, PartialEq, ::prost::Message)] pub struct TrainingPipeline { /// Output only. Resource name of the TrainingPipeline. #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, /// Required. The user-defined name of this TrainingPipeline. #[prost(string, tag = "2")] pub display_name: ::prost::alloc::string::String, /// Specifies AI Platform owned input data that may be used for training the /// Model. The TrainingPipeline's [training_task_definition][google.cloud.aiplatform.v1.TrainingPipeline.training_task_definition] should make /// clear whether this config is used and if there are any special requirements /// on how it should be filled. If nothing about this config is mentioned in /// the [training_task_definition][google.cloud.aiplatform.v1.TrainingPipeline.training_task_definition], then it should be assumed that the /// TrainingPipeline does not depend on this configuration. #[prost(message, optional, tag = "3")] pub input_data_config: ::core::option::Option<InputDataConfig>, /// Required. A Google Cloud Storage path to the YAML file that defines the training task /// which is responsible for producing the model artifact, and may also include /// additional auxiliary work. /// The definition files that can be used here are found in /// gs://google-cloud-aiplatform/schema/trainingjob/definition/. /// Note: The URI given on output will be immutable and probably different, /// including the URI scheme, than the one given on input. The output URI will /// point to a location where the user only has a read access. #[prost(string, tag = "4")] pub training_task_definition: ::prost::alloc::string::String, /// Required. The training task's parameter(s), as specified in the /// [training_task_definition][google.cloud.aiplatform.v1.TrainingPipeline.training_task_definition]'s `inputs`. #[prost(message, optional, tag = "5")] pub training_task_inputs: ::core::option::Option<::prost_types::Value>, /// Output only. The metadata information as specified in the [training_task_definition][google.cloud.aiplatform.v1.TrainingPipeline.training_task_definition]'s /// `metadata`. This metadata is an auxiliary runtime and final information /// about the training task. While the pipeline is running this information is /// populated only at a best effort basis. Only present if the /// pipeline's [training_task_definition][google.cloud.aiplatform.v1.TrainingPipeline.training_task_definition] contains `metadata` object. #[prost(message, optional, tag = "6")] pub training_task_metadata: ::core::option::Option<::prost_types::Value>, /// Describes the Model that may be uploaded (via [ModelService.UploadModel][google.cloud.aiplatform.v1.ModelService.UploadModel]) /// by this TrainingPipeline. The TrainingPipeline's /// [training_task_definition][google.cloud.aiplatform.v1.TrainingPipeline.training_task_definition] should make clear whether this Model /// description should be populated, and if there are any special requirements /// regarding how it should be filled. If nothing is mentioned in the /// [training_task_definition][google.cloud.aiplatform.v1.TrainingPipeline.training_task_definition], then it should be assumed that this field /// should not be filled and the training task either uploads the Model without /// a need of this information, or that training task does not support /// uploading a Model as part of the pipeline. /// When the Pipeline's state becomes `PIPELINE_STATE_SUCCEEDED` and /// the trained Model had been uploaded into AI Platform, then the /// model_to_upload's resource [name][google.cloud.aiplatform.v1.Model.name] is populated. The Model /// is always uploaded into the Project and Location in which this pipeline /// is. #[prost(message, optional, tag = "7")] pub model_to_upload: ::core::option::Option<Model>, /// Output only. The detailed state of the pipeline. #[prost(enumeration = "PipelineState", tag = "9")] pub state: i32, /// Output only. Only populated when the pipeline's state is `PIPELINE_STATE_FAILED` or /// `PIPELINE_STATE_CANCELLED`. #[prost(message, optional, tag = "10")] pub error: ::core::option::Option<super::super::super::rpc::Status>, /// Output only. Time when the TrainingPipeline was created. #[prost(message, optional, tag = "11")] pub create_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. Time when the TrainingPipeline for the first time entered the /// `PIPELINE_STATE_RUNNING` state. #[prost(message, optional, tag = "12")] pub start_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. Time when the TrainingPipeline entered any of the following states: /// `PIPELINE_STATE_SUCCEEDED`, `PIPELINE_STATE_FAILED`, /// `PIPELINE_STATE_CANCELLED`. #[prost(message, optional, tag = "13")] pub end_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. Time when the TrainingPipeline was most recently updated. #[prost(message, optional, tag = "14")] pub update_time: ::core::option::Option<::prost_types::Timestamp>, /// The labels with user-defined metadata to organize TrainingPipelines. /// /// Label keys and values can be no longer than 64 characters /// (Unicode codepoints), can only contain lowercase letters, numeric /// characters, underscores and dashes. International characters are allowed. /// /// See https://goo.gl/xmQnxf for more information and examples of labels. #[prost(map = "string, string", tag = "15")] pub labels: ::std::collections::HashMap<::prost::alloc::string::String, ::prost::alloc::string::String>, /// Customer-managed encryption key spec for a TrainingPipeline. If set, this /// TrainingPipeline will be secured by this key. /// /// Note: Model trained by this TrainingPipeline is also secured by this key if /// [model_to_upload][google.cloud.aiplatform.v1.TrainingPipeline.encryption_spec] is not set separately. #[prost(message, optional, tag = "18")] pub encryption_spec: ::core::option::Option<EncryptionSpec>, } /// Specifies AI Platform owned input data to be used for training, and /// possibly evaluating, the Model. #[derive(Clone, PartialEq, ::prost::Message)] pub struct InputDataConfig { /// Required. The ID of the Dataset in the same Project and Location which data will be /// used to train the Model. The Dataset must use schema compatible with /// Model being trained, and what is compatible should be described in the /// used TrainingPipeline's [training_task_definition] /// [google.cloud.aiplatform.v1.TrainingPipeline.training_task_definition]. /// For tabular Datasets, all their data is exported to training, to pick /// and choose from. #[prost(string, tag = "1")] pub dataset_id: ::prost::alloc::string::String, /// Applicable only to Datasets that have DataItems and Annotations. /// /// A filter on Annotations of the Dataset. Only Annotations that both /// match this filter and belong to DataItems not ignored by the split method /// are used in respectively training, validation or test role, depending on /// the role of the DataItem they are on (for the auto-assigned that role is /// decided by AI Platform). A filter with same syntax as the one used in /// [ListAnnotations][google.cloud.aiplatform.v1.DatasetService.ListAnnotations] may be used, but note /// here it filters across all Annotations of the Dataset, and not just within /// a single DataItem. #[prost(string, tag = "6")] pub annotations_filter: ::prost::alloc::string::String, /// Applicable only to custom training with Datasets that have DataItems and /// Annotations. /// /// Cloud Storage URI that points to a YAML file describing the annotation /// schema. The schema is defined as an OpenAPI 3.0.2 /// [Schema Object](https://tinyurl.com/y538mdwt#schema-object). /// The schema files that can be used here are found in /// gs://google-cloud-aiplatform/schema/dataset/annotation/ , note that the /// chosen schema must be consistent with /// [metadata][google.cloud.aiplatform.v1.Dataset.metadata_schema_uri] of the Dataset specified by /// [dataset_id][google.cloud.aiplatform.v1.InputDataConfig.dataset_id]. /// /// Only Annotations that both match this schema and belong to DataItems not /// ignored by the split method are used in respectively training, validation /// or test role, depending on the role of the DataItem they are on. /// /// When used in conjunction with [annotations_filter][google.cloud.aiplatform.v1.InputDataConfig.annotations_filter], the Annotations used /// for training are filtered by both [annotations_filter][google.cloud.aiplatform.v1.InputDataConfig.annotations_filter] and /// [annotation_schema_uri][google.cloud.aiplatform.v1.InputDataConfig.annotation_schema_uri]. #[prost(string, tag = "9")] pub annotation_schema_uri: ::prost::alloc::string::String, /// The instructions how the input data should be split between the /// training, validation and test sets. /// If no split type is provided, the [fraction_split][google.cloud.aiplatform.v1.InputDataConfig.fraction_split] is used by default. #[prost(oneof = "input_data_config::Split", tags = "2, 3, 4, 5")] pub split: ::core::option::Option<input_data_config::Split>, /// Only applicable to Custom and Hyperparameter Tuning TrainingPipelines. /// /// The destination of the training data to be written to. /// /// Supported destination file formats: /// * For non-tabular data: "jsonl". /// * For tabular data: "csv" and "bigquery". /// /// The following AI Platform environment variables are passed to containers /// or python modules of the training task when this field is set: /// /// * AIP_DATA_FORMAT : Exported data format. /// * AIP_TRAINING_DATA_URI : Sharded exported training data uris. /// * AIP_VALIDATION_DATA_URI : Sharded exported validation data uris. /// * AIP_TEST_DATA_URI : Sharded exported test data uris. #[prost(oneof = "input_data_config::Destination", tags = "8, 10")] pub destination: ::core::option::Option<input_data_config::Destination>, } /// Nested message and enum types in `InputDataConfig`. pub mod input_data_config { /// The instructions how the input data should be split between the /// training, validation and test sets. /// If no split type is provided, the [fraction_split][google.cloud.aiplatform.v1.InputDataConfig.fraction_split] is used by default. #[derive(Clone, PartialEq, ::prost::Oneof)] pub enum Split { /// Split based on fractions defining the size of each set. #[prost(message, tag = "2")] FractionSplit(super::FractionSplit), /// Split based on the provided filters for each set. #[prost(message, tag = "3")] FilterSplit(super::FilterSplit), /// Supported only for tabular Datasets. /// /// Split based on a predefined key. #[prost(message, tag = "4")] PredefinedSplit(super::PredefinedSplit), /// Supported only for tabular Datasets. /// /// Split based on the timestamp of the input data pieces. #[prost(message, tag = "5")] TimestampSplit(super::TimestampSplit), } /// Only applicable to Custom and Hyperparameter Tuning TrainingPipelines. /// /// The destination of the training data to be written to. /// /// Supported destination file formats: /// * For non-tabular data: "jsonl". /// * For tabular data: "csv" and "bigquery". /// /// The following AI Platform environment variables are passed to containers /// or python modules of the training task when this field is set: /// /// * AIP_DATA_FORMAT : Exported data format. /// * AIP_TRAINING_DATA_URI : Sharded exported training data uris. /// * AIP_VALIDATION_DATA_URI : Sharded exported validation data uris. /// * AIP_TEST_DATA_URI : Sharded exported test data uris. #[derive(Clone, PartialEq, ::prost::Oneof)] pub enum Destination { /// The Cloud Storage location where the training data is to be /// written to. In the given directory a new directory is created with /// name: /// `dataset-<dataset-id>-<annotation-type>-<timestamp-of-training-call>` /// where timestamp is in YYYY-MM-DDThh:mm:ss.sssZ ISO-8601 format. /// All training input data is written into that directory. /// /// The AI Platform environment variables representing Cloud Storage /// data URIs are represented in the Cloud Storage wildcard /// format to support sharded data. e.g.: "gs://.../training-*.jsonl" /// /// * AIP_DATA_FORMAT = "jsonl" for non-tabular data, "csv" for tabular data /// * AIP_TRAINING_DATA_URI = /// /// "gcs_destination/dataset-<dataset-id>-<annotation-type>-<time>/training-*.${AIP_DATA_FORMAT}" /// /// * AIP_VALIDATION_DATA_URI = /// /// "gcs_destination/dataset-<dataset-id>-<annotation-type>-<time>/validation-*.${AIP_DATA_FORMAT}" /// /// * AIP_TEST_DATA_URI = /// /// "gcs_destination/dataset-<dataset-id>-<annotation-type>-<time>/test-*.${AIP_DATA_FORMAT}" #[prost(message, tag = "8")] GcsDestination(super::GcsDestination), /// Only applicable to custom training with tabular Dataset with BigQuery /// source. /// /// The BigQuery project location where the training data is to be written /// to. In the given project a new dataset is created with name /// `dataset_<dataset-id>_<annotation-type>_<timestamp-of-training-call>` /// where timestamp is in YYYY_MM_DDThh_mm_ss_sssZ format. All training /// input data is written into that dataset. In the dataset three /// tables are created, `training`, `validation` and `test`. /// /// * AIP_DATA_FORMAT = "bigquery". /// * AIP_TRAINING_DATA_URI = /// /// "bigquery_destination.dataset_<dataset-id>_<annotation-type>_<time>.training" /// /// * AIP_VALIDATION_DATA_URI = /// /// "bigquery_destination.dataset_<dataset-id>_<annotation-type>_<time>.validation" /// /// * AIP_TEST_DATA_URI = /// "bigquery_destination.dataset_<dataset-id>_<annotation-type>_<time>.test" #[prost(message, tag = "10")] BigqueryDestination(super::BigQueryDestination), } } /// Assigns the input data to training, validation, and test sets as per the /// given fractions. Any of `training_fraction`, `validation_fraction` and /// `test_fraction` may optionally be provided, they must sum to up to 1. If the /// provided ones sum to less than 1, the remainder is assigned to sets as /// decided by AI Platform. If none of the fractions are set, by default roughly /// 80% of data is used for training, 10% for validation, and 10% for test. #[derive(Clone, PartialEq, ::prost::Message)] pub struct FractionSplit { /// The fraction of the input data that is to be used to train the Model. #[prost(double, tag = "1")] pub training_fraction: f64, /// The fraction of the input data that is to be used to validate the Model. #[prost(double, tag = "2")] pub validation_fraction: f64, /// The fraction of the input data that is to be used to evaluate the Model. #[prost(double, tag = "3")] pub test_fraction: f64, } /// Assigns input data to training, validation, and test sets based on the given /// filters, data pieces not matched by any filter are ignored. Currently only /// supported for Datasets containing DataItems. /// If any of the filters in this message are to match nothing, then they can be /// set as '-' (the minus sign). /// /// Supported only for unstructured Datasets. /// #[derive(Clone, PartialEq, ::prost::Message)] pub struct FilterSplit { /// Required. A filter on DataItems of the Dataset. DataItems that match /// this filter are used to train the Model. A filter with same syntax /// as the one used in [DatasetService.ListDataItems][google.cloud.aiplatform.v1.DatasetService.ListDataItems] may be used. If a /// single DataItem is matched by more than one of the FilterSplit filters, /// then it is assigned to the first set that applies to it in the /// training, validation, test order. #[prost(string, tag = "1")] pub training_filter: ::prost::alloc::string::String, /// Required. A filter on DataItems of the Dataset. DataItems that match /// this filter are used to validate the Model. A filter with same syntax /// as the one used in [DatasetService.ListDataItems][google.cloud.aiplatform.v1.DatasetService.ListDataItems] may be used. If a /// single DataItem is matched by more than one of the FilterSplit filters, /// then it is assigned to the first set that applies to it in the /// training, validation, test order. #[prost(string, tag = "2")] pub validation_filter: ::prost::alloc::string::String, /// Required. A filter on DataItems of the Dataset. DataItems that match /// this filter are used to test the Model. A filter with same syntax /// as the one used in [DatasetService.ListDataItems][google.cloud.aiplatform.v1.DatasetService.ListDataItems] may be used. If a /// single DataItem is matched by more than one of the FilterSplit filters, /// then it is assigned to the first set that applies to it in the /// training, validation, test order. #[prost(string, tag = "3")] pub test_filter: ::prost::alloc::string::String, } /// Assigns input data to training, validation, and test sets based on the /// value of a provided key. /// /// Supported only for tabular Datasets. #[derive(Clone, PartialEq, ::prost::Message)] pub struct PredefinedSplit { /// Required. The key is a name of one of the Dataset's data columns. /// The value of the key (either the label's value or value in the column) /// must be one of {`training`, `validation`, `test`}, and it defines to which /// set the given piece of data is assigned. If for a piece of data the key /// is not present or has an invalid value, that piece is ignored by the /// pipeline. #[prost(string, tag = "1")] pub key: ::prost::alloc::string::String, } /// Assigns input data to training, validation, and test sets based on a /// provided timestamps. The youngest data pieces are assigned to training set, /// next to validation set, and the oldest to the test set. /// /// Supported only for tabular Datasets. #[derive(Clone, PartialEq, ::prost::Message)] pub struct TimestampSplit { /// The fraction of the input data that is to be used to train the Model. #[prost(double, tag = "1")] pub training_fraction: f64, /// The fraction of the input data that is to be used to validate the Model. #[prost(double, tag = "2")] pub validation_fraction: f64, /// The fraction of the input data that is to be used to evaluate the Model. #[prost(double, tag = "3")] pub test_fraction: f64, /// Required. The key is a name of one of the Dataset's data columns. /// The values of the key (the values in the column) must be in RFC 3339 /// `date-time` format, where `time-offset` = `"Z"` /// (e.g. 1985-04-12T23:20:50.52Z). If for a piece of data the key is not /// present or has an invalid value, that piece is ignored by the pipeline. #[prost(string, tag = "4")] pub key: ::prost::alloc::string::String, } /// Request message for [DatasetService.CreateDataset][google.cloud.aiplatform.v1.DatasetService.CreateDataset]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct CreateDatasetRequest { /// Required. The resource name of the Location to create the Dataset in. /// Format: `projects/{project}/locations/{location}` #[prost(string, tag = "1")] pub parent: ::prost::alloc::string::String, /// Required. The Dataset to create. #[prost(message, optional, tag = "2")] pub dataset: ::core::option::Option<Dataset>, } /// Runtime operation information for [DatasetService.CreateDataset][google.cloud.aiplatform.v1.DatasetService.CreateDataset]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct CreateDatasetOperationMetadata { /// The operation generic information. #[prost(message, optional, tag = "1")] pub generic_metadata: ::core::option::Option<GenericOperationMetadata>, } /// Request message for [DatasetService.GetDataset][google.cloud.aiplatform.v1.DatasetService.GetDataset]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct GetDatasetRequest { /// Required. The name of the Dataset resource. #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, /// Mask specifying which fields to read. #[prost(message, optional, tag = "2")] pub read_mask: ::core::option::Option<::prost_types::FieldMask>, } /// Request message for [DatasetService.UpdateDataset][google.cloud.aiplatform.v1.DatasetService.UpdateDataset]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct UpdateDatasetRequest { /// Required. The Dataset which replaces the resource on the server. #[prost(message, optional, tag = "1")] pub dataset: ::core::option::Option<Dataset>, /// Required. The update mask applies to the resource. /// For the `FieldMask` definition, see /// [FieldMask](https://tinyurl.com/protobufs/google.protobuf#fieldmask). /// Updatable fields: /// /// * `display_name` /// * `description` /// * `labels` #[prost(message, optional, tag = "2")] pub update_mask: ::core::option::Option<::prost_types::FieldMask>, } /// Request message for [DatasetService.ListDatasets][google.cloud.aiplatform.v1.DatasetService.ListDatasets]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListDatasetsRequest { /// Required. The name of the Dataset's parent resource. /// Format: `projects/{project}/locations/{location}` #[prost(string, tag = "1")] pub parent: ::prost::alloc::string::String, /// An expression for filtering the results of the request. For field names /// both snake_case and camelCase are supported. /// /// * `display_name`: supports = and != /// * `metadata_schema_uri`: supports = and != /// * `labels` supports general map functions that is: /// * `labels.key=value` - key:value equality /// * `labels.key:* or labels:key - key existence /// * A key including a space must be quoted. `labels."a key"`. /// /// Some examples: /// * `displayName="myDisplayName"` /// * `labels.myKey="myValue"` #[prost(string, tag = "2")] pub filter: ::prost::alloc::string::String, /// The standard list page size. #[prost(int32, tag = "3")] pub page_size: i32, /// The standard list page token. #[prost(string, tag = "4")] pub page_token: ::prost::alloc::string::String, /// Mask specifying which fields to read. #[prost(message, optional, tag = "5")] pub read_mask: ::core::option::Option<::prost_types::FieldMask>, /// A comma-separated list of fields to order by, sorted in ascending order. /// Use "desc" after a field name for descending. /// Supported fields: /// * `display_name` /// * `create_time` /// * `update_time` #[prost(string, tag = "6")] pub order_by: ::prost::alloc::string::String, } /// Response message for [DatasetService.ListDatasets][google.cloud.aiplatform.v1.DatasetService.ListDatasets]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListDatasetsResponse { /// A list of Datasets that matches the specified filter in the request. #[prost(message, repeated, tag = "1")] pub datasets: ::prost::alloc::vec::Vec<Dataset>, /// The standard List next-page token. #[prost(string, tag = "2")] pub next_page_token: ::prost::alloc::string::String, } /// Request message for [DatasetService.DeleteDataset][google.cloud.aiplatform.v1.DatasetService.DeleteDataset]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DeleteDatasetRequest { /// Required. The resource name of the Dataset to delete. /// Format: /// `projects/{project}/locations/{location}/datasets/{dataset}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, } /// Request message for [DatasetService.ImportData][google.cloud.aiplatform.v1.DatasetService.ImportData]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ImportDataRequest { /// Required. The name of the Dataset resource. /// Format: /// `projects/{project}/locations/{location}/datasets/{dataset}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, /// Required. The desired input locations. The contents of all input locations will be /// imported in one batch. #[prost(message, repeated, tag = "2")] pub import_configs: ::prost::alloc::vec::Vec<ImportDataConfig>, } /// Response message for [DatasetService.ImportData][google.cloud.aiplatform.v1.DatasetService.ImportData]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ImportDataResponse {} /// Runtime operation information for [DatasetService.ImportData][google.cloud.aiplatform.v1.DatasetService.ImportData]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ImportDataOperationMetadata { /// The common part of the operation metadata. #[prost(message, optional, tag = "1")] pub generic_metadata: ::core::option::Option<GenericOperationMetadata>, } /// Request message for [DatasetService.ExportData][google.cloud.aiplatform.v1.DatasetService.ExportData]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ExportDataRequest { /// Required. The name of the Dataset resource. /// Format: /// `projects/{project}/locations/{location}/datasets/{dataset}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, /// Required. The desired output location. #[prost(message, optional, tag = "2")] pub export_config: ::core::option::Option<ExportDataConfig>, } /// Response message for [DatasetService.ExportData][google.cloud.aiplatform.v1.DatasetService.ExportData]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ExportDataResponse { /// All of the files that are exported in this export operation. #[prost(string, repeated, tag = "1")] pub exported_files: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, } /// Runtime operation information for [DatasetService.ExportData][google.cloud.aiplatform.v1.DatasetService.ExportData]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ExportDataOperationMetadata { /// The common part of the operation metadata. #[prost(message, optional, tag = "1")] pub generic_metadata: ::core::option::Option<GenericOperationMetadata>, /// A Google Cloud Storage directory which path ends with '/'. The exported /// data is stored in the directory. #[prost(string, tag = "2")] pub gcs_output_directory: ::prost::alloc::string::String, } /// Request message for [DatasetService.ListDataItems][google.cloud.aiplatform.v1.DatasetService.ListDataItems]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListDataItemsRequest { /// Required. The resource name of the Dataset to list DataItems from. /// Format: /// `projects/{project}/locations/{location}/datasets/{dataset}` #[prost(string, tag = "1")] pub parent: ::prost::alloc::string::String, /// The standard list filter. #[prost(string, tag = "2")] pub filter: ::prost::alloc::string::String, /// The standard list page size. #[prost(int32, tag = "3")] pub page_size: i32, /// The standard list page token. #[prost(string, tag = "4")] pub page_token: ::prost::alloc::string::String, /// Mask specifying which fields to read. #[prost(message, optional, tag = "5")] pub read_mask: ::core::option::Option<::prost_types::FieldMask>, /// A comma-separated list of fields to order by, sorted in ascending order. /// Use "desc" after a field name for descending. #[prost(string, tag = "6")] pub order_by: ::prost::alloc::string::String, } /// Response message for [DatasetService.ListDataItems][google.cloud.aiplatform.v1.DatasetService.ListDataItems]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListDataItemsResponse { /// A list of DataItems that matches the specified filter in the request. #[prost(message, repeated, tag = "1")] pub data_items: ::prost::alloc::vec::Vec<DataItem>, /// The standard List next-page token. #[prost(string, tag = "2")] pub next_page_token: ::prost::alloc::string::String, } /// Request message for [DatasetService.GetAnnotationSpec][google.cloud.aiplatform.v1.DatasetService.GetAnnotationSpec]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct GetAnnotationSpecRequest { /// Required. The name of the AnnotationSpec resource. /// Format: /// /// `projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, /// Mask specifying which fields to read. #[prost(message, optional, tag = "2")] pub read_mask: ::core::option::Option<::prost_types::FieldMask>, } /// Request message for [DatasetService.ListAnnotations][google.cloud.aiplatform.v1.DatasetService.ListAnnotations]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListAnnotationsRequest { /// Required. The resource name of the DataItem to list Annotations from. /// Format: /// /// `projects/{project}/locations/{location}/datasets/{dataset}/dataItems/{data_item}` #[prost(string, tag = "1")] pub parent: ::prost::alloc::string::String, /// The standard list filter. #[prost(string, tag = "2")] pub filter: ::prost::alloc::string::String, /// The standard list page size. #[prost(int32, tag = "3")] pub page_size: i32, /// The standard list page token. #[prost(string, tag = "4")] pub page_token: ::prost::alloc::string::String, /// Mask specifying which fields to read. #[prost(message, optional, tag = "5")] pub read_mask: ::core::option::Option<::prost_types::FieldMask>, /// A comma-separated list of fields to order by, sorted in ascending order. /// Use "desc" after a field name for descending. #[prost(string, tag = "6")] pub order_by: ::prost::alloc::string::String, } /// Response message for [DatasetService.ListAnnotations][google.cloud.aiplatform.v1.DatasetService.ListAnnotations]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListAnnotationsResponse { /// A list of Annotations that matches the specified filter in the request. #[prost(message, repeated, tag = "1")] pub annotations: ::prost::alloc::vec::Vec<Annotation>, /// The standard List next-page token. #[prost(string, tag = "2")] pub next_page_token: ::prost::alloc::string::String, } #[doc = r" Generated client implementations."] pub mod dataset_service_client { #![allow(unused_variables, dead_code, missing_docs)] use tonic::codegen::*; pub struct DatasetServiceClient<T> { inner: tonic::client::Grpc<T>, } impl<T> DatasetServiceClient<T> where T: tonic::client::GrpcService<tonic::body::BoxBody>, T::ResponseBody: Body + HttpBody + Send + 'static, T::Error: Into<StdError>, <T::ResponseBody as HttpBody>::Error: Into<StdError> + Send, { pub fn new(inner: T) -> Self { let inner = tonic::client::Grpc::new(inner); Self { inner } } pub fn with_interceptor(inner: T, interceptor: impl Into<tonic::Interceptor>) -> Self { let inner = tonic::client::Grpc::with_interceptor(inner, interceptor); Self { inner } } #[doc = " Creates a Dataset."] pub async fn create_dataset( &mut self, request: impl tonic::IntoRequest<super::CreateDatasetRequest>, ) -> Result< tonic::Response<super::super::super::super::longrunning::Operation>, tonic::Status, > { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.DatasetService/CreateDataset", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Gets a Dataset."] pub async fn get_dataset( &mut self, request: impl tonic::IntoRequest<super::GetDatasetRequest>, ) -> Result<tonic::Response<super::Dataset>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.DatasetService/GetDataset", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Updates a Dataset."] pub async fn update_dataset( &mut self, request: impl tonic::IntoRequest<super::UpdateDatasetRequest>, ) -> Result<tonic::Response<super::Dataset>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.DatasetService/UpdateDataset", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Lists Datasets in a Location."] pub async fn list_datasets( &mut self, request: impl tonic::IntoRequest<super::ListDatasetsRequest>, ) -> Result<tonic::Response<super::ListDatasetsResponse>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.DatasetService/ListDatasets", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Deletes a Dataset."] pub async fn delete_dataset( &mut self, request: impl tonic::IntoRequest<super::DeleteDatasetRequest>, ) -> Result< tonic::Response<super::super::super::super::longrunning::Operation>, tonic::Status, > { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.DatasetService/DeleteDataset", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Imports data into a Dataset."] pub async fn import_data( &mut self, request: impl tonic::IntoRequest<super::ImportDataRequest>, ) -> Result< tonic::Response<super::super::super::super::longrunning::Operation>, tonic::Status, > { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.DatasetService/ImportData", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Exports data from a Dataset."] pub async fn export_data( &mut self, request: impl tonic::IntoRequest<super::ExportDataRequest>, ) -> Result< tonic::Response<super::super::super::super::longrunning::Operation>, tonic::Status, > { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.DatasetService/ExportData", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Lists DataItems in a Dataset."] pub async fn list_data_items( &mut self, request: impl tonic::IntoRequest<super::ListDataItemsRequest>, ) -> Result<tonic::Response<super::ListDataItemsResponse>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.DatasetService/ListDataItems", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Gets an AnnotationSpec."] pub async fn get_annotation_spec( &mut self, request: impl tonic::IntoRequest<super::GetAnnotationSpecRequest>, ) -> Result<tonic::Response<super::AnnotationSpec>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.DatasetService/GetAnnotationSpec", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Lists Annotations belongs to a dataitem"] pub async fn list_annotations( &mut self, request: impl tonic::IntoRequest<super::ListAnnotationsRequest>, ) -> Result<tonic::Response<super::ListAnnotationsResponse>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.DatasetService/ListAnnotations", ); self.inner.unary(request.into_request(), path, codec).await } } impl<T: Clone> Clone for DatasetServiceClient<T> { fn clone(&self) -> Self { Self { inner: self.inner.clone(), } } } impl<T> std::fmt::Debug for DatasetServiceClient<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "DatasetServiceClient {{ ... }}") } } } /// Models are deployed into it, and afterwards Endpoint is called to obtain /// predictions and explanations. #[derive(Clone, PartialEq, ::prost::Message)] pub struct Endpoint { /// Output only. The resource name of the Endpoint. #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, /// Required. The display name of the Endpoint. /// The name can be up to 128 characters long and can be consist of any UTF-8 /// characters. #[prost(string, tag = "2")] pub display_name: ::prost::alloc::string::String, /// The description of the Endpoint. #[prost(string, tag = "3")] pub description: ::prost::alloc::string::String, /// Output only. The models deployed in this Endpoint. /// To add or remove DeployedModels use [EndpointService.DeployModel][google.cloud.aiplatform.v1.EndpointService.DeployModel] and /// [EndpointService.UndeployModel][google.cloud.aiplatform.v1.EndpointService.UndeployModel] respectively. #[prost(message, repeated, tag = "4")] pub deployed_models: ::prost::alloc::vec::Vec<DeployedModel>, /// A map from a DeployedModel's ID to the percentage of this Endpoint's /// traffic that should be forwarded to that DeployedModel. /// /// If a DeployedModel's ID is not listed in this map, then it receives no /// traffic. /// /// The traffic percentage values must add up to 100, or map must be empty if /// the Endpoint is to not accept any traffic at a moment. #[prost(map = "string, int32", tag = "5")] pub traffic_split: ::std::collections::HashMap<::prost::alloc::string::String, i32>, /// Used to perform consistent read-modify-write updates. If not set, a blind /// "overwrite" update happens. #[prost(string, tag = "6")] pub etag: ::prost::alloc::string::String, /// The labels with user-defined metadata to organize your Endpoints. /// /// Label keys and values can be no longer than 64 characters /// (Unicode codepoints), can only contain lowercase letters, numeric /// characters, underscores and dashes. International characters are allowed. /// /// See https://goo.gl/xmQnxf for more information and examples of labels. #[prost(map = "string, string", tag = "7")] pub labels: ::std::collections::HashMap<::prost::alloc::string::String, ::prost::alloc::string::String>, /// Output only. Timestamp when this Endpoint was created. #[prost(message, optional, tag = "8")] pub create_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. Timestamp when this Endpoint was last updated. #[prost(message, optional, tag = "9")] pub update_time: ::core::option::Option<::prost_types::Timestamp>, /// Customer-managed encryption key spec for an Endpoint. If set, this /// Endpoint and all sub-resources of this Endpoint will be secured by /// this key. #[prost(message, optional, tag = "10")] pub encryption_spec: ::core::option::Option<EncryptionSpec>, } /// A deployment of a Model. Endpoints contain one or more DeployedModels. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DeployedModel { /// Output only. The ID of the DeployedModel. #[prost(string, tag = "1")] pub id: ::prost::alloc::string::String, /// Required. The name of the Model that this is the deployment of. Note that the Model /// may be in a different location than the DeployedModel's Endpoint. #[prost(string, tag = "2")] pub model: ::prost::alloc::string::String, /// The display name of the DeployedModel. If not provided upon creation, /// the Model's display_name is used. #[prost(string, tag = "3")] pub display_name: ::prost::alloc::string::String, /// Output only. Timestamp when the DeployedModel was created. #[prost(message, optional, tag = "6")] pub create_time: ::core::option::Option<::prost_types::Timestamp>, /// The service account that the DeployedModel's container runs as. Specify the /// email address of the service account. If this service account is not /// specified, the container runs as a service account that doesn't have access /// to the resource project. /// /// Users deploying the Model must have the `iam.serviceAccounts.actAs` /// permission on this service account. #[prost(string, tag = "11")] pub service_account: ::prost::alloc::string::String, /// For custom-trained Models and AutoML Tabular Models, the container of the /// DeployedModel instances will send `stderr` and `stdout` streams to /// Stackdriver Logging by default. Please note that the logs incur cost, /// which are subject to [Cloud Logging /// pricing](https://cloud.google.com/stackdriver/pricing). /// /// User can disable container logging by setting this flag to true. #[prost(bool, tag = "15")] pub disable_container_logging: bool, /// These logs are like standard server access logs, containing /// information like timestamp and latency for each prediction request. /// /// Note that Stackdriver logs may incur a cost, especially if your project /// receives prediction requests at a high queries per second rate (QPS). /// Estimate your costs before enabling this option. #[prost(bool, tag = "13")] pub enable_access_logging: bool, /// The prediction (for example, the machine) resources that the DeployedModel /// uses. The user is billed for the resources (at least their minimal amount) /// even if the DeployedModel receives no traffic. /// Not all Models support all resources types. See /// [Model.supported_deployment_resources_types][google.cloud.aiplatform.v1.Model.supported_deployment_resources_types]. #[prost(oneof = "deployed_model::PredictionResources", tags = "7, 8")] pub prediction_resources: ::core::option::Option<deployed_model::PredictionResources>, } /// Nested message and enum types in `DeployedModel`. pub mod deployed_model { /// The prediction (for example, the machine) resources that the DeployedModel /// uses. The user is billed for the resources (at least their minimal amount) /// even if the DeployedModel receives no traffic. /// Not all Models support all resources types. See /// [Model.supported_deployment_resources_types][google.cloud.aiplatform.v1.Model.supported_deployment_resources_types]. #[derive(Clone, PartialEq, ::prost::Oneof)] pub enum PredictionResources { /// A description of resources that are dedicated to the DeployedModel, and /// that need a higher degree of manual configuration. #[prost(message, tag = "7")] DedicatedResources(super::DedicatedResources), /// A description of resources that to large degree are decided by AI /// Platform, and require only a modest additional configuration. #[prost(message, tag = "8")] AutomaticResources(super::AutomaticResources), } } /// Request message for [EndpointService.CreateEndpoint][google.cloud.aiplatform.v1.EndpointService.CreateEndpoint]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct CreateEndpointRequest { /// Required. The resource name of the Location to create the Endpoint in. /// Format: `projects/{project}/locations/{location}` #[prost(string, tag = "1")] pub parent: ::prost::alloc::string::String, /// Required. The Endpoint to create. #[prost(message, optional, tag = "2")] pub endpoint: ::core::option::Option<Endpoint>, } /// Runtime operation information for [EndpointService.CreateEndpoint][google.cloud.aiplatform.v1.EndpointService.CreateEndpoint]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct CreateEndpointOperationMetadata { /// The operation generic information. #[prost(message, optional, tag = "1")] pub generic_metadata: ::core::option::Option<GenericOperationMetadata>, } /// Request message for [EndpointService.GetEndpoint][google.cloud.aiplatform.v1.EndpointService.GetEndpoint] #[derive(Clone, PartialEq, ::prost::Message)] pub struct GetEndpointRequest { /// Required. The name of the Endpoint resource. /// Format: /// `projects/{project}/locations/{location}/endpoints/{endpoint}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, } /// Request message for [EndpointService.ListEndpoints][google.cloud.aiplatform.v1.EndpointService.ListEndpoints]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListEndpointsRequest { /// Required. The resource name of the Location from which to list the Endpoints. /// Format: `projects/{project}/locations/{location}` #[prost(string, tag = "1")] pub parent: ::prost::alloc::string::String, /// Optional. An expression for filtering the results of the request. For field names /// both snake_case and camelCase are supported. /// /// * `endpoint` supports = and !=. `endpoint` represents the Endpoint ID, /// i.e. the last segment of the Endpoint's [resource name][google.cloud.aiplatform.v1.Endpoint.name]. /// * `display_name` supports = and, != /// * `labels` supports general map functions that is: /// * `labels.key=value` - key:value equality /// * `labels.key:* or labels:key - key existence /// * A key including a space must be quoted. `labels."a key"`. /// /// Some examples: /// * `endpoint=1` /// * `displayName="myDisplayName"` /// * `labels.myKey="myValue"` #[prost(string, tag = "2")] pub filter: ::prost::alloc::string::String, /// Optional. The standard list page size. #[prost(int32, tag = "3")] pub page_size: i32, /// Optional. The standard list page token. /// Typically obtained via /// [ListEndpointsResponse.next_page_token][google.cloud.aiplatform.v1.ListEndpointsResponse.next_page_token] of the previous /// [EndpointService.ListEndpoints][google.cloud.aiplatform.v1.EndpointService.ListEndpoints] call. #[prost(string, tag = "4")] pub page_token: ::prost::alloc::string::String, /// Optional. Mask specifying which fields to read. #[prost(message, optional, tag = "5")] pub read_mask: ::core::option::Option<::prost_types::FieldMask>, /// A comma-separated list of fields to order by, sorted in ascending order. /// Use "desc" after a field name for descending. /// Supported fields: /// * `display_name` /// * `create_time` /// * `update_time` /// /// Example: `display_name, create_time desc`. #[prost(string, tag = "6")] pub order_by: ::prost::alloc::string::String, } /// Response message for [EndpointService.ListEndpoints][google.cloud.aiplatform.v1.EndpointService.ListEndpoints]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListEndpointsResponse { /// List of Endpoints in the requested page. #[prost(message, repeated, tag = "1")] pub endpoints: ::prost::alloc::vec::Vec<Endpoint>, /// A token to retrieve the next page of results. /// Pass to [ListEndpointsRequest.page_token][google.cloud.aiplatform.v1.ListEndpointsRequest.page_token] to obtain that page. #[prost(string, tag = "2")] pub next_page_token: ::prost::alloc::string::String, } /// Request message for [EndpointService.UpdateEndpoint][google.cloud.aiplatform.v1.EndpointService.UpdateEndpoint]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct UpdateEndpointRequest { /// Required. The Endpoint which replaces the resource on the server. #[prost(message, optional, tag = "1")] pub endpoint: ::core::option::Option<Endpoint>, /// Required. The update mask applies to the resource. /// See /// [FieldMask](https://tinyurl.com/protobufs/google.protobuf#fieldmask). #[prost(message, optional, tag = "2")] pub update_mask: ::core::option::Option<::prost_types::FieldMask>, } /// Request message for [EndpointService.DeleteEndpoint][google.cloud.aiplatform.v1.EndpointService.DeleteEndpoint]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DeleteEndpointRequest { /// Required. The name of the Endpoint resource to be deleted. /// Format: /// `projects/{project}/locations/{location}/endpoints/{endpoint}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, } /// Request message for [EndpointService.DeployModel][google.cloud.aiplatform.v1.EndpointService.DeployModel]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DeployModelRequest { /// Required. The name of the Endpoint resource into which to deploy a Model. /// Format: /// `projects/{project}/locations/{location}/endpoints/{endpoint}` #[prost(string, tag = "1")] pub endpoint: ::prost::alloc::string::String, /// Required. The DeployedModel to be created within the Endpoint. Note that /// [Endpoint.traffic_split][google.cloud.aiplatform.v1.Endpoint.traffic_split] must be updated for the DeployedModel to start /// receiving traffic, either as part of this call, or via /// [EndpointService.UpdateEndpoint][google.cloud.aiplatform.v1.EndpointService.UpdateEndpoint]. #[prost(message, optional, tag = "2")] pub deployed_model: ::core::option::Option<DeployedModel>, /// A map from a DeployedModel's ID to the percentage of this Endpoint's /// traffic that should be forwarded to that DeployedModel. /// /// If this field is non-empty, then the Endpoint's /// [traffic_split][google.cloud.aiplatform.v1.Endpoint.traffic_split] will be overwritten with it. /// To refer to the ID of the just being deployed Model, a "0" should be used, /// and the actual ID of the new DeployedModel will be filled in its place by /// this method. The traffic percentage values must add up to 100. /// /// If this field is empty, then the Endpoint's /// [traffic_split][google.cloud.aiplatform.v1.Endpoint.traffic_split] is not updated. #[prost(map = "string, int32", tag = "3")] pub traffic_split: ::std::collections::HashMap<::prost::alloc::string::String, i32>, } /// Response message for [EndpointService.DeployModel][google.cloud.aiplatform.v1.EndpointService.DeployModel]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DeployModelResponse { /// The DeployedModel that had been deployed in the Endpoint. #[prost(message, optional, tag = "1")] pub deployed_model: ::core::option::Option<DeployedModel>, } /// Runtime operation information for [EndpointService.DeployModel][google.cloud.aiplatform.v1.EndpointService.DeployModel]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DeployModelOperationMetadata { /// The operation generic information. #[prost(message, optional, tag = "1")] pub generic_metadata: ::core::option::Option<GenericOperationMetadata>, } /// Request message for [EndpointService.UndeployModel][google.cloud.aiplatform.v1.EndpointService.UndeployModel]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct UndeployModelRequest { /// Required. The name of the Endpoint resource from which to undeploy a Model. /// Format: /// `projects/{project}/locations/{location}/endpoints/{endpoint}` #[prost(string, tag = "1")] pub endpoint: ::prost::alloc::string::String, /// Required. The ID of the DeployedModel to be undeployed from the Endpoint. #[prost(string, tag = "2")] pub deployed_model_id: ::prost::alloc::string::String, /// If this field is provided, then the Endpoint's /// [traffic_split][google.cloud.aiplatform.v1.Endpoint.traffic_split] will be overwritten with it. If /// last DeployedModel is being undeployed from the Endpoint, the /// [Endpoint.traffic_split] will always end up empty when this call returns. /// A DeployedModel will be successfully undeployed only if it doesn't have /// any traffic assigned to it when this method executes, or if this field /// unassigns any traffic to it. #[prost(map = "string, int32", tag = "3")] pub traffic_split: ::std::collections::HashMap<::prost::alloc::string::String, i32>, } /// Response message for [EndpointService.UndeployModel][google.cloud.aiplatform.v1.EndpointService.UndeployModel]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct UndeployModelResponse {} /// Runtime operation information for [EndpointService.UndeployModel][google.cloud.aiplatform.v1.EndpointService.UndeployModel]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct UndeployModelOperationMetadata { /// The operation generic information. #[prost(message, optional, tag = "1")] pub generic_metadata: ::core::option::Option<GenericOperationMetadata>, } #[doc = r" Generated client implementations."] pub mod endpoint_service_client { #![allow(unused_variables, dead_code, missing_docs)] use tonic::codegen::*; pub struct EndpointServiceClient<T> { inner: tonic::client::Grpc<T>, } impl<T> EndpointServiceClient<T> where T: tonic::client::GrpcService<tonic::body::BoxBody>, T::ResponseBody: Body + HttpBody + Send + 'static, T::Error: Into<StdError>, <T::ResponseBody as HttpBody>::Error: Into<StdError> + Send, { pub fn new(inner: T) -> Self { let inner = tonic::client::Grpc::new(inner); Self { inner } } pub fn with_interceptor(inner: T, interceptor: impl Into<tonic::Interceptor>) -> Self { let inner = tonic::client::Grpc::with_interceptor(inner, interceptor); Self { inner } } #[doc = " Creates an Endpoint."] pub async fn create_endpoint( &mut self, request: impl tonic::IntoRequest<super::CreateEndpointRequest>, ) -> Result< tonic::Response<super::super::super::super::longrunning::Operation>, tonic::Status, > { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.EndpointService/CreateEndpoint", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Gets an Endpoint."] pub async fn get_endpoint( &mut self, request: impl tonic::IntoRequest<super::GetEndpointRequest>, ) -> Result<tonic::Response<super::Endpoint>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.EndpointService/GetEndpoint", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Lists Endpoints in a Location."] pub async fn list_endpoints( &mut self, request: impl tonic::IntoRequest<super::ListEndpointsRequest>, ) -> Result<tonic::Response<super::ListEndpointsResponse>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.EndpointService/ListEndpoints", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Updates an Endpoint."] pub async fn update_endpoint( &mut self, request: impl tonic::IntoRequest<super::UpdateEndpointRequest>, ) -> Result<tonic::Response<super::Endpoint>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.EndpointService/UpdateEndpoint", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Deletes an Endpoint."] pub async fn delete_endpoint( &mut self, request: impl tonic::IntoRequest<super::DeleteEndpointRequest>, ) -> Result< tonic::Response<super::super::super::super::longrunning::Operation>, tonic::Status, > { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.EndpointService/DeleteEndpoint", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Deploys a Model into this Endpoint, creating a DeployedModel within it."] pub async fn deploy_model( &mut self, request: impl tonic::IntoRequest<super::DeployModelRequest>, ) -> Result< tonic::Response<super::super::super::super::longrunning::Operation>, tonic::Status, > { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.EndpointService/DeployModel", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Undeploys a Model from an Endpoint, removing a DeployedModel from it, and"] #[doc = " freeing all resources it's using."] pub async fn undeploy_model( &mut self, request: impl tonic::IntoRequest<super::UndeployModelRequest>, ) -> Result< tonic::Response<super::super::super::super::longrunning::Operation>, tonic::Status, > { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.EndpointService/UndeployModel", ); self.inner.unary(request.into_request(), path, codec).await } } impl<T: Clone> Clone for EndpointServiceClient<T> { fn clone(&self) -> Self { Self { inner: self.inner.clone(), } } } impl<T> std::fmt::Debug for EndpointServiceClient<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "EndpointServiceClient {{ ... }}") } } } /// A message representing a Trial. A Trial contains a unique set of Parameters /// that has been or will be evaluated, along with the objective metrics got by /// running the Trial. #[derive(Clone, PartialEq, ::prost::Message)] pub struct Trial { /// Output only. The identifier of the Trial assigned by the service. #[prost(string, tag = "2")] pub id: ::prost::alloc::string::String, /// Output only. The detailed state of the Trial. #[prost(enumeration = "trial::State", tag = "3")] pub state: i32, /// Output only. The parameters of the Trial. #[prost(message, repeated, tag = "4")] pub parameters: ::prost::alloc::vec::Vec<trial::Parameter>, /// Output only. The final measurement containing the objective value. #[prost(message, optional, tag = "5")] pub final_measurement: ::core::option::Option<Measurement>, /// Output only. Time when the Trial was started. #[prost(message, optional, tag = "7")] pub start_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. Time when the Trial's status changed to `SUCCEEDED` or `INFEASIBLE`. #[prost(message, optional, tag = "8")] pub end_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. The CustomJob name linked to the Trial. /// It's set for a HyperparameterTuningJob's Trial. #[prost(string, tag = "11")] pub custom_job: ::prost::alloc::string::String, } /// Nested message and enum types in `Trial`. pub mod trial { /// A message representing a parameter to be tuned. #[derive(Clone, PartialEq, ::prost::Message)] pub struct Parameter { /// Output only. The ID of the parameter. The parameter should be defined in /// [StudySpec's Parameters][google.cloud.aiplatform.v1.StudySpec.parameters]. #[prost(string, tag = "1")] pub parameter_id: ::prost::alloc::string::String, /// Output only. The value of the parameter. /// `number_value` will be set if a parameter defined in StudySpec is /// in type 'INTEGER', 'DOUBLE' or 'DISCRETE'. /// `string_value` will be set if a parameter defined in StudySpec is /// in type 'CATEGORICAL'. #[prost(message, optional, tag = "2")] pub value: ::core::option::Option<::prost_types::Value>, } /// Describes a Trial state. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum State { /// The Trial state is unspecified. Unspecified = 0, /// Indicates that a specific Trial has been requested, but it has not yet /// been suggested by the service. Requested = 1, /// Indicates that the Trial has been suggested. Active = 2, /// Indicates that the Trial should stop according to the service. Stopping = 3, /// Indicates that the Trial is completed successfully. Succeeded = 4, /// Indicates that the Trial should not be attempted again. /// The service will set a Trial to INFEASIBLE when it's done but missing /// the final_measurement. Infeasible = 5, } } /// Represents specification of a Study. #[derive(Clone, PartialEq, ::prost::Message)] pub struct StudySpec { /// Required. Metric specs for the Study. #[prost(message, repeated, tag = "1")] pub metrics: ::prost::alloc::vec::Vec<study_spec::MetricSpec>, /// Required. The set of parameters to tune. #[prost(message, repeated, tag = "2")] pub parameters: ::prost::alloc::vec::Vec<study_spec::ParameterSpec>, /// The search algorithm specified for the Study. #[prost(enumeration = "study_spec::Algorithm", tag = "3")] pub algorithm: i32, /// The observation noise level of the study. /// Currently only supported by the Vizier service. Not supported by /// HyperparamterTuningJob or TrainingPipeline. #[prost(enumeration = "study_spec::ObservationNoise", tag = "6")] pub observation_noise: i32, /// Describe which measurement selection type will be used #[prost(enumeration = "study_spec::MeasurementSelectionType", tag = "7")] pub measurement_selection_type: i32, } /// Nested message and enum types in `StudySpec`. pub mod study_spec { /// Represents a metric to optimize. #[derive(Clone, PartialEq, ::prost::Message)] pub struct MetricSpec { /// Required. The ID of the metric. Must not contain whitespaces and must be unique /// amongst all MetricSpecs. #[prost(string, tag = "1")] pub metric_id: ::prost::alloc::string::String, /// Required. The optimization goal of the metric. #[prost(enumeration = "metric_spec::GoalType", tag = "2")] pub goal: i32, } /// Nested message and enum types in `MetricSpec`. pub mod metric_spec { /// The available types of optimization goals. #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration, )] #[repr(i32)] pub enum GoalType { /// Goal Type will default to maximize. Unspecified = 0, /// Maximize the goal metric. Maximize = 1, /// Minimize the goal metric. Minimize = 2, } } /// Represents a single parameter to optimize. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ParameterSpec { /// Required. The ID of the parameter. Must not contain whitespaces and must be unique /// amongst all ParameterSpecs. #[prost(string, tag = "1")] pub parameter_id: ::prost::alloc::string::String, /// How the parameter should be scaled. /// Leave unset for `CATEGORICAL` parameters. #[prost(enumeration = "parameter_spec::ScaleType", tag = "6")] pub scale_type: i32, /// A conditional parameter node is active if the parameter's value matches /// the conditional node's parent_value_condition. /// /// If two items in conditional_parameter_specs have the same name, they /// must have disjoint parent_value_condition. #[prost(message, repeated, tag = "10")] pub conditional_parameter_specs: ::prost::alloc::vec::Vec<parameter_spec::ConditionalParameterSpec>, #[prost(oneof = "parameter_spec::ParameterValueSpec", tags = "2, 3, 4, 5")] pub parameter_value_spec: ::core::option::Option<parameter_spec::ParameterValueSpec>, } /// Nested message and enum types in `ParameterSpec`. pub mod parameter_spec { /// Value specification for a parameter in `DOUBLE` type. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DoubleValueSpec { /// Required. Inclusive minimum value of the parameter. #[prost(double, tag = "1")] pub min_value: f64, /// Required. Inclusive maximum value of the parameter. #[prost(double, tag = "2")] pub max_value: f64, } /// Value specification for a parameter in `INTEGER` type. #[derive(Clone, PartialEq, ::prost::Message)] pub struct IntegerValueSpec { /// Required. Inclusive minimum value of the parameter. #[prost(int64, tag = "1")] pub min_value: i64, /// Required. Inclusive maximum value of the parameter. #[prost(int64, tag = "2")] pub max_value: i64, } /// Value specification for a parameter in `CATEGORICAL` type. #[derive(Clone, PartialEq, ::prost::Message)] pub struct CategoricalValueSpec { /// Required. The list of possible categories. #[prost(string, repeated, tag = "1")] pub values: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, } /// Value specification for a parameter in `DISCRETE` type. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DiscreteValueSpec { /// Required. A list of possible values. /// The list should be in increasing order and at least 1e-10 apart. /// For instance, this parameter might have possible settings of 1.5, 2.5, /// and 4.0. This list should not contain more than 1,000 values. #[prost(double, repeated, packed = "false", tag = "1")] pub values: ::prost::alloc::vec::Vec<f64>, } /// Represents a parameter spec with condition from its parent parameter. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ConditionalParameterSpec { /// Required. The spec for a conditional parameter. #[prost(message, optional, tag = "1")] pub parameter_spec: ::core::option::Option<super::ParameterSpec>, /// A set of parameter values from the parent ParameterSpec's feasible /// space. #[prost( oneof = "conditional_parameter_spec::ParentValueCondition", tags = "2, 3, 4" )] pub parent_value_condition: ::core::option::Option<conditional_parameter_spec::ParentValueCondition>, } /// Nested message and enum types in `ConditionalParameterSpec`. pub mod conditional_parameter_spec { /// Represents the spec to match discrete values from parent parameter. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DiscreteValueCondition { /// Required. Matches values of the parent parameter of 'DISCRETE' type. /// All values must exist in `discrete_value_spec` of parent parameter. /// /// The Epsilon of the value matching is 1e-10. #[prost(double, repeated, packed = "false", tag = "1")] pub values: ::prost::alloc::vec::Vec<f64>, } /// Represents the spec to match integer values from parent parameter. #[derive(Clone, PartialEq, ::prost::Message)] pub struct IntValueCondition { /// Required. Matches values of the parent parameter of 'INTEGER' type. /// All values must lie in `integer_value_spec` of parent parameter. #[prost(int64, repeated, packed = "false", tag = "1")] pub values: ::prost::alloc::vec::Vec<i64>, } /// Represents the spec to match categorical values from parent parameter. #[derive(Clone, PartialEq, ::prost::Message)] pub struct CategoricalValueCondition { /// Required. Matches values of the parent parameter of 'CATEGORICAL' type. /// All values must exist in `categorical_value_spec` of parent /// parameter. #[prost(string, repeated, tag = "1")] pub values: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, } /// A set of parameter values from the parent ParameterSpec's feasible /// space. #[derive(Clone, PartialEq, ::prost::Oneof)] pub enum ParentValueCondition { /// The spec for matching values from a parent parameter of /// `DISCRETE` type. #[prost(message, tag = "2")] ParentDiscreteValues(DiscreteValueCondition), /// The spec for matching values from a parent parameter of `INTEGER` /// type. #[prost(message, tag = "3")] ParentIntValues(IntValueCondition), /// The spec for matching values from a parent parameter of /// `CATEGORICAL` type. #[prost(message, tag = "4")] ParentCategoricalValues(CategoricalValueCondition), } } /// The type of scaling that should be applied to this parameter. #[derive( Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration, )] #[repr(i32)] pub enum ScaleType { /// By default, no scaling is applied. Unspecified = 0, /// Scales the feasible space to (0, 1) linearly. UnitLinearScale = 1, /// Scales the feasible space logarithmically to (0, 1). The entire /// feasible space must be strictly positive. UnitLogScale = 2, /// Scales the feasible space "reverse" logarithmically to (0, 1). The /// result is that values close to the top of the feasible space are spread /// out more than points near the bottom. The entire feasible space must be /// strictly positive. UnitReverseLogScale = 3, } #[derive(Clone, PartialEq, ::prost::Oneof)] pub enum ParameterValueSpec { /// The value spec for a 'DOUBLE' parameter. #[prost(message, tag = "2")] DoubleValueSpec(DoubleValueSpec), /// The value spec for an 'INTEGER' parameter. #[prost(message, tag = "3")] IntegerValueSpec(IntegerValueSpec), /// The value spec for a 'CATEGORICAL' parameter. #[prost(message, tag = "4")] CategoricalValueSpec(CategoricalValueSpec), /// The value spec for a 'DISCRETE' parameter. #[prost(message, tag = "5")] DiscreteValueSpec(DiscreteValueSpec), } } /// The available search algorithms for the Study. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum Algorithm { /// The default algorithm used by AI Platform Optimization service. Unspecified = 0, /// Simple grid search within the feasible space. To use grid search, /// all parameters must be `INTEGER`, `CATEGORICAL`, or `DISCRETE`. GridSearch = 2, /// Simple random search within the feasible space. RandomSearch = 3, } /// Describes the noise level of the repeated observations. /// /// "Noisy" means that the repeated observations with the same Trial parameters /// may lead to different metric evaluations. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum ObservationNoise { /// The default noise level chosen by the AI Platform service. Unspecified = 0, /// AI Platform Vizier assumes that the objective function is (nearly) /// perfectly reproducible, and will never repeat the same Trial /// parameters. Low = 1, /// AI Platform Vizier will estimate the amount of noise in metric /// evaluations, it may repeat the same Trial parameters more than once. High = 2, } /// This indicates which measurement to use if/when the service automatically /// selects the final measurement from previously reported intermediate /// measurements. Choose this based on two considerations: /// A) Do you expect your measurements to monotonically improve? /// If so, choose LAST_MEASUREMENT. On the other hand, if you're in a /// situation where your system can "over-train" and you expect the /// performance to get better for a while but then start declining, /// choose BEST_MEASUREMENT. /// B) Are your measurements significantly noisy and/or irreproducible? /// If so, BEST_MEASUREMENT will tend to be over-optimistic, and it /// may be better to choose LAST_MEASUREMENT. /// If both or neither of (A) and (B) apply, it doesn't matter which /// selection type is chosen. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum MeasurementSelectionType { /// Will be treated as LAST_MEASUREMENT. Unspecified = 0, /// Use the last measurement reported. LastMeasurement = 1, /// Use the best measurement reported. BestMeasurement = 2, } } /// A message representing a Measurement of a Trial. A Measurement contains /// the Metrics got by executing a Trial using suggested hyperparameter /// values. #[derive(Clone, PartialEq, ::prost::Message)] pub struct Measurement { /// Output only. The number of steps the machine learning model has been trained for. /// Must be non-negative. #[prost(int64, tag = "2")] pub step_count: i64, /// Output only. A list of metrics got by evaluating the objective functions using suggested /// Parameter values. #[prost(message, repeated, tag = "3")] pub metrics: ::prost::alloc::vec::Vec<measurement::Metric>, } /// Nested message and enum types in `Measurement`. pub mod measurement { /// A message representing a metric in the measurement. #[derive(Clone, PartialEq, ::prost::Message)] pub struct Metric { /// Output only. The ID of the Metric. The Metric should be defined in /// [StudySpec's Metrics][google.cloud.aiplatform.v1.StudySpec.metrics]. #[prost(string, tag = "1")] pub metric_id: ::prost::alloc::string::String, /// Output only. The value for this metric. #[prost(double, tag = "2")] pub value: f64, } } /// Represents a HyperparameterTuningJob. A HyperparameterTuningJob /// has a Study specification and multiple CustomJobs with identical /// CustomJob specification. #[derive(Clone, PartialEq, ::prost::Message)] pub struct HyperparameterTuningJob { /// Output only. Resource name of the HyperparameterTuningJob. #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, /// Required. The display name of the HyperparameterTuningJob. /// The name can be up to 128 characters long and can be consist of any UTF-8 /// characters. #[prost(string, tag = "2")] pub display_name: ::prost::alloc::string::String, /// Required. Study configuration of the HyperparameterTuningJob. #[prost(message, optional, tag = "4")] pub study_spec: ::core::option::Option<StudySpec>, /// Required. The desired total number of Trials. #[prost(int32, tag = "5")] pub max_trial_count: i32, /// Required. The desired number of Trials to run in parallel. #[prost(int32, tag = "6")] pub parallel_trial_count: i32, /// The number of failed Trials that need to be seen before failing /// the HyperparameterTuningJob. /// /// If set to 0, AI Platform decides how many Trials must fail /// before the whole job fails. #[prost(int32, tag = "7")] pub max_failed_trial_count: i32, /// Required. The spec of a trial job. The same spec applies to the CustomJobs created /// in all the trials. #[prost(message, optional, tag = "8")] pub trial_job_spec: ::core::option::Option<CustomJobSpec>, /// Output only. Trials of the HyperparameterTuningJob. #[prost(message, repeated, tag = "9")] pub trials: ::prost::alloc::vec::Vec<Trial>, /// Output only. The detailed state of the job. #[prost(enumeration = "JobState", tag = "10")] pub state: i32, /// Output only. Time when the HyperparameterTuningJob was created. #[prost(message, optional, tag = "11")] pub create_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. Time when the HyperparameterTuningJob for the first time entered the /// `JOB_STATE_RUNNING` state. #[prost(message, optional, tag = "12")] pub start_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. Time when the HyperparameterTuningJob entered any of the following states: /// `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`. #[prost(message, optional, tag = "13")] pub end_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. Time when the HyperparameterTuningJob was most recently updated. #[prost(message, optional, tag = "14")] pub update_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. Only populated when job's state is JOB_STATE_FAILED or /// JOB_STATE_CANCELLED. #[prost(message, optional, tag = "15")] pub error: ::core::option::Option<super::super::super::rpc::Status>, /// The labels with user-defined metadata to organize HyperparameterTuningJobs. /// /// Label keys and values can be no longer than 64 characters /// (Unicode codepoints), can only contain lowercase letters, numeric /// characters, underscores and dashes. International characters are allowed. /// /// See https://goo.gl/xmQnxf for more information and examples of labels. #[prost(map = "string, string", tag = "16")] pub labels: ::std::collections::HashMap<::prost::alloc::string::String, ::prost::alloc::string::String>, /// Customer-managed encryption key options for a HyperparameterTuningJob. /// If this is set, then all resources created by the HyperparameterTuningJob /// will be encrypted with the provided encryption key. #[prost(message, optional, tag = "17")] pub encryption_spec: ::core::option::Option<EncryptionSpec>, } /// Request message for [JobService.CreateCustomJob][google.cloud.aiplatform.v1.JobService.CreateCustomJob]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct CreateCustomJobRequest { /// Required. The resource name of the Location to create the CustomJob in. /// Format: `projects/{project}/locations/{location}` #[prost(string, tag = "1")] pub parent: ::prost::alloc::string::String, /// Required. The CustomJob to create. #[prost(message, optional, tag = "2")] pub custom_job: ::core::option::Option<CustomJob>, } /// Request message for [JobService.GetCustomJob][google.cloud.aiplatform.v1.JobService.GetCustomJob]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct GetCustomJobRequest { /// Required. The name of the CustomJob resource. /// Format: /// `projects/{project}/locations/{location}/customJobs/{custom_job}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, } /// Request message for [JobService.ListCustomJobs][google.cloud.aiplatform.v1.JobService.ListCustomJobs]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListCustomJobsRequest { /// Required. The resource name of the Location to list the CustomJobs from. /// Format: `projects/{project}/locations/{location}` #[prost(string, tag = "1")] pub parent: ::prost::alloc::string::String, /// The standard list filter. /// /// Supported fields: /// /// * `display_name` supports = and !=. /// /// * `state` supports = and !=. /// /// Some examples of using the filter are: /// /// * `state="JOB_STATE_SUCCEEDED" AND display_name="my_job"` /// /// * `state="JOB_STATE_RUNNING" OR display_name="my_job"` /// /// * `NOT display_name="my_job"` /// /// * `state="JOB_STATE_FAILED"` #[prost(string, tag = "2")] pub filter: ::prost::alloc::string::String, /// The standard list page size. #[prost(int32, tag = "3")] pub page_size: i32, /// The standard list page token. /// Typically obtained via /// [ListCustomJobsResponse.next_page_token][google.cloud.aiplatform.v1.ListCustomJobsResponse.next_page_token] of the previous /// [JobService.ListCustomJobs][google.cloud.aiplatform.v1.JobService.ListCustomJobs] call. #[prost(string, tag = "4")] pub page_token: ::prost::alloc::string::String, /// Mask specifying which fields to read. #[prost(message, optional, tag = "5")] pub read_mask: ::core::option::Option<::prost_types::FieldMask>, } /// Response message for [JobService.ListCustomJobs][google.cloud.aiplatform.v1.JobService.ListCustomJobs] #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListCustomJobsResponse { /// List of CustomJobs in the requested page. #[prost(message, repeated, tag = "1")] pub custom_jobs: ::prost::alloc::vec::Vec<CustomJob>, /// A token to retrieve the next page of results. /// Pass to [ListCustomJobsRequest.page_token][google.cloud.aiplatform.v1.ListCustomJobsRequest.page_token] to obtain that page. #[prost(string, tag = "2")] pub next_page_token: ::prost::alloc::string::String, } /// Request message for [JobService.DeleteCustomJob][google.cloud.aiplatform.v1.JobService.DeleteCustomJob]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DeleteCustomJobRequest { /// Required. The name of the CustomJob resource to be deleted. /// Format: /// `projects/{project}/locations/{location}/customJobs/{custom_job}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, } /// Request message for [JobService.CancelCustomJob][google.cloud.aiplatform.v1.JobService.CancelCustomJob]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct CancelCustomJobRequest { /// Required. The name of the CustomJob to cancel. /// Format: /// `projects/{project}/locations/{location}/customJobs/{custom_job}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, } /// Request message for [DataLabelingJobService.CreateDataLabelingJob][]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct CreateDataLabelingJobRequest { /// Required. The parent of the DataLabelingJob. /// Format: `projects/{project}/locations/{location}` #[prost(string, tag = "1")] pub parent: ::prost::alloc::string::String, /// Required. The DataLabelingJob to create. #[prost(message, optional, tag = "2")] pub data_labeling_job: ::core::option::Option<DataLabelingJob>, } /// Request message for [DataLabelingJobService.GetDataLabelingJob][]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct GetDataLabelingJobRequest { /// Required. The name of the DataLabelingJob. /// Format: /// /// `projects/{project}/locations/{location}/dataLabelingJobs/{data_labeling_job}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, } /// Request message for [DataLabelingJobService.ListDataLabelingJobs][]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListDataLabelingJobsRequest { /// Required. The parent of the DataLabelingJob. /// Format: `projects/{project}/locations/{location}` #[prost(string, tag = "1")] pub parent: ::prost::alloc::string::String, /// The standard list filter. /// /// Supported fields: /// /// * `display_name` supports = and !=. /// /// * `state` supports = and !=. /// /// Some examples of using the filter are: /// /// * `state="JOB_STATE_SUCCEEDED" AND display_name="my_job"` /// /// * `state="JOB_STATE_RUNNING" OR display_name="my_job"` /// /// * `NOT display_name="my_job"` /// /// * `state="JOB_STATE_FAILED"` #[prost(string, tag = "2")] pub filter: ::prost::alloc::string::String, /// The standard list page size. #[prost(int32, tag = "3")] pub page_size: i32, /// The standard list page token. #[prost(string, tag = "4")] pub page_token: ::prost::alloc::string::String, /// Mask specifying which fields to read. FieldMask represents a set of /// symbolic field paths. For example, the mask can be `paths: "name"`. The /// "name" here is a field in DataLabelingJob. /// If this field is not set, all fields of the DataLabelingJob are returned. #[prost(message, optional, tag = "5")] pub read_mask: ::core::option::Option<::prost_types::FieldMask>, /// A comma-separated list of fields to order by, sorted in ascending order by /// default. /// Use `desc` after a field name for descending. #[prost(string, tag = "6")] pub order_by: ::prost::alloc::string::String, } /// Response message for [JobService.ListDataLabelingJobs][google.cloud.aiplatform.v1.JobService.ListDataLabelingJobs]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListDataLabelingJobsResponse { /// A list of DataLabelingJobs that matches the specified filter in the /// request. #[prost(message, repeated, tag = "1")] pub data_labeling_jobs: ::prost::alloc::vec::Vec<DataLabelingJob>, /// The standard List next-page token. #[prost(string, tag = "2")] pub next_page_token: ::prost::alloc::string::String, } /// Request message for [JobService.DeleteDataLabelingJob][google.cloud.aiplatform.v1.JobService.DeleteDataLabelingJob]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DeleteDataLabelingJobRequest { /// Required. The name of the DataLabelingJob to be deleted. /// Format: /// /// `projects/{project}/locations/{location}/dataLabelingJobs/{data_labeling_job}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, } /// Request message for [DataLabelingJobService.CancelDataLabelingJob][]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct CancelDataLabelingJobRequest { /// Required. The name of the DataLabelingJob. /// Format: /// /// `projects/{project}/locations/{location}/dataLabelingJobs/{data_labeling_job}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, } /// Request message for [JobService.CreateHyperparameterTuningJob][google.cloud.aiplatform.v1.JobService.CreateHyperparameterTuningJob]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct CreateHyperparameterTuningJobRequest { /// Required. The resource name of the Location to create the HyperparameterTuningJob in. /// Format: `projects/{project}/locations/{location}` #[prost(string, tag = "1")] pub parent: ::prost::alloc::string::String, /// Required. The HyperparameterTuningJob to create. #[prost(message, optional, tag = "2")] pub hyperparameter_tuning_job: ::core::option::Option<HyperparameterTuningJob>, } /// Request message for [JobService.GetHyperparameterTuningJob][google.cloud.aiplatform.v1.JobService.GetHyperparameterTuningJob]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct GetHyperparameterTuningJobRequest { /// Required. The name of the HyperparameterTuningJob resource. /// Format: /// /// `projects/{project}/locations/{location}/hyperparameterTuningJobs/{hyperparameter_tuning_job}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, } /// Request message for [JobService.ListHyperparameterTuningJobs][google.cloud.aiplatform.v1.JobService.ListHyperparameterTuningJobs]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListHyperparameterTuningJobsRequest { /// Required. The resource name of the Location to list the HyperparameterTuningJobs /// from. Format: `projects/{project}/locations/{location}` #[prost(string, tag = "1")] pub parent: ::prost::alloc::string::String, /// The standard list filter. /// /// Supported fields: /// /// * `display_name` supports = and !=. /// /// * `state` supports = and !=. /// /// Some examples of using the filter are: /// /// * `state="JOB_STATE_SUCCEEDED" AND display_name="my_job"` /// /// * `state="JOB_STATE_RUNNING" OR display_name="my_job"` /// /// * `NOT display_name="my_job"` /// /// * `state="JOB_STATE_FAILED"` #[prost(string, tag = "2")] pub filter: ::prost::alloc::string::String, /// The standard list page size. #[prost(int32, tag = "3")] pub page_size: i32, /// The standard list page token. /// Typically obtained via /// [ListHyperparameterTuningJobsResponse.next_page_token][google.cloud.aiplatform.v1.ListHyperparameterTuningJobsResponse.next_page_token] of the previous /// [JobService.ListHyperparameterTuningJobs][google.cloud.aiplatform.v1.JobService.ListHyperparameterTuningJobs] call. #[prost(string, tag = "4")] pub page_token: ::prost::alloc::string::String, /// Mask specifying which fields to read. #[prost(message, optional, tag = "5")] pub read_mask: ::core::option::Option<::prost_types::FieldMask>, } /// Response message for [JobService.ListHyperparameterTuningJobs][google.cloud.aiplatform.v1.JobService.ListHyperparameterTuningJobs] #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListHyperparameterTuningJobsResponse { /// List of HyperparameterTuningJobs in the requested page. /// [HyperparameterTuningJob.trials][google.cloud.aiplatform.v1.HyperparameterTuningJob.trials] of the jobs will be not be returned. #[prost(message, repeated, tag = "1")] pub hyperparameter_tuning_jobs: ::prost::alloc::vec::Vec<HyperparameterTuningJob>, /// A token to retrieve the next page of results. /// Pass to [ListHyperparameterTuningJobsRequest.page_token][google.cloud.aiplatform.v1.ListHyperparameterTuningJobsRequest.page_token] to obtain that /// page. #[prost(string, tag = "2")] pub next_page_token: ::prost::alloc::string::String, } /// Request message for [JobService.DeleteHyperparameterTuningJob][google.cloud.aiplatform.v1.JobService.DeleteHyperparameterTuningJob]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DeleteHyperparameterTuningJobRequest { /// Required. The name of the HyperparameterTuningJob resource to be deleted. /// Format: /// /// `projects/{project}/locations/{location}/hyperparameterTuningJobs/{hyperparameter_tuning_job}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, } /// Request message for [JobService.CancelHyperparameterTuningJob][google.cloud.aiplatform.v1.JobService.CancelHyperparameterTuningJob]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct CancelHyperparameterTuningJobRequest { /// Required. The name of the HyperparameterTuningJob to cancel. /// Format: /// /// `projects/{project}/locations/{location}/hyperparameterTuningJobs/{hyperparameter_tuning_job}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, } /// Request message for [JobService.CreateBatchPredictionJob][google.cloud.aiplatform.v1.JobService.CreateBatchPredictionJob]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct CreateBatchPredictionJobRequest { /// Required. The resource name of the Location to create the BatchPredictionJob in. /// Format: `projects/{project}/locations/{location}` #[prost(string, tag = "1")] pub parent: ::prost::alloc::string::String, /// Required. The BatchPredictionJob to create. #[prost(message, optional, tag = "2")] pub batch_prediction_job: ::core::option::Option<BatchPredictionJob>, } /// Request message for [JobService.GetBatchPredictionJob][google.cloud.aiplatform.v1.JobService.GetBatchPredictionJob]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct GetBatchPredictionJobRequest { /// Required. The name of the BatchPredictionJob resource. /// Format: /// /// `projects/{project}/locations/{location}/batchPredictionJobs/{batch_prediction_job}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, } /// Request message for [JobService.ListBatchPredictionJobs][google.cloud.aiplatform.v1.JobService.ListBatchPredictionJobs]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListBatchPredictionJobsRequest { /// Required. The resource name of the Location to list the BatchPredictionJobs /// from. Format: `projects/{project}/locations/{location}` #[prost(string, tag = "1")] pub parent: ::prost::alloc::string::String, /// The standard list filter. /// /// Supported fields: /// /// * `display_name` supports = and !=. /// /// * `state` supports = and !=. /// /// Some examples of using the filter are: /// /// * `state="JOB_STATE_SUCCEEDED" AND display_name="my_job"` /// /// * `state="JOB_STATE_RUNNING" OR display_name="my_job"` /// /// * `NOT display_name="my_job"` /// /// * `state="JOB_STATE_FAILED"` #[prost(string, tag = "2")] pub filter: ::prost::alloc::string::String, /// The standard list page size. #[prost(int32, tag = "3")] pub page_size: i32, /// The standard list page token. /// Typically obtained via /// [ListBatchPredictionJobsResponse.next_page_token][google.cloud.aiplatform.v1.ListBatchPredictionJobsResponse.next_page_token] of the previous /// [JobService.ListBatchPredictionJobs][google.cloud.aiplatform.v1.JobService.ListBatchPredictionJobs] call. #[prost(string, tag = "4")] pub page_token: ::prost::alloc::string::String, /// Mask specifying which fields to read. #[prost(message, optional, tag = "5")] pub read_mask: ::core::option::Option<::prost_types::FieldMask>, } /// Response message for [JobService.ListBatchPredictionJobs][google.cloud.aiplatform.v1.JobService.ListBatchPredictionJobs] #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListBatchPredictionJobsResponse { /// List of BatchPredictionJobs in the requested page. #[prost(message, repeated, tag = "1")] pub batch_prediction_jobs: ::prost::alloc::vec::Vec<BatchPredictionJob>, /// A token to retrieve the next page of results. /// Pass to [ListBatchPredictionJobsRequest.page_token][google.cloud.aiplatform.v1.ListBatchPredictionJobsRequest.page_token] to obtain that /// page. #[prost(string, tag = "2")] pub next_page_token: ::prost::alloc::string::String, } /// Request message for [JobService.DeleteBatchPredictionJob][google.cloud.aiplatform.v1.JobService.DeleteBatchPredictionJob]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DeleteBatchPredictionJobRequest { /// Required. The name of the BatchPredictionJob resource to be deleted. /// Format: /// /// `projects/{project}/locations/{location}/batchPredictionJobs/{batch_prediction_job}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, } /// Request message for [JobService.CancelBatchPredictionJob][google.cloud.aiplatform.v1.JobService.CancelBatchPredictionJob]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct CancelBatchPredictionJobRequest { /// Required. The name of the BatchPredictionJob to cancel. /// Format: /// /// `projects/{project}/locations/{location}/batchPredictionJobs/{batch_prediction_job}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, } #[doc = r" Generated client implementations."] pub mod job_service_client { #![allow(unused_variables, dead_code, missing_docs)] use tonic::codegen::*; #[doc = " A service for creating and managing AI Platform's jobs."] pub struct JobServiceClient<T> { inner: tonic::client::Grpc<T>, } impl<T> JobServiceClient<T> where T: tonic::client::GrpcService<tonic::body::BoxBody>, T::ResponseBody: Body + HttpBody + Send + 'static, T::Error: Into<StdError>, <T::ResponseBody as HttpBody>::Error: Into<StdError> + Send, { pub fn new(inner: T) -> Self { let inner = tonic::client::Grpc::new(inner); Self { inner } } pub fn with_interceptor(inner: T, interceptor: impl Into<tonic::Interceptor>) -> Self { let inner = tonic::client::Grpc::with_interceptor(inner, interceptor); Self { inner } } #[doc = " Creates a CustomJob. A created CustomJob right away"] #[doc = " will be attempted to be run."] pub async fn create_custom_job( &mut self, request: impl tonic::IntoRequest<super::CreateCustomJobRequest>, ) -> Result<tonic::Response<super::CustomJob>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.JobService/CreateCustomJob", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Gets a CustomJob."] pub async fn get_custom_job( &mut self, request: impl tonic::IntoRequest<super::GetCustomJobRequest>, ) -> Result<tonic::Response<super::CustomJob>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.JobService/GetCustomJob", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Lists CustomJobs in a Location."] pub async fn list_custom_jobs( &mut self, request: impl tonic::IntoRequest<super::ListCustomJobsRequest>, ) -> Result<tonic::Response<super::ListCustomJobsResponse>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.JobService/ListCustomJobs", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Deletes a CustomJob."] pub async fn delete_custom_job( &mut self, request: impl tonic::IntoRequest<super::DeleteCustomJobRequest>, ) -> Result< tonic::Response<super::super::super::super::longrunning::Operation>, tonic::Status, > { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.JobService/DeleteCustomJob", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Cancels a CustomJob."] #[doc = " Starts asynchronous cancellation on the CustomJob. The server"] #[doc = " makes a best effort to cancel the job, but success is not"] #[doc = " guaranteed. Clients can use [JobService.GetCustomJob][google.cloud.aiplatform.v1.JobService.GetCustomJob] or"] #[doc = " other methods to check whether the cancellation succeeded or whether the"] #[doc = " job completed despite cancellation. On successful cancellation,"] #[doc = " the CustomJob is not deleted; instead it becomes a job with"] #[doc = " a [CustomJob.error][google.cloud.aiplatform.v1.CustomJob.error] value with a [google.rpc.Status.code][google.rpc.Status.code] of 1,"] #[doc = " corresponding to `Code.CANCELLED`, and [CustomJob.state][google.cloud.aiplatform.v1.CustomJob.state] is set to"] #[doc = " `CANCELLED`."] pub async fn cancel_custom_job( &mut self, request: impl tonic::IntoRequest<super::CancelCustomJobRequest>, ) -> Result<tonic::Response<()>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.JobService/CancelCustomJob", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Creates a DataLabelingJob."] pub async fn create_data_labeling_job( &mut self, request: impl tonic::IntoRequest<super::CreateDataLabelingJobRequest>, ) -> Result<tonic::Response<super::DataLabelingJob>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.JobService/CreateDataLabelingJob", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Gets a DataLabelingJob."] pub async fn get_data_labeling_job( &mut self, request: impl tonic::IntoRequest<super::GetDataLabelingJobRequest>, ) -> Result<tonic::Response<super::DataLabelingJob>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.JobService/GetDataLabelingJob", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Lists DataLabelingJobs in a Location."] pub async fn list_data_labeling_jobs( &mut self, request: impl tonic::IntoRequest<super::ListDataLabelingJobsRequest>, ) -> Result<tonic::Response<super::ListDataLabelingJobsResponse>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.JobService/ListDataLabelingJobs", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Deletes a DataLabelingJob."] pub async fn delete_data_labeling_job( &mut self, request: impl tonic::IntoRequest<super::DeleteDataLabelingJobRequest>, ) -> Result< tonic::Response<super::super::super::super::longrunning::Operation>, tonic::Status, > { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.JobService/DeleteDataLabelingJob", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Cancels a DataLabelingJob. Success of cancellation is not guaranteed."] pub async fn cancel_data_labeling_job( &mut self, request: impl tonic::IntoRequest<super::CancelDataLabelingJobRequest>, ) -> Result<tonic::Response<()>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.JobService/CancelDataLabelingJob", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Creates a HyperparameterTuningJob"] pub async fn create_hyperparameter_tuning_job( &mut self, request: impl tonic::IntoRequest<super::CreateHyperparameterTuningJobRequest>, ) -> Result<tonic::Response<super::HyperparameterTuningJob>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.JobService/CreateHyperparameterTuningJob", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Gets a HyperparameterTuningJob"] pub async fn get_hyperparameter_tuning_job( &mut self, request: impl tonic::IntoRequest<super::GetHyperparameterTuningJobRequest>, ) -> Result<tonic::Response<super::HyperparameterTuningJob>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.JobService/GetHyperparameterTuningJob", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Lists HyperparameterTuningJobs in a Location."] pub async fn list_hyperparameter_tuning_jobs( &mut self, request: impl tonic::IntoRequest<super::ListHyperparameterTuningJobsRequest>, ) -> Result<tonic::Response<super::ListHyperparameterTuningJobsResponse>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.JobService/ListHyperparameterTuningJobs", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Deletes a HyperparameterTuningJob."] pub async fn delete_hyperparameter_tuning_job( &mut self, request: impl tonic::IntoRequest<super::DeleteHyperparameterTuningJobRequest>, ) -> Result< tonic::Response<super::super::super::super::longrunning::Operation>, tonic::Status, > { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.JobService/DeleteHyperparameterTuningJob", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Cancels a HyperparameterTuningJob."] #[doc = " Starts asynchronous cancellation on the HyperparameterTuningJob. The server"] #[doc = " makes a best effort to cancel the job, but success is not"] #[doc = " guaranteed. Clients can use [JobService.GetHyperparameterTuningJob][google.cloud.aiplatform.v1.JobService.GetHyperparameterTuningJob] or"] #[doc = " other methods to check whether the cancellation succeeded or whether the"] #[doc = " job completed despite cancellation. On successful cancellation,"] #[doc = " the HyperparameterTuningJob is not deleted; instead it becomes a job with"] #[doc = " a [HyperparameterTuningJob.error][google.cloud.aiplatform.v1.HyperparameterTuningJob.error] value with a [google.rpc.Status.code][google.rpc.Status.code]"] #[doc = " of 1, corresponding to `Code.CANCELLED`, and"] #[doc = " [HyperparameterTuningJob.state][google.cloud.aiplatform.v1.HyperparameterTuningJob.state] is set to `CANCELLED`."] pub async fn cancel_hyperparameter_tuning_job( &mut self, request: impl tonic::IntoRequest<super::CancelHyperparameterTuningJobRequest>, ) -> Result<tonic::Response<()>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.JobService/CancelHyperparameterTuningJob", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Creates a BatchPredictionJob. A BatchPredictionJob once created will"] #[doc = " right away be attempted to start."] pub async fn create_batch_prediction_job( &mut self, request: impl tonic::IntoRequest<super::CreateBatchPredictionJobRequest>, ) -> Result<tonic::Response<super::BatchPredictionJob>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.JobService/CreateBatchPredictionJob", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Gets a BatchPredictionJob"] pub async fn get_batch_prediction_job( &mut self, request: impl tonic::IntoRequest<super::GetBatchPredictionJobRequest>, ) -> Result<tonic::Response<super::BatchPredictionJob>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.JobService/GetBatchPredictionJob", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Lists BatchPredictionJobs in a Location."] pub async fn list_batch_prediction_jobs( &mut self, request: impl tonic::IntoRequest<super::ListBatchPredictionJobsRequest>, ) -> Result<tonic::Response<super::ListBatchPredictionJobsResponse>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.JobService/ListBatchPredictionJobs", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Deletes a BatchPredictionJob. Can only be called on jobs that already"] #[doc = " finished."] pub async fn delete_batch_prediction_job( &mut self, request: impl tonic::IntoRequest<super::DeleteBatchPredictionJobRequest>, ) -> Result< tonic::Response<super::super::super::super::longrunning::Operation>, tonic::Status, > { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.JobService/DeleteBatchPredictionJob", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Cancels a BatchPredictionJob."] #[doc = ""] #[doc = " Starts asynchronous cancellation on the BatchPredictionJob. The server"] #[doc = " makes the best effort to cancel the job, but success is not"] #[doc = " guaranteed. Clients can use [JobService.GetBatchPredictionJob][google.cloud.aiplatform.v1.JobService.GetBatchPredictionJob] or"] #[doc = " other methods to check whether the cancellation succeeded or whether the"] #[doc = " job completed despite cancellation. On a successful cancellation,"] #[doc = " the BatchPredictionJob is not deleted;instead its"] #[doc = " [BatchPredictionJob.state][google.cloud.aiplatform.v1.BatchPredictionJob.state] is set to `CANCELLED`. Any files already"] #[doc = " outputted by the job are not deleted."] pub async fn cancel_batch_prediction_job( &mut self, request: impl tonic::IntoRequest<super::CancelBatchPredictionJobRequest>, ) -> Result<tonic::Response<()>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.JobService/CancelBatchPredictionJob", ); self.inner.unary(request.into_request(), path, codec).await } } impl<T: Clone> Clone for JobServiceClient<T> { fn clone(&self) -> Self { Self { inner: self.inner.clone(), } } } impl<T> std::fmt::Debug for JobServiceClient<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "JobServiceClient {{ ... }}") } } } /// Represents one resource that exists in automl.googleapis.com, /// datalabeling.googleapis.com or ml.googleapis.com. #[derive(Clone, PartialEq, ::prost::Message)] pub struct MigratableResource { /// Output only. Timestamp when the last migration attempt on this MigratableResource started. /// Will not be set if there's no migration attempt on this MigratableResource. #[prost(message, optional, tag = "5")] pub last_migrate_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. Timestamp when this MigratableResource was last updated. #[prost(message, optional, tag = "6")] pub last_update_time: ::core::option::Option<::prost_types::Timestamp>, #[prost(oneof = "migratable_resource::Resource", tags = "1, 2, 3, 4")] pub resource: ::core::option::Option<migratable_resource::Resource>, } /// Nested message and enum types in `MigratableResource`. pub mod migratable_resource { /// Represents one model Version in ml.googleapis.com. #[derive(Clone, PartialEq, ::prost::Message)] pub struct MlEngineModelVersion { /// The ml.googleapis.com endpoint that this model Version currently lives /// in. /// Example values: /// /// * ml.googleapis.com /// * us-centrall-ml.googleapis.com /// * europe-west4-ml.googleapis.com /// * asia-east1-ml.googleapis.com #[prost(string, tag = "1")] pub endpoint: ::prost::alloc::string::String, /// Full resource name of ml engine model Version. /// Format: `projects/{project}/models/{model}/versions/{version}`. #[prost(string, tag = "2")] pub version: ::prost::alloc::string::String, } /// Represents one Model in automl.googleapis.com. #[derive(Clone, PartialEq, ::prost::Message)] pub struct AutomlModel { /// Full resource name of automl Model. /// Format: /// `projects/{project}/locations/{location}/models/{model}`. #[prost(string, tag = "1")] pub model: ::prost::alloc::string::String, /// The Model's display name in automl.googleapis.com. #[prost(string, tag = "3")] pub model_display_name: ::prost::alloc::string::String, } /// Represents one Dataset in automl.googleapis.com. #[derive(Clone, PartialEq, ::prost::Message)] pub struct AutomlDataset { /// Full resource name of automl Dataset. /// Format: /// `projects/{project}/locations/{location}/datasets/{dataset}`. #[prost(string, tag = "1")] pub dataset: ::prost::alloc::string::String, /// The Dataset's display name in automl.googleapis.com. #[prost(string, tag = "4")] pub dataset_display_name: ::prost::alloc::string::String, } /// Represents one Dataset in datalabeling.googleapis.com. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DataLabelingDataset { /// Full resource name of data labeling Dataset. /// Format: /// `projects/{project}/datasets/{dataset}`. #[prost(string, tag = "1")] pub dataset: ::prost::alloc::string::String, /// The Dataset's display name in datalabeling.googleapis.com. #[prost(string, tag = "4")] pub dataset_display_name: ::prost::alloc::string::String, /// The migratable AnnotatedDataset in datalabeling.googleapis.com belongs to /// the data labeling Dataset. #[prost(message, repeated, tag = "3")] pub data_labeling_annotated_datasets: ::prost::alloc::vec::Vec<data_labeling_dataset::DataLabelingAnnotatedDataset>, } /// Nested message and enum types in `DataLabelingDataset`. pub mod data_labeling_dataset { /// Represents one AnnotatedDataset in datalabeling.googleapis.com. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DataLabelingAnnotatedDataset { /// Full resource name of data labeling AnnotatedDataset. /// Format: /// /// `projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}`. #[prost(string, tag = "1")] pub annotated_dataset: ::prost::alloc::string::String, /// The AnnotatedDataset's display name in datalabeling.googleapis.com. #[prost(string, tag = "3")] pub annotated_dataset_display_name: ::prost::alloc::string::String, } } #[derive(Clone, PartialEq, ::prost::Oneof)] pub enum Resource { /// Output only. Represents one Version in ml.googleapis.com. #[prost(message, tag = "1")] MlEngineModelVersion(MlEngineModelVersion), /// Output only. Represents one Model in automl.googleapis.com. #[prost(message, tag = "2")] AutomlModel(AutomlModel), /// Output only. Represents one Dataset in automl.googleapis.com. #[prost(message, tag = "3")] AutomlDataset(AutomlDataset), /// Output only. Represents one Dataset in datalabeling.googleapis.com. #[prost(message, tag = "4")] DataLabelingDataset(DataLabelingDataset), } } /// Request message for [MigrationService.SearchMigratableResources][google.cloud.aiplatform.v1.MigrationService.SearchMigratableResources]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct SearchMigratableResourcesRequest { /// Required. The location that the migratable resources should be searched from. /// It's the AI Platform location that the resources can be migrated to, not /// the resources' original location. /// Format: /// `projects/{project}/locations/{location}` #[prost(string, tag = "1")] pub parent: ::prost::alloc::string::String, /// The standard page size. /// The default and maximum value is 100. #[prost(int32, tag = "2")] pub page_size: i32, /// The standard page token. #[prost(string, tag = "3")] pub page_token: ::prost::alloc::string::String, /// Supported filters are: /// * Resource type: For a specific type of MigratableResource. /// * `ml_engine_model_version:*` /// * `automl_model:*`, /// * `automl_dataset:*` /// * `data_labeling_dataset:*`. /// * Migrated or not: Filter migrated resource or not by last_migrate_time. /// * `last_migrate_time:*` will filter migrated resources. /// * `NOT last_migrate_time:*` will filter not yet migrated resources. #[prost(string, tag = "4")] pub filter: ::prost::alloc::string::String, } /// Response message for [MigrationService.SearchMigratableResources][google.cloud.aiplatform.v1.MigrationService.SearchMigratableResources]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct SearchMigratableResourcesResponse { /// All migratable resources that can be migrated to the /// location specified in the request. #[prost(message, repeated, tag = "1")] pub migratable_resources: ::prost::alloc::vec::Vec<MigratableResource>, /// The standard next-page token. /// The migratable_resources may not fill page_size in /// SearchMigratableResourcesRequest even when there are subsequent pages. #[prost(string, tag = "2")] pub next_page_token: ::prost::alloc::string::String, } /// Request message for [MigrationService.BatchMigrateResources][google.cloud.aiplatform.v1.MigrationService.BatchMigrateResources]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct BatchMigrateResourcesRequest { /// Required. The location of the migrated resource will live in. /// Format: `projects/{project}/locations/{location}` #[prost(string, tag = "1")] pub parent: ::prost::alloc::string::String, /// Required. The request messages specifying the resources to migrate. /// They must be in the same location as the destination. /// Up to 50 resources can be migrated in one batch. #[prost(message, repeated, tag = "2")] pub migrate_resource_requests: ::prost::alloc::vec::Vec<MigrateResourceRequest>, } /// Config of migrating one resource from automl.googleapis.com, /// datalabeling.googleapis.com and ml.googleapis.com to AI Platform. #[derive(Clone, PartialEq, ::prost::Message)] pub struct MigrateResourceRequest { #[prost(oneof = "migrate_resource_request::Request", tags = "1, 2, 3, 4")] pub request: ::core::option::Option<migrate_resource_request::Request>, } /// Nested message and enum types in `MigrateResourceRequest`. pub mod migrate_resource_request { /// Config for migrating version in ml.googleapis.com to AI Platform's Model. #[derive(Clone, PartialEq, ::prost::Message)] pub struct MigrateMlEngineModelVersionConfig { /// Required. The ml.googleapis.com endpoint that this model version should be migrated /// from. /// Example values: /// /// * ml.googleapis.com /// /// * us-centrall-ml.googleapis.com /// /// * europe-west4-ml.googleapis.com /// /// * asia-east1-ml.googleapis.com #[prost(string, tag = "1")] pub endpoint: ::prost::alloc::string::String, /// Required. Full resource name of ml engine model version. /// Format: `projects/{project}/models/{model}/versions/{version}`. #[prost(string, tag = "2")] pub model_version: ::prost::alloc::string::String, /// Required. Display name of the model in AI Platform. /// System will pick a display name if unspecified. #[prost(string, tag = "3")] pub model_display_name: ::prost::alloc::string::String, } /// Config for migrating Model in automl.googleapis.com to AI Platform's Model. #[derive(Clone, PartialEq, ::prost::Message)] pub struct MigrateAutomlModelConfig { /// Required. Full resource name of automl Model. /// Format: /// `projects/{project}/locations/{location}/models/{model}`. #[prost(string, tag = "1")] pub model: ::prost::alloc::string::String, /// Optional. Display name of the model in AI Platform. /// System will pick a display name if unspecified. #[prost(string, tag = "2")] pub model_display_name: ::prost::alloc::string::String, } /// Config for migrating Dataset in automl.googleapis.com to AI Platform's /// Dataset. #[derive(Clone, PartialEq, ::prost::Message)] pub struct MigrateAutomlDatasetConfig { /// Required. Full resource name of automl Dataset. /// Format: /// `projects/{project}/locations/{location}/datasets/{dataset}`. #[prost(string, tag = "1")] pub dataset: ::prost::alloc::string::String, /// Required. Display name of the Dataset in AI Platform. /// System will pick a display name if unspecified. #[prost(string, tag = "2")] pub dataset_display_name: ::prost::alloc::string::String, } /// Config for migrating Dataset in datalabeling.googleapis.com to AI /// Platform's Dataset. #[derive(Clone, PartialEq, ::prost::Message)] pub struct MigrateDataLabelingDatasetConfig { /// Required. Full resource name of data labeling Dataset. /// Format: /// `projects/{project}/datasets/{dataset}`. #[prost(string, tag = "1")] pub dataset: ::prost::alloc::string::String, /// Optional. Display name of the Dataset in AI Platform. /// System will pick a display name if unspecified. #[prost(string, tag = "2")] pub dataset_display_name: ::prost::alloc::string::String, /// Optional. Configs for migrating AnnotatedDataset in datalabeling.googleapis.com to /// AI Platform's SavedQuery. The specified AnnotatedDatasets have to belong /// to the datalabeling Dataset. #[prost(message, repeated, tag = "3")] pub migrate_data_labeling_annotated_dataset_configs: ::prost::alloc::vec::Vec< migrate_data_labeling_dataset_config::MigrateDataLabelingAnnotatedDatasetConfig, >, } /// Nested message and enum types in `MigrateDataLabelingDatasetConfig`. pub mod migrate_data_labeling_dataset_config { /// Config for migrating AnnotatedDataset in datalabeling.googleapis.com to /// AI Platform's SavedQuery. #[derive(Clone, PartialEq, ::prost::Message)] pub struct MigrateDataLabelingAnnotatedDatasetConfig { /// Required. Full resource name of data labeling AnnotatedDataset. /// Format: /// /// `projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}`. #[prost(string, tag = "1")] pub annotated_dataset: ::prost::alloc::string::String, } } #[derive(Clone, PartialEq, ::prost::Oneof)] pub enum Request { /// Config for migrating Version in ml.googleapis.com to AI Platform's Model. #[prost(message, tag = "1")] MigrateMlEngineModelVersionConfig(MigrateMlEngineModelVersionConfig), /// Config for migrating Model in automl.googleapis.com to AI Platform's /// Model. #[prost(message, tag = "2")] MigrateAutomlModelConfig(MigrateAutomlModelConfig), /// Config for migrating Dataset in automl.googleapis.com to AI Platform's /// Dataset. #[prost(message, tag = "3")] MigrateAutomlDatasetConfig(MigrateAutomlDatasetConfig), /// Config for migrating Dataset in datalabeling.googleapis.com to /// AI Platform's Dataset. #[prost(message, tag = "4")] MigrateDataLabelingDatasetConfig(MigrateDataLabelingDatasetConfig), } } /// Response message for [MigrationService.BatchMigrateResources][google.cloud.aiplatform.v1.MigrationService.BatchMigrateResources]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct BatchMigrateResourcesResponse { /// Successfully migrated resources. #[prost(message, repeated, tag = "1")] pub migrate_resource_responses: ::prost::alloc::vec::Vec<MigrateResourceResponse>, } /// Describes a successfully migrated resource. #[derive(Clone, PartialEq, ::prost::Message)] pub struct MigrateResourceResponse { /// Before migration, the identifier in ml.googleapis.com, /// automl.googleapis.com or datalabeling.googleapis.com. #[prost(message, optional, tag = "3")] pub migratable_resource: ::core::option::Option<MigratableResource>, /// After migration, the resource name in AI Platform. #[prost(oneof = "migrate_resource_response::MigratedResource", tags = "1, 2")] pub migrated_resource: ::core::option::Option<migrate_resource_response::MigratedResource>, } /// Nested message and enum types in `MigrateResourceResponse`. pub mod migrate_resource_response { /// After migration, the resource name in AI Platform. #[derive(Clone, PartialEq, ::prost::Oneof)] pub enum MigratedResource { /// Migrated Dataset's resource name. #[prost(string, tag = "1")] Dataset(::prost::alloc::string::String), /// Migrated Model's resource name. #[prost(string, tag = "2")] Model(::prost::alloc::string::String), } } /// Runtime operation information for [MigrationService.BatchMigrateResources][google.cloud.aiplatform.v1.MigrationService.BatchMigrateResources]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct BatchMigrateResourcesOperationMetadata { /// The common part of the operation metadata. #[prost(message, optional, tag = "1")] pub generic_metadata: ::core::option::Option<GenericOperationMetadata>, /// Partial results that reflect the latest migration operation progress. #[prost(message, repeated, tag = "2")] pub partial_results: ::prost::alloc::vec::Vec<batch_migrate_resources_operation_metadata::PartialResult>, } /// Nested message and enum types in `BatchMigrateResourcesOperationMetadata`. pub mod batch_migrate_resources_operation_metadata { /// Represents a partial result in batch migration operation for one /// [MigrateResourceRequest][google.cloud.aiplatform.v1.MigrateResourceRequest]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct PartialResult { /// It's the same as the value in /// [MigrateResourceRequest.migrate_resource_requests][]. #[prost(message, optional, tag = "1")] pub request: ::core::option::Option<super::MigrateResourceRequest>, /// If the resource's migration is ongoing, none of the result will be set. /// If the resource's migration is finished, either error or one of the /// migrated resource name will be filled. #[prost(oneof = "partial_result::Result", tags = "2, 3, 4")] pub result: ::core::option::Option<partial_result::Result>, } /// Nested message and enum types in `PartialResult`. pub mod partial_result { /// If the resource's migration is ongoing, none of the result will be set. /// If the resource's migration is finished, either error or one of the /// migrated resource name will be filled. #[derive(Clone, PartialEq, ::prost::Oneof)] pub enum Result { /// The error result of the migration request in case of failure. #[prost(message, tag = "2")] Error(super::super::super::super::super::rpc::Status), /// Migrated model resource name. #[prost(string, tag = "3")] Model(::prost::alloc::string::String), /// Migrated dataset resource name. #[prost(string, tag = "4")] Dataset(::prost::alloc::string::String), } } } #[doc = r" Generated client implementations."] pub mod migration_service_client { #![allow(unused_variables, dead_code, missing_docs)] use tonic::codegen::*; #[doc = " A service that migrates resources from automl.googleapis.com,"] #[doc = " datalabeling.googleapis.com and ml.googleapis.com to AI Platform."] pub struct MigrationServiceClient<T> { inner: tonic::client::Grpc<T>, } impl<T> MigrationServiceClient<T> where T: tonic::client::GrpcService<tonic::body::BoxBody>, T::ResponseBody: Body + HttpBody + Send + 'static, T::Error: Into<StdError>, <T::ResponseBody as HttpBody>::Error: Into<StdError> + Send, { pub fn new(inner: T) -> Self { let inner = tonic::client::Grpc::new(inner); Self { inner } } pub fn with_interceptor(inner: T, interceptor: impl Into<tonic::Interceptor>) -> Self { let inner = tonic::client::Grpc::with_interceptor(inner, interceptor); Self { inner } } #[doc = " Searches all of the resources in automl.googleapis.com,"] #[doc = " datalabeling.googleapis.com and ml.googleapis.com that can be migrated to"] #[doc = " AI Platform's given location."] pub async fn search_migratable_resources( &mut self, request: impl tonic::IntoRequest<super::SearchMigratableResourcesRequest>, ) -> Result<tonic::Response<super::SearchMigratableResourcesResponse>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.MigrationService/SearchMigratableResources", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Batch migrates resources from ml.googleapis.com, automl.googleapis.com,"] #[doc = " and datalabeling.googleapis.com to AI Platform (Unified)."] pub async fn batch_migrate_resources( &mut self, request: impl tonic::IntoRequest<super::BatchMigrateResourcesRequest>, ) -> Result< tonic::Response<super::super::super::super::longrunning::Operation>, tonic::Status, > { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.MigrationService/BatchMigrateResources", ); self.inner.unary(request.into_request(), path, codec).await } } impl<T: Clone> Clone for MigrationServiceClient<T> { fn clone(&self) -> Self { Self { inner: self.inner.clone(), } } } impl<T> std::fmt::Debug for MigrationServiceClient<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "MigrationServiceClient {{ ... }}") } } } /// A collection of metrics calculated by comparing Model's predictions on all of /// the test data against annotations from the test data. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ModelEvaluation { /// Output only. The resource name of the ModelEvaluation. #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, /// Output only. Points to a YAML file stored on Google Cloud Storage describing the /// [metrics][google.cloud.aiplatform.v1.ModelEvaluation.metrics] of this ModelEvaluation. The schema is /// defined as an OpenAPI 3.0.2 /// [Schema Object](https://tinyurl.com/y538mdwt#schema-object). #[prost(string, tag = "2")] pub metrics_schema_uri: ::prost::alloc::string::String, /// Output only. Evaluation metrics of the Model. The schema of the metrics is stored in /// [metrics_schema_uri][google.cloud.aiplatform.v1.ModelEvaluation.metrics_schema_uri] #[prost(message, optional, tag = "3")] pub metrics: ::core::option::Option<::prost_types::Value>, /// Output only. Timestamp when this ModelEvaluation was created. #[prost(message, optional, tag = "4")] pub create_time: ::core::option::Option<::prost_types::Timestamp>, /// Output only. All possible [dimensions][ModelEvaluationSlice.slice.dimension] of /// ModelEvaluationSlices. The dimensions can be used as the filter of the /// [ModelService.ListModelEvaluationSlices][google.cloud.aiplatform.v1.ModelService.ListModelEvaluationSlices] request, in the form of /// `slice.dimension = <dimension>`. #[prost(string, repeated, tag = "5")] pub slice_dimensions: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, } /// A collection of metrics calculated by comparing Model's predictions on a /// slice of the test data against ground truth annotations. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ModelEvaluationSlice { /// Output only. The resource name of the ModelEvaluationSlice. #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, /// Output only. The slice of the test data that is used to evaluate the Model. #[prost(message, optional, tag = "2")] pub slice: ::core::option::Option<model_evaluation_slice::Slice>, /// Output only. Points to a YAML file stored on Google Cloud Storage describing the /// [metrics][google.cloud.aiplatform.v1.ModelEvaluationSlice.metrics] of this ModelEvaluationSlice. The /// schema is defined as an OpenAPI 3.0.2 /// [Schema Object](https://tinyurl.com/y538mdwt#schema-object). #[prost(string, tag = "3")] pub metrics_schema_uri: ::prost::alloc::string::String, /// Output only. Sliced evaluation metrics of the Model. The schema of the metrics is stored /// in [metrics_schema_uri][google.cloud.aiplatform.v1.ModelEvaluationSlice.metrics_schema_uri] #[prost(message, optional, tag = "4")] pub metrics: ::core::option::Option<::prost_types::Value>, /// Output only. Timestamp when this ModelEvaluationSlice was created. #[prost(message, optional, tag = "5")] pub create_time: ::core::option::Option<::prost_types::Timestamp>, } /// Nested message and enum types in `ModelEvaluationSlice`. pub mod model_evaluation_slice { /// Definition of a slice. #[derive(Clone, PartialEq, ::prost::Message)] pub struct Slice { /// Output only. The dimension of the slice. /// Well-known dimensions are: /// * `annotationSpec`: This slice is on the test data that has either /// ground truth or prediction with [AnnotationSpec.display_name][google.cloud.aiplatform.v1.AnnotationSpec.display_name] /// equals to [value][google.cloud.aiplatform.v1.ModelEvaluationSlice.Slice.value]. #[prost(string, tag = "1")] pub dimension: ::prost::alloc::string::String, /// Output only. The value of the dimension in this slice. #[prost(string, tag = "2")] pub value: ::prost::alloc::string::String, } } /// Request message for [ModelService.UploadModel][google.cloud.aiplatform.v1.ModelService.UploadModel]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct UploadModelRequest { /// Required. The resource name of the Location into which to upload the Model. /// Format: `projects/{project}/locations/{location}` #[prost(string, tag = "1")] pub parent: ::prost::alloc::string::String, /// Required. The Model to create. #[prost(message, optional, tag = "2")] pub model: ::core::option::Option<Model>, } /// Details of [ModelService.UploadModel][google.cloud.aiplatform.v1.ModelService.UploadModel] operation. #[derive(Clone, PartialEq, ::prost::Message)] pub struct UploadModelOperationMetadata { /// The common part of the operation metadata. #[prost(message, optional, tag = "1")] pub generic_metadata: ::core::option::Option<GenericOperationMetadata>, } /// Response message of [ModelService.UploadModel][google.cloud.aiplatform.v1.ModelService.UploadModel] operation. #[derive(Clone, PartialEq, ::prost::Message)] pub struct UploadModelResponse { /// The name of the uploaded Model resource. /// Format: `projects/{project}/locations/{location}/models/{model}` #[prost(string, tag = "1")] pub model: ::prost::alloc::string::String, } /// Request message for [ModelService.GetModel][google.cloud.aiplatform.v1.ModelService.GetModel]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct GetModelRequest { /// Required. The name of the Model resource. /// Format: `projects/{project}/locations/{location}/models/{model}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, } /// Request message for [ModelService.ListModels][google.cloud.aiplatform.v1.ModelService.ListModels]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListModelsRequest { /// Required. The resource name of the Location to list the Models from. /// Format: `projects/{project}/locations/{location}` #[prost(string, tag = "1")] pub parent: ::prost::alloc::string::String, /// An expression for filtering the results of the request. For field names /// both snake_case and camelCase are supported. /// /// * `model` supports = and !=. `model` represents the Model ID, /// i.e. the last segment of the Model's [resource name][google.cloud.aiplatform.v1.Model.name]. /// * `display_name` supports = and != /// * `labels` supports general map functions that is: /// * `labels.key=value` - key:value equality /// * `labels.key:* or labels:key - key existence /// * A key including a space must be quoted. `labels."a key"`. /// /// Some examples: /// * `model=1234` /// * `displayName="myDisplayName"` /// * `labels.myKey="myValue"` #[prost(string, tag = "2")] pub filter: ::prost::alloc::string::String, /// The standard list page size. #[prost(int32, tag = "3")] pub page_size: i32, /// The standard list page token. /// Typically obtained via /// [ListModelsResponse.next_page_token][google.cloud.aiplatform.v1.ListModelsResponse.next_page_token] of the previous /// [ModelService.ListModels][google.cloud.aiplatform.v1.ModelService.ListModels] call. #[prost(string, tag = "4")] pub page_token: ::prost::alloc::string::String, /// Mask specifying which fields to read. #[prost(message, optional, tag = "5")] pub read_mask: ::core::option::Option<::prost_types::FieldMask>, /// A comma-separated list of fields to order by, sorted in ascending order. /// Use "desc" after a field name for descending. /// Supported fields: /// * `display_name` /// * `create_time` /// * `update_time` /// /// Example: `display_name, create_time desc`. #[prost(string, tag = "6")] pub order_by: ::prost::alloc::string::String, } /// Response message for [ModelService.ListModels][google.cloud.aiplatform.v1.ModelService.ListModels] #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListModelsResponse { /// List of Models in the requested page. #[prost(message, repeated, tag = "1")] pub models: ::prost::alloc::vec::Vec<Model>, /// A token to retrieve next page of results. /// Pass to [ListModelsRequest.page_token][google.cloud.aiplatform.v1.ListModelsRequest.page_token] to obtain that page. #[prost(string, tag = "2")] pub next_page_token: ::prost::alloc::string::String, } /// Request message for [ModelService.UpdateModel][google.cloud.aiplatform.v1.ModelService.UpdateModel]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct UpdateModelRequest { /// Required. The Model which replaces the resource on the server. #[prost(message, optional, tag = "1")] pub model: ::core::option::Option<Model>, /// Required. The update mask applies to the resource. /// For the `FieldMask` definition, see /// [FieldMask](https://tinyurl.com/protobufs/google.protobuf#fieldmask). #[prost(message, optional, tag = "2")] pub update_mask: ::core::option::Option<::prost_types::FieldMask>, } /// Request message for [ModelService.DeleteModel][google.cloud.aiplatform.v1.ModelService.DeleteModel]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DeleteModelRequest { /// Required. The name of the Model resource to be deleted. /// Format: `projects/{project}/locations/{location}/models/{model}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, } /// Request message for [ModelService.ExportModel][google.cloud.aiplatform.v1.ModelService.ExportModel]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ExportModelRequest { /// Required. The resource name of the Model to export. /// Format: `projects/{project}/locations/{location}/models/{model}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, /// Required. The desired output location and configuration. #[prost(message, optional, tag = "2")] pub output_config: ::core::option::Option<export_model_request::OutputConfig>, } /// Nested message and enum types in `ExportModelRequest`. pub mod export_model_request { /// Output configuration for the Model export. #[derive(Clone, PartialEq, ::prost::Message)] pub struct OutputConfig { /// The ID of the format in which the Model must be exported. Each Model /// lists the [export formats it supports][google.cloud.aiplatform.v1.Model.supported_export_formats]. /// If no value is provided here, then the first from the list of the Model's /// supported formats is used by default. #[prost(string, tag = "1")] pub export_format_id: ::prost::alloc::string::String, /// The Cloud Storage location where the Model artifact is to be /// written to. Under the directory given as the destination a new one with /// name "`model-export-<model-display-name>-<timestamp-of-export-call>`", /// where timestamp is in YYYY-MM-DDThh:mm:ss.sssZ ISO-8601 format, /// will be created. Inside, the Model and any of its supporting files /// will be written. /// This field should only be set when the `exportableContent` field of the /// [Model.supported_export_formats] object contains `ARTIFACT`. #[prost(message, optional, tag = "3")] pub artifact_destination: ::core::option::Option<super::GcsDestination>, /// The Google Container Registry or Artifact Registry uri where the /// Model container image will be copied to. /// This field should only be set when the `exportableContent` field of the /// [Model.supported_export_formats] object contains `IMAGE`. #[prost(message, optional, tag = "4")] pub image_destination: ::core::option::Option<super::ContainerRegistryDestination>, } } /// Details of [ModelService.ExportModel][google.cloud.aiplatform.v1.ModelService.ExportModel] operation. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ExportModelOperationMetadata { /// The common part of the operation metadata. #[prost(message, optional, tag = "1")] pub generic_metadata: ::core::option::Option<GenericOperationMetadata>, /// Output only. Information further describing the output of this Model export. #[prost(message, optional, tag = "2")] pub output_info: ::core::option::Option<export_model_operation_metadata::OutputInfo>, } /// Nested message and enum types in `ExportModelOperationMetadata`. pub mod export_model_operation_metadata { /// Further describes the output of the ExportModel. Supplements /// [ExportModelRequest.OutputConfig][google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct OutputInfo { /// Output only. If the Model artifact is being exported to Google Cloud Storage this is /// the full path of the directory created, into which the Model files are /// being written to. #[prost(string, tag = "2")] pub artifact_output_uri: ::prost::alloc::string::String, /// Output only. If the Model image is being exported to Google Container Registry or /// Artifact Registry this is the full path of the image created. #[prost(string, tag = "3")] pub image_output_uri: ::prost::alloc::string::String, } } /// Response message of [ModelService.ExportModel][google.cloud.aiplatform.v1.ModelService.ExportModel] operation. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ExportModelResponse {} /// Request message for [ModelService.GetModelEvaluation][google.cloud.aiplatform.v1.ModelService.GetModelEvaluation]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct GetModelEvaluationRequest { /// Required. The name of the ModelEvaluation resource. /// Format: /// /// `projects/{project}/locations/{location}/models/{model}/evaluations/{evaluation}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, } /// Request message for [ModelService.ListModelEvaluations][google.cloud.aiplatform.v1.ModelService.ListModelEvaluations]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListModelEvaluationsRequest { /// Required. The resource name of the Model to list the ModelEvaluations from. /// Format: `projects/{project}/locations/{location}/models/{model}` #[prost(string, tag = "1")] pub parent: ::prost::alloc::string::String, /// The standard list filter. #[prost(string, tag = "2")] pub filter: ::prost::alloc::string::String, /// The standard list page size. #[prost(int32, tag = "3")] pub page_size: i32, /// The standard list page token. /// Typically obtained via /// [ListModelEvaluationsResponse.next_page_token][google.cloud.aiplatform.v1.ListModelEvaluationsResponse.next_page_token] of the previous /// [ModelService.ListModelEvaluations][google.cloud.aiplatform.v1.ModelService.ListModelEvaluations] call. #[prost(string, tag = "4")] pub page_token: ::prost::alloc::string::String, /// Mask specifying which fields to read. #[prost(message, optional, tag = "5")] pub read_mask: ::core::option::Option<::prost_types::FieldMask>, } /// Response message for [ModelService.ListModelEvaluations][google.cloud.aiplatform.v1.ModelService.ListModelEvaluations]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListModelEvaluationsResponse { /// List of ModelEvaluations in the requested page. #[prost(message, repeated, tag = "1")] pub model_evaluations: ::prost::alloc::vec::Vec<ModelEvaluation>, /// A token to retrieve next page of results. /// Pass to [ListModelEvaluationsRequest.page_token][google.cloud.aiplatform.v1.ListModelEvaluationsRequest.page_token] to obtain that page. #[prost(string, tag = "2")] pub next_page_token: ::prost::alloc::string::String, } /// Request message for [ModelService.GetModelEvaluationSlice][google.cloud.aiplatform.v1.ModelService.GetModelEvaluationSlice]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct GetModelEvaluationSliceRequest { /// Required. The name of the ModelEvaluationSlice resource. /// Format: /// /// `projects/{project}/locations/{location}/models/{model}/evaluations/{evaluation}/slices/{slice}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, } /// Request message for [ModelService.ListModelEvaluationSlices][google.cloud.aiplatform.v1.ModelService.ListModelEvaluationSlices]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListModelEvaluationSlicesRequest { /// Required. The resource name of the ModelEvaluation to list the ModelEvaluationSlices /// from. Format: /// /// `projects/{project}/locations/{location}/models/{model}/evaluations/{evaluation}` #[prost(string, tag = "1")] pub parent: ::prost::alloc::string::String, /// The standard list filter. /// /// * `slice.dimension` - for =. #[prost(string, tag = "2")] pub filter: ::prost::alloc::string::String, /// The standard list page size. #[prost(int32, tag = "3")] pub page_size: i32, /// The standard list page token. /// Typically obtained via /// [ListModelEvaluationSlicesResponse.next_page_token][google.cloud.aiplatform.v1.ListModelEvaluationSlicesResponse.next_page_token] of the previous /// [ModelService.ListModelEvaluationSlices][google.cloud.aiplatform.v1.ModelService.ListModelEvaluationSlices] call. #[prost(string, tag = "4")] pub page_token: ::prost::alloc::string::String, /// Mask specifying which fields to read. #[prost(message, optional, tag = "5")] pub read_mask: ::core::option::Option<::prost_types::FieldMask>, } /// Response message for [ModelService.ListModelEvaluationSlices][google.cloud.aiplatform.v1.ModelService.ListModelEvaluationSlices]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListModelEvaluationSlicesResponse { /// List of ModelEvaluations in the requested page. #[prost(message, repeated, tag = "1")] pub model_evaluation_slices: ::prost::alloc::vec::Vec<ModelEvaluationSlice>, /// A token to retrieve next page of results. /// Pass to [ListModelEvaluationSlicesRequest.page_token][google.cloud.aiplatform.v1.ListModelEvaluationSlicesRequest.page_token] to obtain that /// page. #[prost(string, tag = "2")] pub next_page_token: ::prost::alloc::string::String, } #[doc = r" Generated client implementations."] pub mod model_service_client { #![allow(unused_variables, dead_code, missing_docs)] use tonic::codegen::*; #[doc = " A service for managing AI Platform's machine learning Models."] pub struct ModelServiceClient<T> { inner: tonic::client::Grpc<T>, } impl<T> ModelServiceClient<T> where T: tonic::client::GrpcService<tonic::body::BoxBody>, T::ResponseBody: Body + HttpBody + Send + 'static, T::Error: Into<StdError>, <T::ResponseBody as HttpBody>::Error: Into<StdError> + Send, { pub fn new(inner: T) -> Self { let inner = tonic::client::Grpc::new(inner); Self { inner } } pub fn with_interceptor(inner: T, interceptor: impl Into<tonic::Interceptor>) -> Self { let inner = tonic::client::Grpc::with_interceptor(inner, interceptor); Self { inner } } #[doc = " Uploads a Model artifact into AI Platform."] pub async fn upload_model( &mut self, request: impl tonic::IntoRequest<super::UploadModelRequest>, ) -> Result< tonic::Response<super::super::super::super::longrunning::Operation>, tonic::Status, > { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.ModelService/UploadModel", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Gets a Model."] pub async fn get_model( &mut self, request: impl tonic::IntoRequest<super::GetModelRequest>, ) -> Result<tonic::Response<super::Model>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.ModelService/GetModel", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Lists Models in a Location."] pub async fn list_models( &mut self, request: impl tonic::IntoRequest<super::ListModelsRequest>, ) -> Result<tonic::Response<super::ListModelsResponse>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.ModelService/ListModels", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Updates a Model."] pub async fn update_model( &mut self, request: impl tonic::IntoRequest<super::UpdateModelRequest>, ) -> Result<tonic::Response<super::Model>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.ModelService/UpdateModel", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Deletes a Model."] #[doc = " Note: Model can only be deleted if there are no DeployedModels created"] #[doc = " from it."] pub async fn delete_model( &mut self, request: impl tonic::IntoRequest<super::DeleteModelRequest>, ) -> Result< tonic::Response<super::super::super::super::longrunning::Operation>, tonic::Status, > { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.ModelService/DeleteModel", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Exports a trained, exportable, Model to a location specified by the"] #[doc = " user. A Model is considered to be exportable if it has at least one"] #[doc = " [supported export format][google.cloud.aiplatform.v1.Model.supported_export_formats]."] pub async fn export_model( &mut self, request: impl tonic::IntoRequest<super::ExportModelRequest>, ) -> Result< tonic::Response<super::super::super::super::longrunning::Operation>, tonic::Status, > { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.ModelService/ExportModel", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Gets a ModelEvaluation."] pub async fn get_model_evaluation( &mut self, request: impl tonic::IntoRequest<super::GetModelEvaluationRequest>, ) -> Result<tonic::Response<super::ModelEvaluation>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.ModelService/GetModelEvaluation", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Lists ModelEvaluations in a Model."] pub async fn list_model_evaluations( &mut self, request: impl tonic::IntoRequest<super::ListModelEvaluationsRequest>, ) -> Result<tonic::Response<super::ListModelEvaluationsResponse>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.ModelService/ListModelEvaluations", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Gets a ModelEvaluationSlice."] pub async fn get_model_evaluation_slice( &mut self, request: impl tonic::IntoRequest<super::GetModelEvaluationSliceRequest>, ) -> Result<tonic::Response<super::ModelEvaluationSlice>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.ModelService/GetModelEvaluationSlice", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Lists ModelEvaluationSlices in a ModelEvaluation."] pub async fn list_model_evaluation_slices( &mut self, request: impl tonic::IntoRequest<super::ListModelEvaluationSlicesRequest>, ) -> Result<tonic::Response<super::ListModelEvaluationSlicesResponse>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.ModelService/ListModelEvaluationSlices", ); self.inner.unary(request.into_request(), path, codec).await } } impl<T: Clone> Clone for ModelServiceClient<T> { fn clone(&self) -> Self { Self { inner: self.inner.clone(), } } } impl<T> std::fmt::Debug for ModelServiceClient<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "ModelServiceClient {{ ... }}") } } } /// Request message for [PipelineService.CreateTrainingPipeline][google.cloud.aiplatform.v1.PipelineService.CreateTrainingPipeline]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct CreateTrainingPipelineRequest { /// Required. The resource name of the Location to create the TrainingPipeline in. /// Format: `projects/{project}/locations/{location}` #[prost(string, tag = "1")] pub parent: ::prost::alloc::string::String, /// Required. The TrainingPipeline to create. #[prost(message, optional, tag = "2")] pub training_pipeline: ::core::option::Option<TrainingPipeline>, } /// Request message for [PipelineService.GetTrainingPipeline][google.cloud.aiplatform.v1.PipelineService.GetTrainingPipeline]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct GetTrainingPipelineRequest { /// Required. The name of the TrainingPipeline resource. /// Format: /// /// `projects/{project}/locations/{location}/trainingPipelines/{training_pipeline}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, } /// Request message for [PipelineService.ListTrainingPipelines][google.cloud.aiplatform.v1.PipelineService.ListTrainingPipelines]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListTrainingPipelinesRequest { /// Required. The resource name of the Location to list the TrainingPipelines from. /// Format: `projects/{project}/locations/{location}` #[prost(string, tag = "1")] pub parent: ::prost::alloc::string::String, /// The standard list filter. /// Supported fields: /// /// * `display_name` supports = and !=. /// /// * `state` supports = and !=. /// /// Some examples of using the filter are: /// /// * `state="PIPELINE_STATE_SUCCEEDED" AND display_name="my_pipeline"` /// /// * `state="PIPELINE_STATE_RUNNING" OR display_name="my_pipeline"` /// /// * `NOT display_name="my_pipeline"` /// /// * `state="PIPELINE_STATE_FAILED"` #[prost(string, tag = "2")] pub filter: ::prost::alloc::string::String, /// The standard list page size. #[prost(int32, tag = "3")] pub page_size: i32, /// The standard list page token. /// Typically obtained via /// [ListTrainingPipelinesResponse.next_page_token][google.cloud.aiplatform.v1.ListTrainingPipelinesResponse.next_page_token] of the previous /// [PipelineService.ListTrainingPipelines][google.cloud.aiplatform.v1.PipelineService.ListTrainingPipelines] call. #[prost(string, tag = "4")] pub page_token: ::prost::alloc::string::String, /// Mask specifying which fields to read. #[prost(message, optional, tag = "5")] pub read_mask: ::core::option::Option<::prost_types::FieldMask>, } /// Response message for [PipelineService.ListTrainingPipelines][google.cloud.aiplatform.v1.PipelineService.ListTrainingPipelines] #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListTrainingPipelinesResponse { /// List of TrainingPipelines in the requested page. #[prost(message, repeated, tag = "1")] pub training_pipelines: ::prost::alloc::vec::Vec<TrainingPipeline>, /// A token to retrieve the next page of results. /// Pass to [ListTrainingPipelinesRequest.page_token][google.cloud.aiplatform.v1.ListTrainingPipelinesRequest.page_token] to obtain that page. #[prost(string, tag = "2")] pub next_page_token: ::prost::alloc::string::String, } /// Request message for [PipelineService.DeleteTrainingPipeline][google.cloud.aiplatform.v1.PipelineService.DeleteTrainingPipeline]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DeleteTrainingPipelineRequest { /// Required. The name of the TrainingPipeline resource to be deleted. /// Format: /// /// `projects/{project}/locations/{location}/trainingPipelines/{training_pipeline}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, } /// Request message for [PipelineService.CancelTrainingPipeline][google.cloud.aiplatform.v1.PipelineService.CancelTrainingPipeline]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct CancelTrainingPipelineRequest { /// Required. The name of the TrainingPipeline to cancel. /// Format: /// /// `projects/{project}/locations/{location}/trainingPipelines/{training_pipeline}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, } #[doc = r" Generated client implementations."] pub mod pipeline_service_client { #![allow(unused_variables, dead_code, missing_docs)] use tonic::codegen::*; #[doc = " A service for creating and managing AI Platform's pipelines."] pub struct PipelineServiceClient<T> { inner: tonic::client::Grpc<T>, } impl<T> PipelineServiceClient<T> where T: tonic::client::GrpcService<tonic::body::BoxBody>, T::ResponseBody: Body + HttpBody + Send + 'static, T::Error: Into<StdError>, <T::ResponseBody as HttpBody>::Error: Into<StdError> + Send, { pub fn new(inner: T) -> Self { let inner = tonic::client::Grpc::new(inner); Self { inner } } pub fn with_interceptor(inner: T, interceptor: impl Into<tonic::Interceptor>) -> Self { let inner = tonic::client::Grpc::with_interceptor(inner, interceptor); Self { inner } } #[doc = " Creates a TrainingPipeline. A created TrainingPipeline right away will be"] #[doc = " attempted to be run."] pub async fn create_training_pipeline( &mut self, request: impl tonic::IntoRequest<super::CreateTrainingPipelineRequest>, ) -> Result<tonic::Response<super::TrainingPipeline>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.PipelineService/CreateTrainingPipeline", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Gets a TrainingPipeline."] pub async fn get_training_pipeline( &mut self, request: impl tonic::IntoRequest<super::GetTrainingPipelineRequest>, ) -> Result<tonic::Response<super::TrainingPipeline>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.PipelineService/GetTrainingPipeline", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Lists TrainingPipelines in a Location."] pub async fn list_training_pipelines( &mut self, request: impl tonic::IntoRequest<super::ListTrainingPipelinesRequest>, ) -> Result<tonic::Response<super::ListTrainingPipelinesResponse>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.PipelineService/ListTrainingPipelines", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Deletes a TrainingPipeline."] pub async fn delete_training_pipeline( &mut self, request: impl tonic::IntoRequest<super::DeleteTrainingPipelineRequest>, ) -> Result< tonic::Response<super::super::super::super::longrunning::Operation>, tonic::Status, > { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.PipelineService/DeleteTrainingPipeline", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Cancels a TrainingPipeline."] #[doc = " Starts asynchronous cancellation on the TrainingPipeline. The server"] #[doc = " makes a best effort to cancel the pipeline, but success is not"] #[doc = " guaranteed. Clients can use [PipelineService.GetTrainingPipeline][google.cloud.aiplatform.v1.PipelineService.GetTrainingPipeline] or"] #[doc = " other methods to check whether the cancellation succeeded or whether the"] #[doc = " pipeline completed despite cancellation. On successful cancellation,"] #[doc = " the TrainingPipeline is not deleted; instead it becomes a pipeline with"] #[doc = " a [TrainingPipeline.error][google.cloud.aiplatform.v1.TrainingPipeline.error] value with a [google.rpc.Status.code][google.rpc.Status.code] of 1,"] #[doc = " corresponding to `Code.CANCELLED`, and [TrainingPipeline.state][google.cloud.aiplatform.v1.TrainingPipeline.state] is set to"] #[doc = " `CANCELLED`."] pub async fn cancel_training_pipeline( &mut self, request: impl tonic::IntoRequest<super::CancelTrainingPipelineRequest>, ) -> Result<tonic::Response<()>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.PipelineService/CancelTrainingPipeline", ); self.inner.unary(request.into_request(), path, codec).await } } impl<T: Clone> Clone for PipelineServiceClient<T> { fn clone(&self) -> Self { Self { inner: self.inner.clone(), } } } impl<T> std::fmt::Debug for PipelineServiceClient<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "PipelineServiceClient {{ ... }}") } } } /// Request message for [PredictionService.Predict][google.cloud.aiplatform.v1.PredictionService.Predict]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct PredictRequest { /// Required. The name of the Endpoint requested to serve the prediction. /// Format: /// `projects/{project}/locations/{location}/endpoints/{endpoint}` #[prost(string, tag = "1")] pub endpoint: ::prost::alloc::string::String, /// Required. The instances that are the input to the prediction call. /// A DeployedModel may have an upper limit on the number of instances it /// supports per request, and when it is exceeded the prediction call errors /// in case of AutoML Models, or, in case of customer created Models, the /// behaviour is as documented by that Model. /// The schema of any single instance may be specified via Endpoint's /// DeployedModels' [Model's][google.cloud.aiplatform.v1.DeployedModel.model] /// [PredictSchemata's][google.cloud.aiplatform.v1.Model.predict_schemata] /// [instance_schema_uri][google.cloud.aiplatform.v1.PredictSchemata.instance_schema_uri]. #[prost(message, repeated, tag = "2")] pub instances: ::prost::alloc::vec::Vec<::prost_types::Value>, /// The parameters that govern the prediction. The schema of the parameters may /// be specified via Endpoint's DeployedModels' [Model's ][google.cloud.aiplatform.v1.DeployedModel.model] /// [PredictSchemata's][google.cloud.aiplatform.v1.Model.predict_schemata] /// [parameters_schema_uri][google.cloud.aiplatform.v1.PredictSchemata.parameters_schema_uri]. #[prost(message, optional, tag = "3")] pub parameters: ::core::option::Option<::prost_types::Value>, } /// Response message for [PredictionService.Predict][google.cloud.aiplatform.v1.PredictionService.Predict]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct PredictResponse { /// The predictions that are the output of the predictions call. /// The schema of any single prediction may be specified via Endpoint's /// DeployedModels' [Model's ][google.cloud.aiplatform.v1.DeployedModel.model] /// [PredictSchemata's][google.cloud.aiplatform.v1.Model.predict_schemata] /// [prediction_schema_uri][google.cloud.aiplatform.v1.PredictSchemata.prediction_schema_uri]. #[prost(message, repeated, tag = "1")] pub predictions: ::prost::alloc::vec::Vec<::prost_types::Value>, /// ID of the Endpoint's DeployedModel that served this prediction. #[prost(string, tag = "2")] pub deployed_model_id: ::prost::alloc::string::String, } #[doc = r" Generated client implementations."] pub mod prediction_service_client { #![allow(unused_variables, dead_code, missing_docs)] use tonic::codegen::*; #[doc = " A service for online predictions and explanations."] pub struct PredictionServiceClient<T> { inner: tonic::client::Grpc<T>, } impl<T> PredictionServiceClient<T> where T: tonic::client::GrpcService<tonic::body::BoxBody>, T::ResponseBody: Body + HttpBody + Send + 'static, T::Error: Into<StdError>, <T::ResponseBody as HttpBody>::Error: Into<StdError> + Send, { pub fn new(inner: T) -> Self { let inner = tonic::client::Grpc::new(inner); Self { inner } } pub fn with_interceptor(inner: T, interceptor: impl Into<tonic::Interceptor>) -> Self { let inner = tonic::client::Grpc::with_interceptor(inner, interceptor); Self { inner } } #[doc = " Perform an online prediction."] pub async fn predict( &mut self, request: impl tonic::IntoRequest<super::PredictRequest>, ) -> Result<tonic::Response<super::PredictResponse>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.PredictionService/Predict", ); self.inner.unary(request.into_request(), path, codec).await } } impl<T: Clone> Clone for PredictionServiceClient<T> { fn clone(&self) -> Self { Self { inner: self.inner.clone(), } } } impl<T> std::fmt::Debug for PredictionServiceClient<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "PredictionServiceClient {{ ... }}") } } } /// Request message for [SpecialistPoolService.CreateSpecialistPool][google.cloud.aiplatform.v1.SpecialistPoolService.CreateSpecialistPool]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct CreateSpecialistPoolRequest { /// Required. The parent Project name for the new SpecialistPool. /// The form is `projects/{project}/locations/{location}`. #[prost(string, tag = "1")] pub parent: ::prost::alloc::string::String, /// Required. The SpecialistPool to create. #[prost(message, optional, tag = "2")] pub specialist_pool: ::core::option::Option<SpecialistPool>, } /// Runtime operation information for /// [SpecialistPoolService.CreateSpecialistPool][google.cloud.aiplatform.v1.SpecialistPoolService.CreateSpecialistPool]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct CreateSpecialistPoolOperationMetadata { /// The operation generic information. #[prost(message, optional, tag = "1")] pub generic_metadata: ::core::option::Option<GenericOperationMetadata>, } /// Request message for [SpecialistPoolService.GetSpecialistPool][google.cloud.aiplatform.v1.SpecialistPoolService.GetSpecialistPool]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct GetSpecialistPoolRequest { /// Required. The name of the SpecialistPool resource. /// The form is /// /// `projects/{project}/locations/{location}/specialistPools/{specialist_pool}`. #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, } /// Request message for [SpecialistPoolService.ListSpecialistPools][google.cloud.aiplatform.v1.SpecialistPoolService.ListSpecialistPools]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListSpecialistPoolsRequest { /// Required. The name of the SpecialistPool's parent resource. /// Format: `projects/{project}/locations/{location}` #[prost(string, tag = "1")] pub parent: ::prost::alloc::string::String, /// The standard list page size. #[prost(int32, tag = "2")] pub page_size: i32, /// The standard list page token. /// Typically obtained by [ListSpecialistPoolsResponse.next_page_token][google.cloud.aiplatform.v1.ListSpecialistPoolsResponse.next_page_token] of /// the previous [SpecialistPoolService.ListSpecialistPools][google.cloud.aiplatform.v1.SpecialistPoolService.ListSpecialistPools] call. Return /// first page if empty. #[prost(string, tag = "3")] pub page_token: ::prost::alloc::string::String, /// Mask specifying which fields to read. FieldMask represents a set of #[prost(message, optional, tag = "4")] pub read_mask: ::core::option::Option<::prost_types::FieldMask>, } /// Response message for [SpecialistPoolService.ListSpecialistPools][google.cloud.aiplatform.v1.SpecialistPoolService.ListSpecialistPools]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct ListSpecialistPoolsResponse { /// A list of SpecialistPools that matches the specified filter in the request. #[prost(message, repeated, tag = "1")] pub specialist_pools: ::prost::alloc::vec::Vec<SpecialistPool>, /// The standard List next-page token. #[prost(string, tag = "2")] pub next_page_token: ::prost::alloc::string::String, } /// Request message for [SpecialistPoolService.DeleteSpecialistPool][google.cloud.aiplatform.v1.SpecialistPoolService.DeleteSpecialistPool]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DeleteSpecialistPoolRequest { /// Required. The resource name of the SpecialistPool to delete. Format: /// `projects/{project}/locations/{location}/specialistPools/{specialist_pool}` #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, /// If set to true, any specialist managers in this SpecialistPool will also be /// deleted. (Otherwise, the request will only work if the SpecialistPool has /// no specialist managers.) #[prost(bool, tag = "2")] pub force: bool, } /// Request message for [SpecialistPoolService.UpdateSpecialistPool][google.cloud.aiplatform.v1.SpecialistPoolService.UpdateSpecialistPool]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct UpdateSpecialistPoolRequest { /// Required. The SpecialistPool which replaces the resource on the server. #[prost(message, optional, tag = "1")] pub specialist_pool: ::core::option::Option<SpecialistPool>, /// Required. The update mask applies to the resource. #[prost(message, optional, tag = "2")] pub update_mask: ::core::option::Option<::prost_types::FieldMask>, } /// Runtime operation metadata for /// [SpecialistPoolService.UpdateSpecialistPool][google.cloud.aiplatform.v1.SpecialistPoolService.UpdateSpecialistPool]. #[derive(Clone, PartialEq, ::prost::Message)] pub struct UpdateSpecialistPoolOperationMetadata { /// Output only. The name of the SpecialistPool to which the specialists are being added. /// Format: /// /// `projects/{project_id}/locations/{location_id}/specialistPools/{specialist_pool}` #[prost(string, tag = "1")] pub specialist_pool: ::prost::alloc::string::String, /// The operation generic information. #[prost(message, optional, tag = "2")] pub generic_metadata: ::core::option::Option<GenericOperationMetadata>, } #[doc = r" Generated client implementations."] pub mod specialist_pool_service_client { #![allow(unused_variables, dead_code, missing_docs)] use tonic::codegen::*; #[doc = " A service for creating and managing Customer SpecialistPools."] #[doc = " When customers start Data Labeling jobs, they can reuse/create Specialist"] #[doc = " Pools to bring their own Specialists to label the data."] #[doc = " Customers can add/remove Managers for the Specialist Pool on Cloud console,"] #[doc = " then Managers will get email notifications to manage Specialists and tasks on"] #[doc = " CrowdCompute console."] pub struct SpecialistPoolServiceClient<T> { inner: tonic::client::Grpc<T>, } impl<T> SpecialistPoolServiceClient<T> where T: tonic::client::GrpcService<tonic::body::BoxBody>, T::ResponseBody: Body + HttpBody + Send + 'static, T::Error: Into<StdError>, <T::ResponseBody as HttpBody>::Error: Into<StdError> + Send, { pub fn new(inner: T) -> Self { let inner = tonic::client::Grpc::new(inner); Self { inner } } pub fn with_interceptor(inner: T, interceptor: impl Into<tonic::Interceptor>) -> Self { let inner = tonic::client::Grpc::with_interceptor(inner, interceptor); Self { inner } } #[doc = " Creates a SpecialistPool."] pub async fn create_specialist_pool( &mut self, request: impl tonic::IntoRequest<super::CreateSpecialistPoolRequest>, ) -> Result< tonic::Response<super::super::super::super::longrunning::Operation>, tonic::Status, > { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.SpecialistPoolService/CreateSpecialistPool", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Gets a SpecialistPool."] pub async fn get_specialist_pool( &mut self, request: impl tonic::IntoRequest<super::GetSpecialistPoolRequest>, ) -> Result<tonic::Response<super::SpecialistPool>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.SpecialistPoolService/GetSpecialistPool", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Lists SpecialistPools in a Location."] pub async fn list_specialist_pools( &mut self, request: impl tonic::IntoRequest<super::ListSpecialistPoolsRequest>, ) -> Result<tonic::Response<super::ListSpecialistPoolsResponse>, tonic::Status> { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.SpecialistPoolService/ListSpecialistPools", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Deletes a SpecialistPool as well as all Specialists in the pool."] pub async fn delete_specialist_pool( &mut self, request: impl tonic::IntoRequest<super::DeleteSpecialistPoolRequest>, ) -> Result< tonic::Response<super::super::super::super::longrunning::Operation>, tonic::Status, > { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.SpecialistPoolService/DeleteSpecialistPool", ); self.inner.unary(request.into_request(), path, codec).await } #[doc = " Updates a SpecialistPool."] pub async fn update_specialist_pool( &mut self, request: impl tonic::IntoRequest<super::UpdateSpecialistPoolRequest>, ) -> Result< tonic::Response<super::super::super::super::longrunning::Operation>, tonic::Status, > { self.inner.ready().await.map_err(|e| { tonic::Status::new( tonic::Code::Unknown, format!("Service was not ready: {}", e.into()), ) })?; let codec = tonic::codec::ProstCodec::default(); let path = http::uri::PathAndQuery::from_static( "/google.cloud.aiplatform.v1.SpecialistPoolService/UpdateSpecialistPool", ); self.inner.unary(request.into_request(), path, codec).await } } impl<T: Clone> Clone for SpecialistPoolServiceClient<T> { fn clone(&self) -> Self { Self { inner: self.inner.clone(), } } } impl<T> std::fmt::Debug for SpecialistPoolServiceClient<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "SpecialistPoolServiceClient {{ ... }}") } } }
51.037293
173
0.651383
cc4d246a9a15f8e1cd66cdedff955ede66d5328b
3,352
use crate::tensor::backend; use crate::tensor::backend::vulkan::processor::Processor; use std::rc::Rc; use std::sync::Arc; use vulkano::buffer::{BufferUsage, CpuAccessibleBuffer}; use vulkano::device::{Device, DeviceExtensions, Queue, QueuesIter}; use vulkano::instance::{Instance, InstanceExtensions, PhysicalDevice}; #[macro_use] mod processor; mod shader; #[derive(Clone)] pub struct Backend { device: Arc<Device>, processor: Rc<Processor>, } impl Backend { pub fn new() -> Self { // create instance let app_infos = app_info_from_cargo_toml!(); let instance = Instance::new(Some(&app_infos), &InstanceExtensions::none(), None) .expect("No Vulkan implementations available."); // create device let (device, mut queues) = Self::get_device(&instance); let queue = queues.next().unwrap(); let processor = Rc::new(Processor::new(device.clone(), queue)); let backend = Backend { device, processor }; backend } fn get_device(instance: &Arc<Instance>) -> (Arc<Device>, QueuesIter) { // select device at index 0 let physical_device = PhysicalDevice::from_index(&instance, 0) .expect("Failed to get the specified physical device."); let queue_family = physical_device .queue_families() .find(|&q| q.supports_compute()) .expect("Couldn't find a compute queue family."); let device_extensions = DeviceExtensions { khr_storage_buffer_storage_class: true, ..DeviceExtensions::none() }; Device::new( physical_device, physical_device.supported_features(), &device_extensions, [(queue_family, 0.5)].iter().cloned(), ) .expect("failed to create device") } } impl backend::Backend for Backend { fn alloc_mem(&self, size: usize) -> Rc<dyn backend::Buffer<Backend = Backend>> { Rc::new(Buffer::new(size, self.clone())) } fn alloc_mem_from_iter<I>(&self, data: I) -> Rc<dyn backend::Buffer<Backend = Backend>> where I: ExactSizeIterator<Item = f32>, { Rc::new(Buffer::from_iter(data, self.clone())) } fn processor(&self) -> &dyn backend::Processor { self.processor.as_ref() } } pub struct Buffer { backend: Backend, data: Arc<CpuAccessibleBuffer<[f32]>>, } impl Buffer { pub fn new(size: usize, backend: Backend) -> Self { unsafe { Buffer { backend, data: CpuAccessibleBuffer::uninitialized_array( backend.device.clone(), size, BufferUsage::all(), false, ) .unwrap(), } } } pub fn from_iter<I>(data: I, backend: Backend) -> Self where I: ExactSizeIterator<Item = f32>, { Buffer { backend, data: CpuAccessibleBuffer::from_iter( backend.device.clone(), BufferUsage::all(), false, data, ) .unwrap(), } } pub fn downcast(buffer: &dyn backend::Buffer<Backend = Backend>) -> &Self { buffer.as_any().downcast_ref::<Self>().unwrap() } }
27.933333
91
0.566826
3aa652a617d2f91c2cd7a7546ae7bad3efdf96dc
660
use std::future::Future; use crate::{Endpoint, Request, Result}; /// Endpoint for the [`before`](super::EndpointExt::before) method. pub struct Before<E, F> { inner: E, f: F, } impl<E, F> Before<E, F> { #[inline] pub(crate) fn new(inner: E, f: F) -> Before<E, F> { Self { inner, f } } } #[async_trait::async_trait] impl<E, F, Fut> Endpoint for Before<E, F> where E: Endpoint, F: Fn(Request) -> Fut + Send + Sync, Fut: Future<Output = Result<Request>> + Send, { type Output = E::Output; async fn call(&self, req: Request) -> Result<Self::Output> { self.inner.call((self.f)(req).await?).await } }
21.290323
67
0.583333
1c131c3e91dfd6b6ec7ccd9dd9b7d190dc87d386
1,938
// Copyright Amazon.com, Inc. or its affiliates. use std::env; use std::path::PathBuf; /// Makes it easier to construct PathBufs instead of format!() which doesn't /// produce portable path separators. macro_rules! mkpath { ( $($x:expr),* ) => { { let mut buf = PathBuf::new(); $( buf.push($x); )* buf } }; } fn main() { let ionc_path = cmake::Config::new("ion-c").build(); let lib_suffixes = &["lib", "lib64"]; for lib_suffix in lib_suffixes { let ionc_lib_path = mkpath!(&ionc_path, lib_suffix); println!("cargo:rustc-link-search=native={}", ionc_lib_path.display()); } println!("cargo:rustc-link-lib=static=decNumber_static"); println!("cargo:rustc-link-lib=static=ionc_static"); let ionc_inc_path = mkpath!(&ionc_path, "include"); let ionc_internal_inc_path = mkpath!("ion-c/ionc"); let ionc_main_header_path = mkpath!("bindings.h"); let bindings = bindgen::Builder::default() .header(ionc_main_header_path.to_str().unwrap()) // make sure we can find all the relevant headers .clang_arg(format!("-I{}", ionc_inc_path.display())) .clang_arg(format!("-I{}", ionc_internal_inc_path.display())) // defined in IonC's CMake configuration. // See https://github.com/amzn/ion-c/blob/1e911eb689a879427aa8842fe2ca7c78546aeed1/CMakeLists.txt#L22-L26 // for details. .clang_arg("-DDECNUMDIGITS=34") // invalidate the build whenever underlying headers change .parse_callbacks(Box::new(bindgen::CargoCallbacks)) .derive_default(true) .generate() .expect("Unable to generate bindings"); // emit the bindings let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); bindings .write_to_file(out_path.join("ionc_bindings.rs")) .expect("Couldn't write bindings"); }
34
113
0.624355
8ab81684a00eecbcb2cfba7fd5282e2f77614dbb
6,059
extern crate bytes; pub(crate) mod connection; mod metrics; mod readyqueue; mod router; mod slab; mod tracker; use connection::Connection; pub use router::Router; pub use tracker::Tracker; use self::bytes::Bytes; pub use crate::router::metrics::{ConnectionMetrics, MetricsReply, MetricsRequest}; use mqttbytes::Packet; use serde::{Deserialize, Serialize}; use std::fmt; /// Messages from connection to router #[derive(Debug)] pub enum Event { /// Client id and connection handle Connect(Connection), /// Connection ready to receive more data Ready, /// Data for native commitlog Data(Vec<Packet>), /// Disconnection request Disconnect(Disconnection), /// Get metrics of a connection or all connections Metrics(MetricsRequest), } /// Requests for pull operations #[derive(Debug, PartialEq, Clone, Serialize, Deserialize)] pub enum Request { /// Data request Data(DataRequest), /// Topics request Topics(TopicsRequest), /// Acks request Acks(AcksRequest), } /// Notification from router to connection #[derive(Debug)] pub enum Notification { /// Connection reply ConnectionAck(ConnectionAck), /// Individual publish Message(Message), /// Data reply Data(Data), /// Watermarks reply Acks(Vec<Packet>), /// Connection paused by router Pause, /// All metrics Metrics(MetricsReply), } /// Request that connection/linker makes to extract data from commitlog /// NOTE Connection can make one sweep request to get data from multiple topics /// but we'll keep it simple for now as multiple requests in one message can /// makes constant extraction size harder #[derive(Clone, PartialEq, Serialize, Deserialize)] pub struct DataRequest { /// Log to sweep pub(crate) topic: String, /// QoS of the request pub(crate) qos: u8, /// (segment, offset) tuples per replica (1 native and 2 replicas) pub(crate) cursor: (u64, u64), /// Last retain id pub(crate) last_retain: u64, /// Maximum count of payload buffer per replica max_count: usize, } impl DataRequest { /// New data request with offsets starting from 0 pub fn new(topic: String, qos: u8) -> DataRequest { DataRequest { topic, qos, cursor: (0, 0), last_retain: 0, max_count: 100, } } /// New data request with provided offsets pub fn offsets( topic: String, qos: u8, cursor: (u64, u64), last_retain: u64, ) -> DataRequest { DataRequest { topic, qos, cursor, last_retain, max_count: 100, } } } impl fmt::Debug for DataRequest { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "Topic = {}, cursors = {:?}, max_count = {}", self.topic, self.cursor, self.max_count ) } } pub struct Message { /// Log to sweep pub topic: String, /// Qos of the topic pub qos: u8, /// Reply data chain pub payload: Bytes, } impl Message { pub fn new(topic: String, qos: u8, payload: Bytes) -> Message { Message { topic, payload, qos, } } } impl fmt::Debug for Message { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "Topic = {:?}, Payload size = {}", self.topic, self.payload.len() ) } } pub struct Data { /// Log to sweep pub topic: String, /// Qos of the topic pub qos: u8, /// (segment, offset) tuples per replica (1 native and 2 replicas) pub cursor: (u64, u64), /// Next retain publish id pub last_retain: u64, /// Payload size pub size: usize, /// Reply data chain pub payload: Vec<Bytes>, } impl Data { pub fn new( topic: String, qos: u8, cursor: (u64, u64), last_retain: u64, size: usize, payload: Vec<Bytes>, ) -> Data { Data { topic, cursor, last_retain, size, payload, qos, } } } impl fmt::Debug for Data { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "Topic = {:?}, Cursors = {:?}, Payload size = {}, Payload count = {}", self.topic, self.cursor, self.size, self.payload.len() ) } } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct TopicsRequest { /// Start from this offset offset: usize, /// Maximum number of topics to read count: usize, } impl TopicsRequest { pub fn new() -> TopicsRequest { TopicsRequest { offset: 0, count: 10, } } pub fn set_count(&mut self, count: usize) { self.count = count; } pub fn offset(offset: usize) -> TopicsRequest { TopicsRequest { offset, count: 10 } } } pub struct Topics<'a> { offset: usize, topics: &'a [String], } impl<'a> Topics<'a> { pub fn new(offset: usize, topics: &'a [String]) -> Topics { Topics { offset, topics } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AcksRequest; impl AcksRequest { pub fn new() -> AcksRequest { AcksRequest } } #[derive(Debug)] pub enum ConnectionAck { /// Id assigned by the router for this connection and /// previous session status Success((usize, bool, Vec<Notification>)), /// Failure and reason for failure string Failure(String), } #[derive(Debug)] pub struct Disconnection { id: String, execute_will: bool, pending: Vec<Notification>, } impl Disconnection { pub fn new(id: String, execute_will: bool, pending: Vec<Notification>) -> Disconnection { Disconnection { id, execute_will, pending, } } }
22.608209
93
0.574847
cc6da5531002d83af409345e54c5a21895a5ec03
20,368
//! Contains all structures and methods to create and manage transforms. //! //! Transform allows you to combine spatial properties into single matrix in //! easy manner. It contains many methods that can be used to modify a single //! property of transform which then will be "baked" into single matrix. //! //! # Complexity //! //! rg3d uses complex transform model inherited from FBX transform formulae: //! //! http://download.autodesk.com/us/fbx/20112/FBX_SDK_HELP/index.html?url=WS1a9193826455f5ff1f92379812724681e696651.htm,topicNumber=d0e7429 //! //! Transform = T * Roff * Rp * Rpre * R * Rpost * Rp⁻¹ * Soff * Sp * S * Sp⁻¹ //! //! where //! T - Translation //! Roff - Rotation offset //! Rp - Rotation pivot //! Rpre - Pre-rotation //! R - Rotation //! Rpost - Post-rotation //! Rp⁻¹ - Inverse of the rotation pivot //! Soff - Scaling offset //! Sp - Scaling pivot //! S - Scaling //! Sp⁻¹ - Inverse of the scaling pivot //! //! It is very flexible, however it can be slow in computation. To solve possible //! performance issues, rg3d tries to precache every possible component. This means //! that we use lazy evaluation: you can setup all required properties, and actual //! calculations will be delayed until you try to get matrix from transform. This makes //! calculations faster, but increases required amount of memory. //! //! In most cases you don't need to bother about all those properties, you need just T R S - //! it will cover 99% of requirements. //! //! Fun fact: transform format was dictated by the use of monster called FBX file format. //! Some libraries (like assimp) decomposes this complex formula into set of smaller transforms //! which are contains only T R S components and then combine them to get final result, I find //! this approach very bug prone, and it is still heavy from computation side. It is much //! easier to use it as is. //! //! # Decomposition //! //! Once transform baked into matrix, it is *almost* impossible to decompose it back into //! initial components, thats why engine does not provide any methods to get those //! properties back. use crate::{ core::{ algebra::{Matrix3, Matrix4, UnitQuaternion, Vector3}, visitor::{Visit, VisitResult, Visitor}, }, scene::TemplateVariable, utils::log::{Log, MessageKind}, }; use std::cell::Cell; /// See module docs. #[derive(Clone, Debug)] pub struct Transform { /// Indicates that some property has changed and matrix must be /// recalculated before use. This is some sort of lazy evaluation. dirty: Cell<bool>, local_scale: TemplateVariable<Vector3<f32>>, local_position: TemplateVariable<Vector3<f32>>, local_rotation: TemplateVariable<UnitQuaternion<f32>>, pre_rotation: TemplateVariable<UnitQuaternion<f32>>, post_rotation: TemplateVariable<UnitQuaternion<f32>>, rotation_offset: TemplateVariable<Vector3<f32>>, rotation_pivot: TemplateVariable<Vector3<f32>>, scaling_offset: TemplateVariable<Vector3<f32>>, scaling_pivot: TemplateVariable<Vector3<f32>>, /// Combined transform. Final result of combination of other properties. matrix: Cell<Matrix4<f32>>, post_rotation_matrix: Matrix3<f32>, } /// Helper to load old versions. fn compatibility_visit<T: Default + Visit>( value: &mut TemplateVariable<T>, name: &str, visitor: &mut Visitor, ) -> VisitResult { if value.visit(name, visitor).is_err() { // Try visit inner value. let mut inner = T::default(); inner.visit(name, visitor)?; *value = TemplateVariable::new_custom(inner); } Ok(()) } impl Visit for Transform { fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult { visitor.enter_region(name)?; compatibility_visit(&mut self.local_scale, "LocalScale", visitor)?; compatibility_visit(&mut self.local_position, "LocalPosition", visitor)?; compatibility_visit(&mut self.local_rotation, "LocalRotation", visitor)?; compatibility_visit(&mut self.pre_rotation, "PreRotation", visitor)?; compatibility_visit(&mut self.post_rotation, "PostRotation", visitor)?; compatibility_visit(&mut self.rotation_offset, "RotationOffset", visitor)?; compatibility_visit(&mut self.rotation_pivot, "RotationPivot", visitor)?; compatibility_visit(&mut self.scaling_offset, "ScalingOffset", visitor)?; compatibility_visit(&mut self.scaling_pivot, "ScalingPivot", visitor)?; if visitor.is_reading() { self.post_rotation_matrix = build_post_rotation_matrix(self.post_rotation.clone_inner()); } visitor.leave_region() } } impl Default for Transform { fn default() -> Self { Self::identity() } } fn build_post_rotation_matrix(post_rotation: UnitQuaternion<f32>) -> Matrix3<f32> { post_rotation .to_rotation_matrix() .matrix() .try_inverse() .unwrap_or_else(|| { Log::writeln( MessageKind::Warning, "Unable to inverse post rotation matrix! Fallback to identity matrix.".to_owned(), ); Matrix3::identity() }) } impl Transform { /// Creates new transform that has no effect, in other words any vector /// or matrix will remain unchanged if combined with identity transform. pub fn identity() -> Self { Self { dirty: Cell::new(true), local_position: TemplateVariable::new(Vector3::default()), local_scale: TemplateVariable::new(Vector3::new(1.0, 1.0, 1.0)), local_rotation: TemplateVariable::new(UnitQuaternion::identity()), pre_rotation: TemplateVariable::new(UnitQuaternion::identity()), post_rotation: TemplateVariable::new(UnitQuaternion::identity()), rotation_offset: TemplateVariable::new(Vector3::default()), rotation_pivot: TemplateVariable::new(Vector3::default()), scaling_offset: TemplateVariable::new(Vector3::default()), scaling_pivot: TemplateVariable::new(Vector3::default()), matrix: Cell::new(Matrix4::identity()), post_rotation_matrix: Matrix3::identity(), } } /// Returns current position of transform. #[inline] pub fn position(&self) -> &TemplateVariable<Vector3<f32>> { &self.local_position } /// Sets position of transform. #[inline] pub fn set_position(&mut self, local_position: Vector3<f32>) -> &mut Self { if self.dirty.get() || *self.local_position != local_position { self.local_position.set(local_position); self.dirty.set(true); } self } /// Returns current rotation quaternion of transform. #[inline] pub fn rotation(&self) -> &TemplateVariable<UnitQuaternion<f32>> { &self.local_rotation } /// Sets rotation of transform. #[inline] pub fn set_rotation(&mut self, local_rotation: UnitQuaternion<f32>) -> &mut Self { if self.dirty.get() || *self.local_rotation != local_rotation { self.local_rotation.set(local_rotation); self.dirty.set(true); } self } /// Returns current scale factor of transform. #[inline] pub fn scale(&self) -> &TemplateVariable<Vector3<f32>> { &self.local_scale } /// Sets scale of transform. It is strongly advised to use only uniform scaling, /// non-uniform is possible but it can lead to very "interesting" effects, also /// non-uniform scaling possible will be removed in future, especially if engine /// migrate to some full-featured physics engine. #[inline] pub fn set_scale(&mut self, local_scale: Vector3<f32>) -> &mut Self { if self.dirty.get() || *self.local_scale != local_scale { self.local_scale.set(local_scale); self.dirty.set(true); } self } /// Sets pre-rotation of transform. Usually pre-rotation can be used to change /// "coordinate" system of transform. It is mostly for FBX compatibility, and /// never used in other places of engine. #[inline] pub fn set_pre_rotation(&mut self, pre_rotation: UnitQuaternion<f32>) -> &mut Self { if self.dirty.get() || *self.pre_rotation != pre_rotation { self.pre_rotation.set(pre_rotation); self.dirty.set(true); } self } /// Returns current pre-rotation of transform. #[inline] pub fn pre_rotation(&self) -> &TemplateVariable<UnitQuaternion<f32>> { &self.pre_rotation } /// Sets post-rotation of transform. Usually post-rotation can be used to change /// "coordinate" system of transform. It is mostly for FBX compatibility, and /// never used in other places of engine. #[inline] pub fn set_post_rotation(&mut self, post_rotation: UnitQuaternion<f32>) -> &mut Self { if self.dirty.get() || *self.post_rotation != post_rotation { self.post_rotation.set(post_rotation); self.post_rotation_matrix = build_post_rotation_matrix(self.post_rotation.clone_inner()); self.dirty.set(true); } self } /// Returns current post-rotation of transform. #[inline] pub fn post_rotation(&self) -> &TemplateVariable<UnitQuaternion<f32>> { &self.post_rotation } /// Sets rotation offset of transform. Moves rotation pivot using given vector, /// it results in rotation being performed around rotation pivot with some offset. #[inline] pub fn set_rotation_offset(&mut self, rotation_offset: Vector3<f32>) -> &mut Self { if self.dirty.get() || *self.rotation_offset != rotation_offset { self.rotation_offset.set(rotation_offset); self.dirty.set(true); } self } /// Returns current rotation offset of transform. #[inline] pub fn rotation_offset(&self) -> &TemplateVariable<Vector3<f32>> { &self.rotation_offset } /// Sets rotation pivot of transform. This method sets a point around which all /// rotations will be performed. For example it can be used to rotate a cube around /// its vertex. #[inline] pub fn set_rotation_pivot(&mut self, rotation_pivot: Vector3<f32>) -> &mut Self { if self.dirty.get() || *self.rotation_pivot != rotation_pivot { self.rotation_pivot.set(rotation_pivot); self.dirty.set(true); } self } /// Returns current rotation pivot of transform. #[inline] pub fn rotation_pivot(&self) -> &TemplateVariable<Vector3<f32>> { &self.rotation_pivot } /// Sets scaling offset. Scaling offset defines offset from position of scaling /// pivot. #[inline] pub fn set_scaling_offset(&mut self, scaling_offset: Vector3<f32>) -> &mut Self { if self.dirty.get() || *self.scaling_offset != scaling_offset { self.scaling_offset.set(scaling_offset); self.dirty.set(true); } self } /// Returns current scaling offset of transform. #[inline] pub fn scaling_offset(&self) -> &TemplateVariable<Vector3<f32>> { &self.scaling_offset } /// Sets scaling pivot. Scaling pivot sets a point around which scale will be /// performed. #[inline] pub fn set_scaling_pivot(&mut self, scaling_pivot: Vector3<f32>) -> &mut Self { if self.dirty.get() || *self.scaling_pivot != scaling_pivot { self.scaling_pivot.set(scaling_pivot); self.dirty.set(true); } self } /// Returns current scaling pivot of transform. #[inline] pub fn scaling_pivot(&self) -> &TemplateVariable<Vector3<f32>> { &self.scaling_pivot } /// Shifts local position using given vector. It is a shortcut for: /// set_position(position() + offset) #[inline] pub fn offset(&mut self, vec: Vector3<f32>) -> &mut Self { self.local_position.set(*self.local_position + vec); self.dirty.set(true); self } fn calculate_local_transform(&self) -> Matrix4<f32> { // Make shortcuts to remove visual clutter. let por = &self.post_rotation_matrix; let pr = *self.pre_rotation.to_rotation_matrix().matrix(); let r = *self.local_rotation.to_rotation_matrix().matrix(); let sx = self.local_scale.x; let sy = self.local_scale.y; let sz = self.local_scale.z; let tx = self.local_position.x; let ty = self.local_position.y; let tz = self.local_position.z; let rpx = self.rotation_pivot.x; let rpy = self.rotation_pivot.y; let rpz = self.rotation_pivot.z; let rox = self.rotation_offset.x; let roy = self.rotation_offset.y; let roz = self.rotation_offset.z; let spx = self.scaling_pivot.x; let spy = self.scaling_pivot.y; let spz = self.scaling_pivot.z; let sox = self.scaling_offset.x; let soy = self.scaling_offset.y; let soz = self.scaling_offset.z; // Optimized multiplication of these matrices: // // Transform = T * Roff * Rp * Rpre * R * Rpost * Rp⁻¹ * Soff * Sp * S * Sp⁻¹ // // where // T - Translation // Roff - Rotation offset // Rp - Rotation pivot // Rpre - Pre-rotation // R - Rotation // Rpost - Post-rotation // Rp⁻¹ - Inverse of the rotation pivot // Soff - Scaling offset // Sp - Scaling pivot // S - Scaling // Sp⁻¹ - Inverse of the scaling pivot let a0 = pr[0] * r[0] + pr[3] * r[1] + pr[6] * r[2]; let a1 = pr[1] * r[0] + pr[4] * r[1] + pr[7] * r[2]; let a2 = pr[2] * r[0] + pr[5] * r[1] + pr[8] * r[2]; let a3 = pr[0] * r[3] + pr[3] * r[4] + pr[6] * r[5]; let a4 = pr[1] * r[3] + pr[4] * r[4] + pr[7] * r[5]; let a5 = pr[2] * r[3] + pr[5] * r[4] + pr[8] * r[5]; let a6 = pr[0] * r[6] + pr[3] * r[7] + pr[6] * r[8]; let a7 = pr[1] * r[6] + pr[4] * r[7] + pr[7] * r[8]; let a8 = pr[2] * r[6] + pr[5] * r[7] + pr[8] * r[8]; let f0 = por[0] * a0 + por[1] * a3 + por[2] * a6; let f1 = por[0] * a1 + por[1] * a4 + por[2] * a7; let f2 = por[0] * a2 + por[1] * a5 + por[2] * a8; let f3 = por[3] * a0 + por[4] * a3 + por[5] * a6; let f4 = por[3] * a1 + por[4] * a4 + por[5] * a7; let f5 = por[3] * a2 + por[4] * a5 + por[5] * a8; let f6 = por[6] * a0 + por[7] * a3 + por[8] * a6; let f7 = por[6] * a1 + por[7] * a4 + por[8] * a7; let f8 = por[6] * a2 + por[7] * a5 + por[8] * a8; let m0 = sx * f0; let m1 = sx * f1; let m2 = sx * f2; let m3 = 0.0; let m4 = sy * f3; let m5 = sy * f4; let m6 = sy * f5; let m7 = 0.0; let m8 = sz * f6; let m9 = sz * f7; let m10 = sz * f8; let m11 = 0.0; let k0 = spx * f0; let k1 = spy * f3; let k2 = spz * f6; let m12 = rox + rpx + tx - rpx * f0 - rpy * f3 - rpz * f6 + sox * f0 + k0 + soy * f3 + k1 + soz * f6 + k2 - sx * k0 - sy * k1 - sz * k2; let k3 = spx * f1; let k4 = spy * f4; let k5 = spz * f7; let m13 = roy + rpy + ty - rpx * f1 - rpy * f4 - rpz * f7 + sox * f1 + k3 + soy * f4 + k4 + soz * f7 + k5 - sx * k3 - sy * k4 - sz * k5; let k6 = spx * f2; let k7 = spy * f5; let k8 = spz * f8; let m14 = roz + rpz + tz - rpx * f2 - rpy * f5 - rpz * f8 + sox * f2 + k6 + soy * f5 + k7 + soz * f8 + k8 - sx * k6 - sy * k7 - sz * k8; let m15 = 1.0; Matrix4::new( m0, m4, m8, m12, m1, m5, m9, m13, m2, m6, m10, m14, m3, m7, m11, m15, ) } /// Returns matrix which is final result of transform. Matrix then can be used to transform /// a vector, or combine with other matrix, to make transform hierarchy for example. pub fn matrix(&self) -> Matrix4<f32> { if self.dirty.get() { self.matrix.set(self.calculate_local_transform()); self.dirty.set(false) } self.matrix.get() } } /// Transform builder allows you to construct transform in declarative manner. /// This is typical implementation of Builder pattern. pub struct TransformBuilder { local_scale: Vector3<f32>, local_position: Vector3<f32>, local_rotation: UnitQuaternion<f32>, pre_rotation: UnitQuaternion<f32>, post_rotation: UnitQuaternion<f32>, rotation_offset: Vector3<f32>, rotation_pivot: Vector3<f32>, scaling_offset: Vector3<f32>, scaling_pivot: Vector3<f32>, } impl Default for TransformBuilder { fn default() -> Self { Self::new() } } impl TransformBuilder { /// Creates new transform builder. If it won't be modified then it will produce /// identity transform as result. pub fn new() -> Self { Self { local_scale: Vector3::new(1.0, 1.0, 1.0), local_position: Default::default(), local_rotation: UnitQuaternion::identity(), pre_rotation: UnitQuaternion::identity(), post_rotation: UnitQuaternion::identity(), rotation_offset: Default::default(), rotation_pivot: Default::default(), scaling_offset: Default::default(), scaling_pivot: Default::default(), } } /// Sets desired local scale. pub fn with_local_scale(mut self, scale: Vector3<f32>) -> Self { self.local_scale = scale; self } /// Sets desired local position. pub fn with_local_position(mut self, position: Vector3<f32>) -> Self { self.local_position = position; self } /// Sets desired local rotation. pub fn with_local_rotation(mut self, rotation: UnitQuaternion<f32>) -> Self { self.local_rotation = rotation; self } /// Sets desired pre-rotation. pub fn with_pre_rotation(mut self, rotation: UnitQuaternion<f32>) -> Self { self.pre_rotation = rotation; self } /// Sets desired post-rotation. pub fn with_post_rotation(mut self, rotation: UnitQuaternion<f32>) -> Self { self.post_rotation = rotation; self } /// Sets desired rotation offset. pub fn with_rotation_offset(mut self, offset: Vector3<f32>) -> Self { self.rotation_offset = offset; self } /// Sets desired rotation pivot. pub fn with_rotation_pivot(mut self, pivot: Vector3<f32>) -> Self { self.rotation_pivot = pivot; self } /// Sets desired scaling offset. pub fn with_scaling_offset(mut self, offset: Vector3<f32>) -> Self { self.scaling_offset = offset; self } /// Sets desired scaling pivot. pub fn with_scaling_pivot(mut self, pivot: Vector3<f32>) -> Self { self.scaling_pivot = pivot; self } /// Builds new Transform instance using provided values. pub fn build(self) -> Transform { Transform { dirty: Cell::new(true), local_scale: TemplateVariable::new(self.local_scale), local_position: TemplateVariable::new(self.local_position), local_rotation: TemplateVariable::new(self.local_rotation), pre_rotation: TemplateVariable::new(self.pre_rotation), post_rotation: TemplateVariable::new(self.post_rotation), rotation_offset: TemplateVariable::new(self.rotation_offset), rotation_pivot: TemplateVariable::new(self.rotation_pivot), scaling_offset: TemplateVariable::new(self.scaling_offset), scaling_pivot: TemplateVariable::new(self.scaling_pivot), matrix: Cell::new(Matrix4::identity()), post_rotation_matrix: build_post_rotation_matrix(self.post_rotation), } } }
36.049558
139
0.602956
616f7cba17538dff266bc1cd387ae1a825e763af
3,854
use std::io::Read; use lazy_static::lazy_static; use regex::{Regex, RegexBuilder}; use super::{ByteRecord, Reader}; use crate::{ datatypes::*, error::{ArrowError, Result}, }; pub fn projected_schema(schema: &Schema, projection: Option<&[usize]>) -> Schema { match &projection { Some(projection) => { let fields = schema.fields(); let projected_fields: Vec<Field> = projection.iter().map(|i| fields[*i].clone()).collect(); Schema::new_from(projected_fields, schema.metadata().clone()) } None => schema.clone(), } } /// Reads `len` rows from the CSV into Bytes, skiping `skip` /// This operation has minimal CPU work and is thus the fastest way to read through a CSV /// without deserializing the contents to arrow. pub fn read_rows<R: Read>( reader: &mut Reader<R>, skip: usize, len: usize, ) -> Result<Vec<ByteRecord>> { // skip first `start` rows. let mut row = ByteRecord::new(); for _ in 0..skip { let res = reader.read_byte_record(&mut row); if !res.unwrap_or(false) { break; } } reader .byte_records() .enumerate() .take(len) .map(|(row_number, row)| { row.map_err(|e| { ArrowError::External(format!(" at line {}", skip + row_number), Box::new(e)) }) }) .collect::<Result<Vec<_>>>() } lazy_static! { static ref DECIMAL_RE: Regex = Regex::new(r"^-?(\d+\.\d+)$").unwrap(); static ref INTEGER_RE: Regex = Regex::new(r"^-?(\d+)$").unwrap(); static ref BOOLEAN_RE: Regex = RegexBuilder::new(r"^(true)$|^(false)$") .case_insensitive(true) .build() .unwrap(); static ref DATE_RE: Regex = Regex::new(r"^\d{4}-\d\d-\d\d$").unwrap(); static ref DATETIME_RE: Regex = Regex::new(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d$").unwrap(); } /// Infer the data type of a record pub fn infer(string: &str) -> DataType { // when quoting is enabled in the reader, these quotes aren't escaped, we default to // Utf8 for them if string.starts_with('"') { return DataType::Utf8; } // match regex in a particular order if BOOLEAN_RE.is_match(string) { DataType::Boolean } else if DECIMAL_RE.is_match(string) { DataType::Float64 } else if INTEGER_RE.is_match(string) { DataType::Int64 } else if DATETIME_RE.is_match(string) { DataType::Date64 } else if DATE_RE.is_match(string) { DataType::Date32 } else { DataType::Utf8 } } #[cfg(test)] mod tests { use std::sync::Arc; use super::super::{deserialize_batch, deserialize_column, infer_schema, ReaderBuilder}; use super::*; use crate::array::{Float64Array, Utf8Array}; #[test] fn test_read() -> Result<()> { let mut reader = ReaderBuilder::new().from_path("test/data/uk_cities_with_headers.csv")?; let schema = Arc::new(infer_schema(&mut reader, None, true, &infer)?); let rows = read_rows(&mut reader, 0, 100)?; let batch = deserialize_batch(&rows, schema.fields(), None, 0, deserialize_column)?; let batch_schema = batch.schema(); assert_eq!(&schema, batch_schema); assert_eq!(37, batch.num_rows()); assert_eq!(3, batch.num_columns()); let lat = batch .column(1) .as_any() .downcast_ref::<Float64Array>() .unwrap(); assert!((57.653484 - lat.value(0)).abs() < f64::EPSILON); let city = batch .column(0) .as_any() .downcast_ref::<Utf8Array<i32>>() .unwrap(); assert_eq!("Elgin, Scotland, the UK", city.value(0)); assert_eq!("Aberdeen, Aberdeen City, UK", city.value(13)); Ok(()) } }
29.419847
97
0.574987
e9abd1b548e8dde79a1ac6cc237e0c4a8ff902b8
42,442
use super::{ CodeKind, CodeLocation, CodeLocationMessage, EffectiveRange, MissingTokenKind, SyntaxToken, Trivia, TriviaKind, }; use crate::arena::{BumpaloArena, BumpaloBox}; use crate::semantic::Scope; use crate::syntax::tree::*; use crate::syntax::Token; use std::cell::Cell; pub struct NodePath<'a> { source: Option<&'a str>, node: NodeKind<'a>, parent: BumpaloBox<'a, Cell<Option<&'a NodePath<'a>>>>, // Scopes. If the node is the root, these scopes point it even if exited. scope: BumpaloBox<'a, Cell<&'a Scope<'a>>>, main_scope: BumpaloBox<'a, Cell<&'a Scope<'a>>>, declarations: BumpaloBox<'a, Cell<&'a Scope<'a>>>, skipped: BumpaloBox<'a, Cell<bool>>, stopped: BumpaloBox<'a, Cell<bool>>, } impl<'a> NodePath<'a> { pub fn new( arena: &'a BumpaloArena, source: Option<&'a str>, node: NodeKind<'a>, parent: Option<&'a NodePath<'a>>, scope: &'a Scope<'a>, main_scope: &'a Scope<'a>, declarations: &'a Scope<'a>, ) -> Self { Self { node, source, parent: BumpaloBox::new_in(Cell::new(parent), arena), scope: BumpaloBox::new_in(Cell::new(scope), arena), main_scope: BumpaloBox::new_in(Cell::new(main_scope), arena), declarations: BumpaloBox::new_in(Cell::new(declarations), arena), skipped: BumpaloBox::new_in(Cell::new(false), arena), stopped: BumpaloBox::new_in(Cell::new(false), arena), } } pub fn root_path(arena: &'a BumpaloArena, node: &'a Program<'a>) -> Self { Self::new( arena, node.source(), NodeKind::Program(node), None, node.main_scope(), node.main_scope(), node.declarations_scope(), ) } pub fn child_path( arena: &'a BumpaloArena, node: NodeKind<'a>, parent: &'a NodePath<'a>, ) -> Self { Self::new( arena, parent.source(), node, Some(parent), parent.scope.get(), parent.main_scope.get(), parent.declarations.get(), ) } pub fn source(&self) -> Option<&'a str> { self.source } pub fn node(&self) -> NodeKind<'a> { self.node } pub fn location(&self) -> CodeLocation<'a> { self.location_with(self.node.range()) } pub fn location_with(&self, range: EffectiveRange) -> CodeLocation<'a> { CodeLocation::new(self.source(), range) } pub fn location_message( &self, range: EffectiveRange, message: &str, ) -> CodeLocationMessage<'a> { CodeLocationMessage::new(self.location_with(range), message.to_string()) } /// Returns `true` if `skip()` or `stop()` invoked. fn skipped(&self) -> bool { self.skipped.get() || self.stopped.get() } /// Returns `true` if `stop()` invoked. fn stopped(&self) -> bool { self.stopped.get() } /// skips traversing the children and `exit` of the current path. pub fn skip(&self) { self.skipped.replace(true); } /// stops traversing entirely. pub fn stop(&self) { self.stopped.replace(true); } pub fn parent(&self) -> Option<&'a NodePath<'a>> { self.parent.get() } pub fn expect_parent(&self) -> &'a NodePath<'a> { self.parent() .unwrap_or_else(|| panic!("parent must exist.")) } pub fn scope(&self) -> &'a Scope<'a> { self.scope.get() } fn on_enter(&self) { match self.node { NodeKind::Block(block) => { self.scope.replace(block.scope()); } NodeKind::CaseArm(arm) => { self.scope.replace(arm.scope()); } NodeKind::StructDeclaration(_) => { self.scope.replace(self.declarations.get()); } NodeKind::FunctionDeclaration(_) => { self.scope.replace(self.declarations.get()); } _ => {} } } fn on_exit(&self) { match self.node { // Before binding completed, parent scope is `None`. NodeKind::Block(block) => { if let Some(scope) = block.scope().parent() { self.scope.replace(scope); } } NodeKind::CaseArm(arm) => { if let Some(scope) = arm.scope().parent() { self.scope.replace(scope); } } NodeKind::StructDeclaration(_) => { self.scope.replace(self.main_scope.get()); } NodeKind::FunctionDeclaration(_) => { self.scope.replace(self.main_scope.get()); } _ => {} } } } #[allow(unused_variables, unused_mut)] pub trait Visitor<'a> { // Token fn enter_whitespace(&mut self, path: &'a NodePath<'a>, token: &Token, trivia: &Trivia) {} fn exit_whitespace(&mut self, path: &'a NodePath<'a>, token: &Token, trivia: &Trivia) {} fn enter_line_comment( &mut self, path: &'a NodePath<'a>, token: &Token, trivia: &Trivia, comment: &str, ) { } fn exit_line_comment( &mut self, path: &'a NodePath<'a>, token: &Token, trivia: &Trivia, comment: &str, ) { } fn enter_interpreted_token(&mut self, path: &'a NodePath<'a>, token: &Token) {} fn exit_interpreted_token(&mut self, path: &'a NodePath<'a>, token: &Token) {} fn enter_missing_token( &mut self, path: &'a NodePath<'a>, range: EffectiveRange, item: MissingTokenKind, ) { } fn exit_missing_token( &mut self, path: &'a NodePath<'a>, range: EffectiveRange, item: MissingTokenKind, ) { } fn enter_skipped_token( &mut self, path: &'a NodePath<'a>, token: &Token, expected: MissingTokenKind, ) { } fn exit_skipped_token( &mut self, path: &'a NodePath<'a>, token: &Token, expected: MissingTokenKind, ) { } // Node fn enter_node(&mut self, path: &'a NodePath<'a>, node: NodeKind<'a>) {} fn exit_node(&mut self, path: &'a NodePath<'a>, node: NodeKind<'a>) {} fn enter_program(&mut self, path: &'a NodePath<'a>, program: &'a Program<'a>) {} fn exit_program(&mut self, path: &'a NodePath<'a>, program: &'a Program<'a>) {} fn enter_top_level(&mut self, path: &'a NodePath<'a>, top_level: &'a TopLevel<'a>) {} fn exit_top_level(&mut self, path: &'a NodePath<'a>, top_level: &'a TopLevel<'a>) {} fn enter_block(&mut self, path: &'a NodePath<'a>, block: &'a Block<'a>) {} fn exit_block(&mut self, path: &'a NodePath<'a>, block: &'a Block<'a>) {} fn enter_identifier(&mut self, path: &'a NodePath<'a>, id: &'a Identifier<'a>) {} fn exit_identifier(&mut self, path: &'a NodePath<'a>, id: &'a Identifier<'a>) {} fn enter_struct_definition( &mut self, path: &'a NodePath<'a>, definition: &'a StructDeclaration<'a>, ) { } fn exit_struct_definition( &mut self, path: &'a NodePath<'a>, definition: &'a StructDeclaration<'a>, ) { } fn enter_function_definition( &mut self, path: &'a NodePath<'a>, definition: &'a FunctionDeclaration<'a>, ) { } fn exit_function_definition( &mut self, path: &'a NodePath<'a>, definition: &'a FunctionDeclaration<'a>, ) { } fn enter_function_parameter( &mut self, path: &'a NodePath<'a>, function: &'a FunctionDeclaration<'a>, param: &'a FunctionParameter<'a>, ) { } fn exit_function_parameter( &mut self, path: &'a NodePath<'a>, function: &'a FunctionDeclaration<'a>, param: &'a FunctionParameter<'a>, ) { } fn enter_type_field( &mut self, path: &'a NodePath<'a>, struct_def: &'a StructDeclaration<'a>, field: &'a TypeField<'a>, ) { } fn exit_type_field( &mut self, path: &'a NodePath<'a>, struct_def: &'a StructDeclaration<'a>, field: &'a TypeField<'a>, ) { } fn enter_type_annotation( &mut self, path: &'a NodePath<'a>, annotation: &'a TypeAnnotation<'a>, ) { } fn exit_type_annotation(&mut self, path: &'a NodePath<'a>, annotation: &'a TypeAnnotation<'a>) { } fn enter_statement(&mut self, path: &'a NodePath<'a>, statement: &'a Statement<'a>) {} fn exit_statement(&mut self, path: &'a NodePath<'a>, statement: &'a Statement<'a>) {} fn enter_expression_statement( &mut self, path: &'a NodePath<'a>, statement: &'a ExpressionStatement<'a>, ) { } fn exit_expression_statement( &mut self, path: &'a NodePath<'a>, statement: &'a ExpressionStatement<'a>, ) { } fn enter_empty_statement(&mut self, path: &'a NodePath<'a>, statement: &'a EmptyStatement<'a>) { } fn exit_empty_statement(&mut self, path: &'a NodePath<'a>, statement: &'a EmptyStatement<'a>) {} fn enter_variable_declaration( &mut self, path: &'a NodePath<'a>, declaration: &'a VariableDeclaration<'a>, ) { } fn exit_variable_declaration( &mut self, path: &'a NodePath<'a>, declaration: &'a VariableDeclaration<'a>, ) { } fn enter_case_arm(&mut self, path: &'a NodePath<'a>, arm: &'a CaseArm<'a>) {} fn exit_case_arm(&mut self, path: &'a NodePath<'a>, arm: &'a CaseArm<'a>) {} fn enter_value_field( &mut self, path: &'a NodePath<'a>, struct_literal: &'a StructLiteral<'a>, field: &'a ValueField<'a>, ) { } fn exit_value_field( &mut self, path: &'a NodePath<'a>, struct_literal: &'a StructLiteral<'a>, field: &'a ValueField<'a>, ) { } fn enter_grouped_expression( &mut self, path: &'a NodePath<'a>, expression: &'a GroupedExpression<'a>, ) { } fn exit_grouped_expression( &mut self, path: &'a NodePath<'a>, expression: &'a GroupedExpression<'a>, ) { } fn enter_expression(&mut self, path: &'a NodePath<'a>, expression: &'a Expression<'a>) {} fn exit_expression(&mut self, path: &'a NodePath<'a>, expression: &'a Expression<'a>) {} fn enter_integer_literal(&mut self, path: &'a NodePath<'a>, literal: &'a IntegerLiteral<'a>) {} fn exit_integer_literal(&mut self, path: &'a NodePath<'a>, literal: &'a IntegerLiteral<'a>) {} fn enter_boolean_literal(&mut self, path: &'a NodePath<'a>, literal: &'a BooleanLiteral<'a>) {} fn exit_boolean_literal(&mut self, path: &'a NodePath<'a>, literal: &'a BooleanLiteral<'a>) {} fn enter_string_literal(&mut self, path: &'a NodePath<'a>, literal: &'a StringLiteral<'a>) {} fn exit_string_literal(&mut self, path: &'a NodePath<'a>, literal: &'a StringLiteral<'a>) {} fn enter_struct_literal(&mut self, path: &'a NodePath<'a>, expr: &'a StructLiteral<'a>) {} fn exit_struct_literal(&mut self, path: &'a NodePath<'a>, expr: &'a StructLiteral<'a>) {} fn enter_variable_expression( &mut self, path: &'a NodePath<'a>, expr: &'a VariableExpression<'a>, ) { } fn exit_variable_expression( &mut self, path: &'a NodePath<'a>, expr: &'a VariableExpression<'a>, ) { } fn enter_binary_expression(&mut self, path: &'a NodePath<'a>, expr: &'a BinaryExpression<'a>) {} fn exit_binary_expression(&mut self, path: &'a NodePath<'a>, expr: &'a BinaryExpression<'a>) {} fn enter_unary_expression( &mut self, path: &'a NodePath<'a>, unary_expr: &'a UnaryExpression<'a>, ) { } fn exit_unary_expression( &mut self, path: &'a NodePath<'a>, unary_expr: &'a UnaryExpression<'a>, ) { } fn enter_subscript_expression( &mut self, path: &'a NodePath<'a>, subscript_expr: &'a SubscriptExpression<'a>, ) { } fn exit_subscript_expression( &mut self, path: &'a NodePath<'a>, subscript_expr: &'a SubscriptExpression<'a>, ) { } fn enter_call_expression(&mut self, path: &'a NodePath<'a>, call_expr: &'a CallExpression<'a>) { } fn exit_call_expression(&mut self, path: &'a NodePath<'a>, call_expr: &'a CallExpression<'a>) {} fn enter_member_expression( &mut self, path: &'a NodePath<'a>, member_expr: &'a MemberExpression<'a>, ) { } fn exit_member_expression( &mut self, path: &'a NodePath<'a>, member_expr: &'a MemberExpression<'a>, ) { } fn enter_array_expression( &mut self, path: &'a NodePath<'a>, array_expr: &'a ArrayExpression<'a>, ) { } fn exit_array_expression( &mut self, path: &'a NodePath<'a>, array_expr: &'a ArrayExpression<'a>, ) { } fn enter_if_expression(&mut self, path: &'a NodePath<'a>, if_expr: &'a IfExpression<'a>) {} fn exit_if_expression(&mut self, path: &'a NodePath<'a>, if_expr: &'a IfExpression<'a>) {} fn enter_case_expression(&mut self, path: &'a NodePath<'a>, case_expr: &'a CaseExpression<'a>) { } fn exit_case_expression(&mut self, path: &'a NodePath<'a>, case_expr: &'a CaseExpression<'a>) {} fn enter_pattern(&mut self, path: &'a NodePath<'a>, pattern: &'a Pattern<'a>) {} fn exit_pattern(&mut self, path: &'a NodePath<'a>, pattern: &'a Pattern<'a>) {} fn enter_integer_pattern(&mut self, path: &'a NodePath<'a>, pattern: &'a IntegerPattern<'a>) {} fn exit_integer_pattern(&mut self, path: &'a NodePath<'a>, pattern: &'a IntegerPattern<'a>) {} fn enter_variable_pattern(&mut self, path: &'a NodePath<'a>, pattern: &'a VariablePattern<'a>) { } fn exit_variable_pattern(&mut self, path: &'a NodePath<'a>, pattern: &'a VariablePattern<'a>) {} fn enter_array_pattern(&mut self, path: &'a NodePath<'a>, pattern: &'a ArrayPattern<'a>) {} fn exit_array_pattern(&mut self, path: &'a NodePath<'a>, pattern: &'a ArrayPattern<'a>) {} fn enter_rest_pattern(&mut self, path: &'a NodePath<'a>, pattern: &'a RestPattern<'a>) {} fn exit_rest_pattern(&mut self, path: &'a NodePath<'a>, pattern: &'a RestPattern<'a>) {} fn enter_struct_pattern(&mut self, path: &'a NodePath<'a>, pattern: &'a StructPattern<'a>) {} fn exit_struct_pattern(&mut self, path: &'a NodePath<'a>, pattern: &'a StructPattern<'a>) {} fn enter_value_field_pattern( &mut self, path: &'a NodePath<'a>, pattern: &'a ValueFieldPattern<'a>, ) { } fn exit_value_field_pattern( &mut self, path: &'a NodePath<'a>, pattern: &'a ValueFieldPattern<'a>, ) { } } pub fn traverse<'a>( arena: &'a BumpaloArena, visitor: &mut dyn Visitor<'a>, program: &'a Program<'a>, ) { let path = arena.alloc(NodePath::root_path(arena, program)); traverse_path(arena, visitor, path); } fn traverse_path<'a>( arena: &'a BumpaloArena, visitor: &mut dyn Visitor<'a>, path: &'a NodePath<'a>, ) { let node = path.node(); path.on_enter(); if !path.skipped() { dispatch_enter(visitor, path); } if !path.skipped() { // Remove *wrapper* node from the parent-child relationship. if node.is_top_level() || node.is_statement() || node.is_expression() || node.is_pattern() { let parent_path = path.expect_parent(); traverse_children(arena, visitor, parent_path, path.node()); // Propagates `stop` if the path wasn't already stopped. if !path.stopped() && parent_path.stopped() { path.stopped.replace(true); } } else { traverse_children(arena, visitor, path, path.node()); } } if !path.skipped() { dispatch_exit(visitor, path); } path.on_exit(); } fn traverse_children<'a>( arena: &'a BumpaloArena, visitor: &mut dyn Visitor<'a>, path: &'a NodePath<'a>, node: NodeKind<'a>, ) { for kind in node.code() { if path.skipped() { break; } match kind { CodeKind::Node(node) => { let child_path = arena.alloc(NodePath::child_path(arena, *node, path)); traverse_path(arena, visitor, child_path); // Propagates `stop` if the path wasn't already stopped. if !path.stopped() && child_path.stopped() { path.stopped.replace(true); } } CodeKind::SyntaxToken(token) => match token { SyntaxToken::Interpreted(token) => traverse_interpreted_token(visitor, path, token), SyntaxToken::Missing { range, item } => { traverse_missing_token(visitor, path, *range, *item) } SyntaxToken::Skipped { token, expected } => { traverse_skipped_token(visitor, path, token, *expected) } }, } } } fn dispatch_enter<'a>(visitor: &mut dyn Visitor<'a>, path: &'a NodePath<'a>) { let node = path.node(); visitor.enter_node(path, node); match node { NodeKind::Program(kind) => { visitor.enter_program(path, kind); } NodeKind::TopLevel(kind) => { visitor.enter_top_level(path, kind); } NodeKind::Block(kind) => { visitor.enter_block(path, kind); } NodeKind::Identifier(kind) => { visitor.enter_identifier(path, kind); } NodeKind::StructDeclaration(kind) => { visitor.enter_struct_definition(path, kind); } NodeKind::FunctionDeclaration(kind) => { visitor.enter_function_definition(path, kind); } NodeKind::TypeField(kind) => { let parent = path.expect_parent(); let struct_def = parent.node().struct_definition().unwrap(); visitor.enter_type_field(path, struct_def, kind); } NodeKind::TypeAnnotation(kind) => { visitor.enter_type_annotation(path, kind); } NodeKind::FunctionParameter(kind) => { let parent_path = path.expect_parent(); let fun = parent_path.node().function_definition().unwrap(); visitor.enter_function_parameter(path, fun, kind); } NodeKind::Statement(kind) => { visitor.enter_statement(path, kind); } NodeKind::ExpressionStatement(kind) => { visitor.enter_expression_statement(path, kind); } NodeKind::EmptyStatement(kind) => { visitor.enter_empty_statement(path, kind); } NodeKind::VariableDeclaration(kind) => { visitor.enter_variable_declaration(path, kind); } NodeKind::ValueField(kind) => { let parent = path.expect_parent(); let literal = parent.node().struct_literal().unwrap(); visitor.enter_value_field(path, literal, kind); } // Expression NodeKind::IntegerLiteral(value) => { visitor.enter_integer_literal(path, value); } NodeKind::BooleanLiteral(value) => { visitor.enter_boolean_literal(path, value); } NodeKind::StringLiteral(value) => { visitor.enter_string_literal(path, value); } NodeKind::VariableExpression(kind) => { visitor.enter_variable_expression(path, kind); } NodeKind::BinaryExpression(kind) => { visitor.enter_binary_expression(path, kind); } NodeKind::UnaryExpression(kind) => { visitor.enter_unary_expression(path, kind); } NodeKind::SubscriptExpression(kind) => { visitor.enter_subscript_expression(path, kind); } NodeKind::CallExpression(kind) => { visitor.enter_call_expression(path, kind); } NodeKind::MemberExpression(kind) => { visitor.enter_member_expression(path, kind); } NodeKind::ArrayExpression(kind) => { visitor.enter_array_expression(path, kind); } NodeKind::StructLiteral(kind) => { visitor.enter_struct_literal(path, kind); } NodeKind::IfExpression(kind) => { visitor.enter_if_expression(path, kind); } NodeKind::CaseExpression(kind) => { visitor.enter_case_expression(path, kind); } NodeKind::CaseArm(kind) => { visitor.enter_case_arm(path, kind); } NodeKind::GroupedExpression(kind) => { visitor.enter_grouped_expression(path, kind); } NodeKind::Expression(expr) => { visitor.enter_expression(path, expr); } // Pattern NodeKind::Pattern(kind) => { visitor.enter_pattern(path, kind); } NodeKind::IntegerPattern(kind) => { visitor.enter_integer_pattern(path, kind); } NodeKind::VariablePattern(kind) => { visitor.enter_variable_pattern(path, kind); } NodeKind::ArrayPattern(pattern) => { visitor.enter_array_pattern(path, pattern); } NodeKind::RestPattern(pattern) => { visitor.enter_rest_pattern(path, pattern); } NodeKind::StructPattern(pattern) => { visitor.enter_struct_pattern(path, pattern); } NodeKind::ValueFieldPattern(kind) => { visitor.enter_value_field_pattern(path, kind); // Since omitted value pattern doesn't appear in AST, // we have to visit pseudo value node manually. if let Some(value_pattern) = kind.omitted_value() { visitor.enter_pattern(path, value_pattern); if let PatternKind::VariablePattern(variable_pattern) = value_pattern.kind() { visitor.enter_variable_pattern(path, variable_pattern); } } } } } fn dispatch_exit<'a>(visitor: &mut dyn Visitor<'a>, path: &'a NodePath<'a>) { let node = path.node(); visitor.exit_node(path, node); match node { NodeKind::Program(kind) => { visitor.exit_program(path, kind); } NodeKind::TopLevel(kind) => { visitor.exit_top_level(path, kind); } NodeKind::Block(kind) => { visitor.exit_block(path, kind); } NodeKind::Identifier(kind) => { visitor.exit_identifier(path, kind); } NodeKind::StructDeclaration(kind) => { visitor.exit_struct_definition(path, kind); } NodeKind::FunctionDeclaration(kind) => { visitor.exit_function_definition(path, kind); } NodeKind::TypeField(kind) => { let parent = path.expect_parent(); let struct_def = parent.node().struct_definition().unwrap(); visitor.exit_type_field(path, struct_def, kind); } NodeKind::TypeAnnotation(kind) => { visitor.exit_type_annotation(path, kind); } NodeKind::FunctionParameter(kind) => { let parent_path = path.expect_parent(); let fun = parent_path.node().function_definition().unwrap(); visitor.exit_function_parameter(path, fun, kind); } NodeKind::Statement(kind) => { visitor.exit_statement(path, kind); } NodeKind::ExpressionStatement(kind) => { visitor.exit_expression_statement(path, kind); } NodeKind::EmptyStatement(kind) => { visitor.exit_empty_statement(path, kind); } NodeKind::VariableDeclaration(kind) => { visitor.exit_variable_declaration(path, kind); } NodeKind::ValueField(kind) => { let parent = path.expect_parent(); let literal = parent.node().struct_literal().unwrap(); visitor.exit_value_field(path, literal, kind); } // Expression NodeKind::IntegerLiteral(value) => { visitor.exit_integer_literal(path, value); } NodeKind::BooleanLiteral(value) => { visitor.exit_boolean_literal(path, value); } NodeKind::StringLiteral(value) => { visitor.exit_string_literal(path, value); } NodeKind::VariableExpression(kind) => { visitor.exit_variable_expression(path, kind); } NodeKind::BinaryExpression(kind) => { visitor.exit_binary_expression(path, kind); } NodeKind::UnaryExpression(kind) => { visitor.exit_unary_expression(path, kind); } NodeKind::SubscriptExpression(kind) => { visitor.exit_subscript_expression(path, kind); } NodeKind::MemberExpression(kind) => { visitor.exit_member_expression(path, kind); } NodeKind::CallExpression(kind) => { visitor.exit_call_expression(path, kind); } NodeKind::ArrayExpression(kind) => { visitor.exit_array_expression(path, kind); } NodeKind::StructLiteral(kind) => { visitor.exit_struct_literal(path, kind); } NodeKind::IfExpression(kind) => { visitor.exit_if_expression(path, kind); } NodeKind::CaseExpression(kind) => { visitor.exit_case_expression(path, kind); } NodeKind::CaseArm(kind) => { visitor.exit_case_arm(path, kind); } NodeKind::GroupedExpression(kind) => { visitor.exit_grouped_expression(path, kind); } NodeKind::Expression(expr) => { visitor.exit_expression(path, expr); } // Pattern NodeKind::Pattern(pattern) => { visitor.exit_pattern(path, pattern); } NodeKind::IntegerPattern(pattern) => { visitor.exit_integer_pattern(path, pattern); } NodeKind::VariablePattern(pattern) => { visitor.exit_variable_pattern(path, pattern); } NodeKind::ArrayPattern(pattern) => { visitor.exit_array_pattern(path, pattern); } NodeKind::RestPattern(pattern) => { visitor.exit_rest_pattern(path, pattern); } NodeKind::StructPattern(pattern) => { visitor.exit_struct_pattern(path, pattern); } NodeKind::ValueFieldPattern(kind) => { if let Some(value_pattern) = kind.omitted_value() { if let PatternKind::VariablePattern(variable_pattern) = value_pattern.kind() { visitor.exit_variable_pattern(path, variable_pattern); } visitor.exit_pattern(path, value_pattern); } visitor.exit_value_field_pattern(path, kind); } } } fn traverse_token_trivia<'a>(visitor: &mut dyn Visitor<'a>, path: &'a NodePath<'a>, token: &Token) { for trivia in &token.leading_trivia { if path.skipped() { break; } match &trivia.kind { TriviaKind::LineComment(comment) => { if !path.skipped() { visitor.enter_line_comment(path, token, trivia, comment); } if !path.skipped() { visitor.exit_line_comment(path, token, trivia, comment); } } TriviaKind::Whitespace => { if !path.skipped() { visitor.enter_whitespace(path, token, trivia); } if !path.skipped() { visitor.exit_whitespace(path, token, trivia); } } } } } fn traverse_interpreted_token<'a>( visitor: &mut dyn Visitor<'a>, path: &'a NodePath<'a>, token: &Token, ) { if !path.skipped() { traverse_token_trivia(visitor, path, token); } if !path.skipped() { visitor.enter_interpreted_token(path, token); } if !path.skipped() { visitor.exit_interpreted_token(path, token); } } fn traverse_missing_token<'a>( visitor: &mut dyn Visitor<'a>, path: &'a NodePath<'a>, range: EffectiveRange, item: MissingTokenKind, ) { if !path.skipped() { visitor.enter_missing_token(path, range, item); } if !path.skipped() { visitor.exit_missing_token(path, range, item); } } fn traverse_skipped_token<'a>( visitor: &mut dyn Visitor<'a>, path: &'a NodePath<'a>, token: &Token, expected: MissingTokenKind, ) { if !path.skipped() { traverse_token_trivia(visitor, path, token); } if !path.skipped() { visitor.enter_skipped_token(path, token, expected); } if !path.skipped() { visitor.exit_skipped_token(path, token, expected); } } #[cfg(test)] mod tests { use super::*; use crate::arena::BumpaloArena; use crate::syntax::Parser; // count expressions #[derive(Debug, Default)] struct ExpressionCounter { number_of_expressions: i32, } impl<'a> Visitor<'a> for ExpressionCounter { fn enter_expression(&mut self, _path: &'a NodePath<'a>, _expr: &'a Expression<'a>) { self.number_of_expressions += 1; } } #[test] fn number_integer() { let mut visitor = ExpressionCounter::default(); let arena = BumpaloArena::new(); let program = Parser::parse_string(&arena, "42 + 55"); traverse(&arena, &mut visitor, &program); assert_eq!(visitor.number_of_expressions, 3); } // stop() #[derive(Debug, Default)] struct StopInExpression { stop_at: i32, enter_program: i32, exit_program: i32, enter_statement: i32, exit_statement: i32, enter_expression: i32, exit_expression: i32, } impl<'a> Visitor<'a> for StopInExpression { fn enter_program(&mut self, _path: &'a NodePath<'a>, _program: &'a Program<'a>) { self.enter_program += 1; } fn exit_program(&mut self, _path: &'a NodePath<'a>, _program: &'a Program<'a>) { self.exit_program += 1; } fn enter_statement(&mut self, _path: &'a NodePath<'a>, _statement: &'a Statement<'a>) { self.enter_statement += 1; } fn exit_statement(&mut self, _path: &'a NodePath<'a>, _statement: &'a Statement<'a>) { self.exit_statement += 1; } fn enter_expression(&mut self, path: &'a NodePath<'a>, _expression: &'a Expression<'a>) { if self.enter_expression == self.stop_at { path.stop(); } self.enter_expression += 1; } fn exit_expression(&mut self, _path: &'a NodePath<'a>, _expression: &'a Expression<'a>) { self.exit_expression += 1; } } #[test] fn never_stop_traversal() { let mut visitor = StopInExpression::default(); visitor.stop_at = -1; // never stop let arena = BumpaloArena::new(); let program = Parser::parse_string(&arena, "42 + 55"); traverse(&arena, &mut visitor, &program); assert_eq!(visitor.enter_program, 1); assert_eq!(visitor.enter_statement, 1); assert_eq!(visitor.enter_expression, 3); assert_eq!(visitor.exit_program, 1); assert_eq!(visitor.exit_statement, 1); assert_eq!(visitor.exit_expression, 3); } #[test] fn stop_at_2nd_expression() { let mut visitor = StopInExpression::default(); visitor.stop_at = 1; // Stop at 2nd expression let arena = BumpaloArena::new(); let program = Parser::parse_string(&arena, "42 + 55"); traverse(&arena, &mut visitor, &program); assert_eq!(visitor.enter_program, 1); assert_eq!(visitor.enter_statement, 1); assert_eq!(visitor.enter_expression, 2); assert_eq!(visitor.exit_program, 0); assert_eq!(visitor.exit_statement, 0); assert_eq!(visitor.exit_expression, 0); } #[test] fn stop_at_last_expression() { let mut visitor = StopInExpression::default(); visitor.stop_at = 2; // Stop at 2nd expression let arena = BumpaloArena::new(); let program = Parser::parse_string(&arena, "42 + 55"); traverse(&arena, &mut visitor, &program); assert_eq!(visitor.enter_program, 1); assert_eq!(visitor.enter_statement, 1); assert_eq!(visitor.enter_expression, 3); assert_eq!(visitor.exit_program, 0); assert_eq!(visitor.exit_statement, 0); assert_eq!(visitor.exit_expression, 1); } // record AST #[derive(Debug, Default)] struct ASTWalker { node_names: Vec<&'static str>, parent_names: Vec<&'static str>, } impl<'a> ASTWalker { fn enter_path(&mut self, path: &'a NodePath<'a>) { self.node_names.push(path.node().node_type_name()); self.parent_names.push( path.parent() .map(|p| p.node().node_type_name()) .unwrap_or(""), ); } } impl<'a> Visitor<'a> for ASTWalker { fn enter_program(&mut self, path: &'a NodePath<'a>, _program: &'a Program<'a>) { self.enter_path(path); } fn enter_top_level(&mut self, path: &'a NodePath<'a>, _node: &'a TopLevel<'a>) { self.enter_path(path); } fn enter_block(&mut self, path: &'a NodePath<'a>, _block: &'a Block<'a>) { self.enter_path(path); } fn enter_identifier(&mut self, path: &'a NodePath<'a>, _id: &'a Identifier<'a>) { self.enter_path(path); } fn enter_struct_definition( &mut self, path: &'a NodePath<'a>, _definition: &'a StructDeclaration<'a>, ) { self.enter_path(path); } fn exit_struct_definition( &mut self, path: &'a NodePath<'a>, _definition: &'a StructDeclaration<'a>, ) { self.enter_path(path); } fn enter_function_definition( &mut self, path: &'a NodePath<'a>, _definition: &'a FunctionDeclaration<'a>, ) { self.enter_path(path); } fn enter_function_parameter( &mut self, path: &'a NodePath<'a>, _function: &'a FunctionDeclaration<'a>, _param: &'a FunctionParameter<'a>, ) { self.enter_path(path); } fn enter_type_field( &mut self, path: &'a NodePath<'a>, _struct_def: &'a StructDeclaration<'a>, _field: &'a TypeField<'a>, ) { self.enter_path(path); } fn enter_type_annotation( &mut self, path: &'a NodePath<'a>, _annotation: &'a TypeAnnotation<'a>, ) { self.enter_path(path); } fn enter_statement(&mut self, path: &'a NodePath<'a>, _statement: &'a Statement<'a>) { self.enter_path(path); } fn enter_expression_statement( &mut self, path: &'a NodePath<'a>, _statement: &'a ExpressionStatement<'a>, ) { self.enter_path(path); } fn enter_empty_statement( &mut self, path: &'a NodePath<'a>, _statement: &'a EmptyStatement<'a>, ) { self.enter_path(path); } fn enter_variable_declaration( &mut self, path: &'a NodePath<'a>, _declaration: &'a VariableDeclaration<'a>, ) { self.enter_path(path); } fn enter_case_arm(&mut self, path: &'a NodePath<'a>, _arm: &'a CaseArm<'a>) { self.enter_path(path); } fn enter_value_field( &mut self, path: &'a NodePath<'a>, _struct_literal: &'a StructLiteral<'a>, _field: &'a ValueField<'a>, ) { self.enter_path(path); } fn enter_grouped_expression( &mut self, path: &'a NodePath<'a>, _expression: &'a GroupedExpression<'a>, ) { self.enter_path(path); } fn enter_expression(&mut self, path: &'a NodePath<'a>, _expression: &'a Expression<'a>) { self.enter_path(path); } fn enter_integer_literal( &mut self, path: &'a NodePath<'a>, _literal: &'a IntegerLiteral<'a>, ) { self.enter_path(path); } fn enter_string_literal( &mut self, path: &'a NodePath<'a>, _literal: &'a StringLiteral<'a>, ) { self.enter_path(path); } fn enter_struct_literal(&mut self, path: &'a NodePath<'a>, _expr: &'a StructLiteral<'a>) { self.enter_path(path); } fn enter_variable_expression( &mut self, path: &'a NodePath<'a>, _expr: &'a VariableExpression<'a>, ) { self.enter_path(path); } fn enter_binary_expression( &mut self, path: &'a NodePath<'a>, _expr: &'a BinaryExpression<'a>, ) { self.enter_path(path); } fn enter_unary_expression( &mut self, path: &'a NodePath<'a>, _unary_expr: &'a UnaryExpression<'a>, ) { self.enter_path(path); } fn enter_subscript_expression( &mut self, path: &'a NodePath<'a>, _subscript_expr: &'a SubscriptExpression<'a>, ) { self.enter_path(path); } fn enter_call_expression( &mut self, path: &'a NodePath<'a>, _call_expr: &'a CallExpression<'a>, ) { self.enter_path(path); } fn enter_member_expression( &mut self, path: &'a NodePath<'a>, _member_expr: &'a MemberExpression<'a>, ) { self.enter_path(path); } fn enter_array_expression( &mut self, path: &'a NodePath<'a>, _array_expr: &'a ArrayExpression<'a>, ) { self.enter_path(path); } fn enter_if_expression(&mut self, path: &'a NodePath<'a>, _if_expr: &'a IfExpression<'a>) { self.enter_path(path); } fn enter_case_expression( &mut self, path: &'a NodePath<'a>, _case_expr: &'a CaseExpression<'a>, ) { self.enter_path(path); } fn enter_pattern(&mut self, path: &'a NodePath<'a>, _pattern: &'a Pattern<'a>) { self.enter_path(path); } fn enter_variable_pattern( &mut self, path: &'a NodePath<'a>, _pattern: &'a VariablePattern<'a>, ) { self.enter_path(path); } fn enter_array_pattern(&mut self, path: &'a NodePath<'a>, _pattern: &'a ArrayPattern<'a>) { self.enter_path(path); } fn enter_rest_pattern(&mut self, path: &'a NodePath<'a>, _pattern: &'a RestPattern<'a>) { self.enter_path(path); } fn enter_struct_pattern( &mut self, path: &'a NodePath<'a>, _pattern: &'a StructPattern<'a>, ) { self.enter_path(path); } fn enter_value_field_pattern( &mut self, path: &'a NodePath<'a>, _pattern: &'a ValueFieldPattern<'a>, ) { self.enter_path(path); } } // Structural testing for an expression statement #[test] fn parent_child_expression_statement() { let mut visitor = ASTWalker::default(); let arena = BumpaloArena::new(); let program = Parser::parse_string(&arena, "1"); traverse(&arena, &mut visitor, &program); assert_eq!( visitor.node_names, vec![ "Program", "TopLevel", "Statement", "ExpressionStatement", "Expression", "IntegerLiteral" ] ); // Statement (wrapper node) should be skipped. assert_eq!( visitor.parent_names, vec![ "", "Program", "Program", "Program", "ExpressionStatement", "ExpressionStatement", ] ); } #[test] fn parent_child_pattern() { let mut visitor = ASTWalker::default(); let arena = BumpaloArena::new(); let program = Parser::parse_string(&arena, "let x = 1"); traverse(&arena, &mut visitor, &program); assert_eq!( visitor.node_names, vec![ "Program", "TopLevel", "Statement", "VariableDeclaration", "Pattern", "VariablePattern", "Identifier", "Expression", "IntegerLiteral" ] ); // Statement (wrapper node) should be skipped. assert_eq!( visitor.parent_names, vec![ "", "Program", "Program", "Program", "VariableDeclaration", "VariableDeclaration", "VariablePattern", "VariableDeclaration", "VariableDeclaration", ] ); } }
30.599856
100
0.540385
5b034f2f5b412916794aa053e349ee49637afca2
3,628
use futures::future; use futures::future::Future; use futures::Stream; use hyper; use hyper::{Body, Method, StatusCode}; use hyper::server::{Http, Request, Response, Service}; use regex::Regex; use std::net::{IpAddr, SocketAddr}; use std::sync::Arc; use storage::Engine; pub struct ApiService { engine: Arc<Engine + Send + Sync>, bind_address: String, bind_port: u16, } impl ApiService { pub fn new(engine: Arc<Engine + Send + Sync>, bind_address: String, bind_port: u16) -> ApiService { ApiService { engine, bind_address, bind_port, } } pub fn start(&self) -> () { let address: IpAddr = self.bind_address.parse().unwrap(); let socket: SocketAddr = SocketAddr::new(address, self.bind_port); let handler = ServiceHandler { engine: self.engine.to_owned() }; let server = Http::new() .bind( &socket, move || Ok(handler.clone()), ) .unwrap(); server.run().unwrap(); } } #[derive(Clone)] struct ServiceHandler { engine: Arc<Engine> } impl Service for ServiceHandler { type Request = Request; type Response = Response; type Error = hyper::Error; type Future = Box<Future<Item=Self::Response, Error=Self::Error>>; fn call(&self, req: Self::Request) -> Self::Future { let method = req.method().clone(); let key = Self::get_key_from_path(req.path()); let response: Self::Future = match (method, key) { (Method::Get, Some(key)) => self.get(key), (Method::Put, Some(key)) => self.put(key, req.body()), (Method::Post, Some(key)) => self.put(key, req.body()), (Method::Delete, Some(key)) => self.delete(key), _ => self.default() }; response } } impl ServiceHandler { fn get_key_from_path(path: &str) -> Option<String> { lazy_static! { static ref URI_REGEX: Regex = Regex::new("^/(?P<key>[^/]+)").unwrap(); } URI_REGEX.captures(path) .map(|captures| captures["key"].to_string()) .and_then(|key| if key.is_empty() { None } else { Some(key) }) } fn get(&self, key: String) -> Box<Future<Item=Response, Error=hyper::Error>> { let mut response = Response::new(); match self.engine.get(key) { Some(result) => response.set_body(result), None => response.set_status(StatusCode::NotFound), }; Box::new(future::ok(response)) } fn put(&self, key: String, body: Body) -> Box<Future<Item=Response, Error=hyper::Error>> { let engine = self.engine.to_owned(); let future = body .concat2() .map(move |chunk| { let data = chunk.iter() .cloned() .collect::<Vec<u8>>(); if engine.put(key, data) { Response::new() } else { Response::new().with_status(StatusCode::InternalServerError) } }); Box::new(future) } fn delete(&self, key: String) -> Box<Future<Item=Response, Error=hyper::Error>> { let response = if self.engine.put(key, vec![]) { Response::new() } else { Response::new().with_status(StatusCode::InternalServerError) }; Box::new(future::ok(response)) } fn default(&self) -> Box<Future<Item=Response, Error=hyper::Error>> { Box::new(future::ok(Response::new().with_status(StatusCode::NotFound))) } }
29.024
103
0.54796
f8f7e581cfc28e80a12991b1704fc58fd4100d4f
56,907
//! A higher level Clang API built on top of the generated bindings in the //! `clang_sys` module. #![allow(non_upper_case_globals, dead_code)] use cexpr; use clang_sys::*; use regex; use std::{mem, ptr, slice}; use std::ffi::{CStr, CString}; use std::fmt; use std::hash::Hash; use std::hash::Hasher; use std::os::raw::{c_char, c_int, c_uint, c_ulong, c_longlong, c_ulonglong}; /// A cursor into the Clang AST, pointing to an AST node. /// /// We call the AST node pointed to by the cursor the cursor's "referent". #[derive(Copy, Clone)] pub struct Cursor { x: CXCursor, } impl fmt::Debug for Cursor { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!( fmt, "Cursor({} kind: {}, loc: {}, usr: {:?})", self.spelling(), kind_to_str(self.kind()), self.location(), self.usr() ) } } impl Cursor { /// Get the Unified Symbol Resolution for this cursor's referent, if /// available. /// /// The USR can be used to compare entities across translation units. pub fn usr(&self) -> Option<String> { let s = unsafe { cxstring_into_string(clang_getCursorUSR(self.x)) }; if s.is_empty() { None } else { Some(s) } } /// Is this cursor's referent a declaration? pub fn is_declaration(&self) -> bool { unsafe { clang_isDeclaration(self.kind()) != 0 } } /// Get this cursor's referent's spelling. pub fn spelling(&self) -> String { unsafe { cxstring_into_string(clang_getCursorSpelling(self.x)) } } /// Get this cursor's referent's display name. /// /// This is not necessarily a valid identifier. It includes extra /// information, such as parameters for a function, etc. pub fn display_name(&self) -> String { unsafe { cxstring_into_string(clang_getCursorDisplayName(self.x)) } } /// Get the mangled name of this cursor's referent. pub fn mangling(&self) -> String { if clang_Cursor_getMangling::is_loaded() { unsafe { cxstring_into_string(clang_Cursor_getMangling(self.x)) } } else { self.spelling() } } /// Gets the C++ manglings for this cursor, or an error if the function is /// not loaded or the manglings are not available. pub fn cxx_manglings(&self) -> Result<Vec<String>, ()> { use clang_sys::*; if !clang_Cursor_getCXXManglings::is_loaded() { return Err(()); } unsafe { let manglings = clang_Cursor_getCXXManglings(self.x); if manglings.is_null() { return Err(()); } let count = (*manglings).Count as usize; let mut result = Vec::with_capacity(count); for i in 0..count { let string_ptr = (*manglings).Strings.offset(i as isize); result.push(cxstring_to_string_leaky(*string_ptr)); } clang_disposeStringSet(manglings); Ok(result) } } /// Returns whether the cursor refers to a built-in definition. pub fn is_builtin(&self) -> bool { let (file, _, _, _) = self.location().location(); file.name().is_none() } /// Get the `Cursor` for this cursor's referent's lexical parent. /// /// The lexical parent is the parent of the definition. The semantic parent /// is the parent of the declaration. Generally, the lexical parent doesn't /// have any effect on semantics, while the semantic parent does. /// /// In the following snippet, the `Foo` class would be the semantic parent /// of the out-of-line `method` definition, while the lexical parent is the /// translation unit. /// /// ```c++ /// class Foo { /// void method(); /// }; /// /// void Foo::method() { /* ... */ } /// ``` pub fn lexical_parent(&self) -> Cursor { unsafe { Cursor { x: clang_getCursorLexicalParent(self.x), } } } /// Get the referent's semantic parent, if one is available. /// /// See documentation for `lexical_parent` for details on semantic vs /// lexical parents. pub fn fallible_semantic_parent(&self) -> Option<Cursor> { let sp = unsafe { Cursor { x: clang_getCursorSemanticParent(self.x), } }; if sp == *self || !sp.is_valid() { return None; } Some(sp) } /// Get the referent's semantic parent. /// /// See documentation for `lexical_parent` for details on semantic vs /// lexical parents. pub fn semantic_parent(&self) -> Cursor { self.fallible_semantic_parent().unwrap() } /// Return the number of template arguments used by this cursor's referent, /// if the referent is either a template instantiation. Returns `None` /// otherwise. /// /// NOTE: This may not return `Some` for partial template specializations, /// see #193 and #194. pub fn num_template_args(&self) -> Option<u32> { // XXX: `clang_Type_getNumTemplateArguments` is sort of reliable, while // `clang_Cursor_getNumTemplateArguments` is totally unreliable. // Therefore, try former first, and only fallback to the latter if we // have to. self.cur_type() .num_template_args() .or_else(|| { let n: c_int = unsafe { clang_Cursor_getNumTemplateArguments(self.x) }; if n >= 0 { Some(n as u32) } else { debug_assert_eq!(n, -1); None } }) .or_else(|| { let canonical = self.canonical(); if canonical != *self { canonical.num_template_args() } else { None } }) } /// Get a cursor pointing to this referent's containing translation unit. /// /// Note that we shouldn't create a `TranslationUnit` struct here, because /// bindgen assumes there will only be one of them alive at a time, and /// disposes it on drop. That can change if this would be required, but I /// think we can survive fine without it. pub fn translation_unit(&self) -> Cursor { assert!(self.is_valid()); unsafe { let tu = clang_Cursor_getTranslationUnit(self.x); let cursor = Cursor { x: clang_getTranslationUnitCursor(tu), }; assert!(cursor.is_valid()); cursor } } /// Is the referent a top level construct? pub fn is_toplevel(&self) -> bool { let mut semantic_parent = self.fallible_semantic_parent(); while semantic_parent.is_some() && (semantic_parent.unwrap().kind() == CXCursor_Namespace || semantic_parent.unwrap().kind() == CXCursor_NamespaceAlias || semantic_parent.unwrap().kind() == CXCursor_NamespaceRef) { semantic_parent = semantic_parent.unwrap().fallible_semantic_parent(); } let tu = self.translation_unit(); // Yes, this can happen with, e.g., macro definitions. semantic_parent == tu.fallible_semantic_parent() } /// There are a few kinds of types that we need to treat specially, mainly /// not tracking the type declaration but the location of the cursor, given /// clang doesn't expose a proper declaration for these types. pub fn is_template_like(&self) -> bool { match self.kind() { CXCursor_ClassTemplate | CXCursor_ClassTemplatePartialSpecialization | CXCursor_TypeAliasTemplateDecl => true, _ => false, } } /// Get the kind of referent this cursor is pointing to. pub fn kind(&self) -> CXCursorKind { self.x.kind } /// Returns true is the cursor is a definition pub fn is_definition(&self) -> bool { unsafe { clang_isCursorDefinition(self.x) != 0 } } /// Is the referent a template specialization? pub fn is_template_specialization(&self) -> bool { self.specialized().is_some() } /// Is the referent a fully specialized template specialization without any /// remaining free template arguments? pub fn is_fully_specialized_template(&self) -> bool { self.is_template_specialization() && self.kind() != CXCursor_ClassTemplatePartialSpecialization && self.num_template_args().unwrap_or(0) > 0 } /// Is the referent a template specialization that still has remaining free /// template arguments? pub fn is_in_non_fully_specialized_template(&self) -> bool { if self.is_toplevel() { return false; } let parent = self.semantic_parent(); if parent.is_fully_specialized_template() { return false; } if !parent.is_template_like() { return parent.is_in_non_fully_specialized_template(); } return true; } /// Is this cursor pointing a valid referent? pub fn is_valid(&self) -> bool { unsafe { clang_isInvalid(self.kind()) == 0 } } /// Get the source location for the referent. pub fn location(&self) -> SourceLocation { unsafe { SourceLocation { x: clang_getCursorLocation(self.x), } } } /// Get the source location range for the referent. pub fn extent(&self) -> CXSourceRange { unsafe { clang_getCursorExtent(self.x) } } /// Get the raw declaration comment for this referent, if one exists. pub fn raw_comment(&self) -> Option<String> { let s = unsafe { cxstring_into_string(clang_Cursor_getRawCommentText(self.x)) }; if s.is_empty() { None } else { Some(s) } } /// Get the referent's parsed comment. pub fn comment(&self) -> Comment { unsafe { Comment { x: clang_Cursor_getParsedComment(self.x), } } } /// Get the referent's type. pub fn cur_type(&self) -> Type { unsafe { Type { x: clang_getCursorType(self.x), } } } /// Given that this cursor's referent is a reference to another type, or is /// a declaration, get the cursor pointing to the referenced type or type of /// the declared thing. pub fn definition(&self) -> Option<Cursor> { unsafe { let ret = Cursor { x: clang_getCursorDefinition(self.x), }; if ret.is_valid() && ret.kind() != CXCursor_NoDeclFound { Some(ret) } else { None } } } /// Given that this cursor's referent is reference type, get the cursor /// pointing to the referenced type. pub fn referenced(&self) -> Option<Cursor> { unsafe { let ret = Cursor { x: clang_getCursorReferenced(self.x), }; if ret.is_valid() { Some(ret) } else { None } } } /// Get the canonical cursor for this referent. /// /// Many types can be declared multiple times before finally being properly /// defined. This method allows us to get the canonical cursor for the /// referent type. pub fn canonical(&self) -> Cursor { unsafe { Cursor { x: clang_getCanonicalCursor(self.x), } } } /// Given that this cursor points to either a template specialization or a /// template instantiation, get a cursor pointing to the template definition /// that is being specialized. pub fn specialized(&self) -> Option<Cursor> { unsafe { let ret = Cursor { x: clang_getSpecializedCursorTemplate(self.x), }; if ret.is_valid() { Some(ret) } else { None } } } /// Assuming that this cursor's referent is a template declaration, get the /// kind of cursor that would be generated for its specializations. pub fn template_kind(&self) -> CXCursorKind { unsafe { clang_getTemplateCursorKind(self.x) } } /// Traverse this cursor's referent and its children. /// /// Call the given function on each AST node traversed. pub fn visit<Visitor>(&self, mut visitor: Visitor) where Visitor: FnMut(Cursor) -> CXChildVisitResult, { unsafe { clang_visitChildren( self.x, visit_children::<Visitor>, mem::transmute(&mut visitor), ); } } /// Collect all of this cursor's children into a vec and return them. pub fn collect_children(&self) -> Vec<Cursor> { let mut children = vec![]; self.visit(|c| { children.push(c); CXChildVisit_Continue }); children } /// Does this cursor have any children? pub fn has_children(&self) -> bool { let mut has_children = false; self.visit(|_| { has_children = true; CXChildVisit_Break }); has_children } /// Does this cursor have at least `n` children? pub fn has_at_least_num_children(&self, n: usize) -> bool { assert!(n > 0); let mut num_left = n; self.visit(|_| { num_left -= 1; if num_left == 0 { CXChildVisit_Break } else { CXChildVisit_Continue } }); num_left == 0 } /// Returns whether the given location contains a cursor with the given /// kind in the first level of nesting underneath (doesn't look /// recursively). pub fn contains_cursor(&self, kind: CXCursorKind) -> bool { let mut found = false; self.visit(|c| if c.kind() == kind { found = true; CXChildVisit_Break } else { CXChildVisit_Continue }); found } /// Is the referent an inlined function? pub fn is_inlined_function(&self) -> bool { clang_Cursor_isFunctionInlined::is_loaded() && unsafe { clang_Cursor_isFunctionInlined(self.x) != 0 } } /// Get the width of this cursor's referent bit field, or `None` if the /// referent is not a bit field. pub fn bit_width(&self) -> Option<u32> { unsafe { let w = clang_getFieldDeclBitWidth(self.x); if w == -1 { None } else { Some(w as u32) } } } /// Get the integer representation type used to hold this cursor's referent /// enum type. pub fn enum_type(&self) -> Option<Type> { unsafe { let t = Type { x: clang_getEnumDeclIntegerType(self.x), }; if t.is_valid() { Some(t) } else { None } } } /// Get the signed constant value for this cursor's enum variant referent. /// /// Returns None if the cursor's referent is not an enum variant. pub fn enum_val_signed(&self) -> Option<i64> { unsafe { if self.kind() == CXCursor_EnumConstantDecl { Some(clang_getEnumConstantDeclValue(self.x) as i64) } else { None } } } /// Get the unsigned constant value for this cursor's enum variant referent. /// /// Returns None if the cursor's referent is not an enum variant. pub fn enum_val_unsigned(&self) -> Option<u64> { unsafe { if self.kind() == CXCursor_EnumConstantDecl { Some(clang_getEnumConstantDeclUnsignedValue(self.x) as u64) } else { None } } } /// Given that this cursor's referent is a `typedef`, get the `Type` that is /// being aliased. pub fn typedef_type(&self) -> Option<Type> { let inner = Type { x: unsafe { clang_getTypedefDeclUnderlyingType(self.x) }, }; if inner.is_valid() { Some(inner) } else { None } } /// Get the linkage kind for this cursor's referent. /// /// This only applies to functions and variables. pub fn linkage(&self) -> CXLinkageKind { unsafe { clang_getCursorLinkage(self.x) } } /// Get the visibility of this cursor's referent. pub fn visibility(&self) -> CXVisibilityKind { if clang_getCursorVisibility::is_loaded() { unsafe { clang_getCursorVisibility(self.x) } } else { CXVisibility_Default } } /// Given that this cursor's referent is a function, return cursors to its /// parameters. pub fn args(&self) -> Option<Vec<Cursor>> { // XXX: We might want to use and keep num_args // match self.kind() { // CXCursor_FunctionDecl | // CXCursor_CXXMethod => { unsafe { let w = clang_Cursor_getNumArguments(self.x); if w == -1 { None } else { let num = w as u32; let mut args = vec![]; for i in 0..num { args.push(Cursor { x: clang_Cursor_getArgument(self.x, i as c_uint), }); } Some(args) } } } /// Given that this cursor's referent is a function/method call or /// declaration, return the number of arguments it takes. /// /// Returns -1 if the cursor's referent is not a function/method call or /// declaration. pub fn num_args(&self) -> Result<u32, ()> { unsafe { let w = clang_Cursor_getNumArguments(self.x); if w == -1 { Err(()) } else { Ok(w as u32) } } } /// Get the access specifier for this cursor's referent. pub fn access_specifier(&self) -> CX_CXXAccessSpecifier { unsafe { clang_getCXXAccessSpecifier(self.x) } } /// Is this cursor's referent a field declaration that is marked as /// `mutable`? pub fn is_mutable_field(&self) -> bool { clang_CXXField_isMutable::is_loaded() && unsafe { clang_CXXField_isMutable(self.x) != 0 } } /// Get the offset of the field represented by the Cursor. pub fn offset_of_field(&self) -> Result<usize, LayoutError> { if !clang_Cursor_getOffsetOfField::is_loaded() { return Err(LayoutError::from(-1)); } let offset = unsafe { clang_Cursor_getOffsetOfField(self.x) }; if offset < 0 { Err(LayoutError::from(offset as i32)) } else { Ok(offset as usize) } } /// Is this cursor's referent a member function that is declared `static`? pub fn method_is_static(&self) -> bool { unsafe { clang_CXXMethod_isStatic(self.x) != 0 } } /// Is this cursor's referent a member function that is declared `const`? pub fn method_is_const(&self) -> bool { unsafe { clang_CXXMethod_isConst(self.x) != 0 } } /// Is this cursor's referent a member function that is virtual? pub fn method_is_virtual(&self) -> bool { unsafe { clang_CXXMethod_isVirtual(self.x) != 0 } } /// Is this cursor's referent a member function that is pure virtual? pub fn method_is_pure_virtual(&self) -> bool { unsafe { clang_CXXMethod_isPureVirtual(self.x) != 0 } } /// Is this cursor's referent a struct or class with virtual members? pub fn is_virtual_base(&self) -> bool { unsafe { clang_isVirtualBase(self.x) != 0 } } /// Try to evaluate this cursor. pub fn evaluate(&self) -> Option<EvalResult> { EvalResult::new(*self) } /// Return the result type for this cursor pub fn ret_type(&self) -> Option<Type> { let rt = Type { x: unsafe { clang_getCursorResultType(self.x) }, }; if rt.is_valid() { Some(rt) } else { None } } /// Gets the tokens that correspond to that cursor. pub fn tokens(&self) -> Option<Vec<Token>> { let range = self.extent(); let mut tokens = vec![]; unsafe { let tu = clang_Cursor_getTranslationUnit(self.x); let mut token_ptr = ptr::null_mut(); let mut num_tokens: c_uint = 0; clang_tokenize(tu, range, &mut token_ptr, &mut num_tokens); if token_ptr.is_null() { return None; } let token_array = slice::from_raw_parts(token_ptr, num_tokens as usize); for &token in token_array.iter() { let kind = clang_getTokenKind(token); let spelling = cxstring_into_string(clang_getTokenSpelling(tu, token)); tokens.push(Token { kind: kind, spelling: spelling, }); } clang_disposeTokens(tu, token_ptr, num_tokens); } Some(tokens) } /// Gets the tokens that correspond to that cursor as `cexpr` tokens. pub fn cexpr_tokens(self) -> Option<Vec<cexpr::token::Token>> { use cexpr::token; self.tokens().map(|tokens| { tokens .into_iter() .filter_map(|token| { let kind = match token.kind { CXToken_Punctuation => token::Kind::Punctuation, CXToken_Literal => token::Kind::Literal, CXToken_Identifier => token::Kind::Identifier, CXToken_Keyword => token::Kind::Keyword, // NB: cexpr is not too happy about comments inside // expressions, so we strip them down here. CXToken_Comment => return None, _ => { error!("Found unexpected token kind: {:?}", token); return None; } }; Some(token::Token { kind: kind, raw: token.spelling.into_bytes().into_boxed_slice(), }) }) .collect::<Vec<_>>() }) } } /// Checks whether the name looks like an identifier, i.e. is alphanumeric /// (including '_') and does not start with a digit. pub fn is_valid_identifier(name: &str) -> bool { let mut chars = name.chars(); let first_valid = chars .next() .map(|c| c.is_alphabetic() || c == '_') .unwrap_or(false); first_valid && chars.all(|c| c.is_alphanumeric() || c == '_') } extern "C" fn visit_children<Visitor>( cur: CXCursor, _parent: CXCursor, data: CXClientData, ) -> CXChildVisitResult where Visitor: FnMut(Cursor) -> CXChildVisitResult, { let func: &mut Visitor = unsafe { mem::transmute(data) }; let child = Cursor { x: cur, }; (*func)(child) } impl PartialEq for Cursor { fn eq(&self, other: &Cursor) -> bool { unsafe { clang_equalCursors(self.x, other.x) == 1 } } } impl Eq for Cursor {} impl Hash for Cursor { fn hash<H: Hasher>(&self, state: &mut H) { unsafe { clang_hashCursor(self.x) }.hash(state) } } /// The type of a node in clang's AST. #[derive(Clone, Copy)] pub struct Type { x: CXType, } impl PartialEq for Type { fn eq(&self, other: &Self) -> bool { unsafe { clang_equalTypes(self.x, other.x) != 0 } } } impl Eq for Type {} impl fmt::Debug for Type { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!( fmt, "Type({}, kind: {}, cconv: {}, decl: {:?}, canon: {:?})", self.spelling(), type_to_str(self.kind()), self.call_conv(), self.declaration(), self.declaration().canonical() ) } } /// An error about the layout of a struct, class, or type. #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] pub enum LayoutError { /// Asked for the layout of an invalid type. Invalid, /// Asked for the layout of an incomplete type. Incomplete, /// Asked for the layout of a dependent type. Dependent, /// Asked for the layout of a type that does not have constant size. NotConstantSize, /// Asked for the layout of a field in a type that does not have such a /// field. InvalidFieldName, /// An unknown layout error. Unknown, } impl ::std::convert::From<i32> for LayoutError { fn from(val: i32) -> Self { use self::LayoutError::*; match val { CXTypeLayoutError_Invalid => Invalid, CXTypeLayoutError_Incomplete => Incomplete, CXTypeLayoutError_Dependent => Dependent, CXTypeLayoutError_NotConstantSize => NotConstantSize, CXTypeLayoutError_InvalidFieldName => InvalidFieldName, _ => Unknown, } } } impl Type { /// Get this type's kind. pub fn kind(&self) -> CXTypeKind { self.x.kind } /// Get a cursor pointing to this type's declaration. pub fn declaration(&self) -> Cursor { unsafe { Cursor { x: clang_getTypeDeclaration(self.x), } } } /// Get the canonical declaration of this type, if it is available. pub fn canonical_declaration( &self, location: Option<&Cursor>, ) -> Option<CanonicalTypeDeclaration> { let mut declaration = self.declaration(); if !declaration.is_valid() { if let Some(location) = location { let mut location = *location; if let Some(referenced) = location.referenced() { location = referenced; } if location.is_template_like() { declaration = location; } } } let canonical = declaration.canonical(); if canonical.is_valid() && canonical.kind() != CXCursor_NoDeclFound { Some(CanonicalTypeDeclaration(*self, canonical)) } else { None } } /// Get a raw display name for this type. pub fn spelling(&self) -> String { let s = unsafe { cxstring_into_string(clang_getTypeSpelling(self.x)) }; // Clang 5.0 introduced changes in the spelling API so it returned the // full qualified name. Let's undo that here. if s.split("::").all(|s| is_valid_identifier(s)) { if let Some(s) = s.split("::").last() { return s.to_owned(); } } s } /// Is this type const qualified? pub fn is_const(&self) -> bool { unsafe { clang_isConstQualifiedType(self.x) != 0 } } /// What is the size of this type? Paper over invalid types by returning `0` /// for them. pub fn size(&self) -> usize { unsafe { let val = clang_Type_getSizeOf(self.x); if val < 0 { 0 } else { val as usize } } } /// What is the size of this type? pub fn fallible_size(&self) -> Result<usize, LayoutError> { let val = unsafe { clang_Type_getSizeOf(self.x) }; if val < 0 { Err(LayoutError::from(val as i32)) } else { Ok(val as usize) } } /// What is the alignment of this type? Paper over invalid types by /// returning `0`. pub fn align(&self) -> usize { unsafe { let val = clang_Type_getAlignOf(self.x); if val < 0 { 0 } else { val as usize } } } /// What is the alignment of this type? pub fn fallible_align(&self) -> Result<usize, LayoutError> { unsafe { let val = clang_Type_getAlignOf(self.x); if val < 0 { Err(LayoutError::from(val as i32)) } else { Ok(val as usize) } } } /// Get the layout for this type, or an error describing why it does not /// have a valid layout. pub fn fallible_layout(&self) -> Result<::ir::layout::Layout, LayoutError> { use ir::layout::Layout; let size = self.fallible_size()?; let align = self.fallible_align()?; Ok(Layout::new(size, align)) } /// Get the number of template arguments this type has, or `None` if it is /// not some kind of template. pub fn num_template_args(&self) -> Option<u32> { // If an old libclang is loaded, we have no hope of answering this // question correctly. However, that's no reason to panic when // generating bindings for simple C headers with an old libclang. if !clang_Type_getNumTemplateArguments::is_loaded() { return None } let n = unsafe { clang_Type_getNumTemplateArguments(self.x) }; if n >= 0 { Some(n as u32) } else { debug_assert_eq!(n, -1); None } } /// If this type is a class template specialization, return its /// template arguments. Otherwise, return None. pub fn template_args(&self) -> Option<TypeTemplateArgIterator> { self.num_template_args().map(|n| { TypeTemplateArgIterator { x: self.x, length: n, index: 0, } }) } /// Given that this type is a pointer type, return the type that it points /// to. pub fn pointee_type(&self) -> Option<Type> { match self.kind() { CXType_Pointer | CXType_RValueReference | CXType_LValueReference | CXType_MemberPointer | CXType_BlockPointer | CXType_ObjCObjectPointer => { let ret = Type { x: unsafe { clang_getPointeeType(self.x) }, }; debug_assert!(ret.is_valid()); Some(ret) } _ => None, } } /// Given that this type is an array, vector, or complex type, return the /// type of its elements. pub fn elem_type(&self) -> Option<Type> { let current_type = Type { x: unsafe { clang_getElementType(self.x) }, }; if current_type.is_valid() { Some(current_type) } else { None } } /// Given that this type is an array or vector type, return its number of /// elements. pub fn num_elements(&self) -> Option<usize> { let num_elements_returned = unsafe { clang_getNumElements(self.x) }; if num_elements_returned != -1 { Some(num_elements_returned as usize) } else { None } } /// Get the canonical version of this type. This sees through `typedef`s and /// aliases to get the underlying, canonical type. pub fn canonical_type(&self) -> Type { unsafe { Type { x: clang_getCanonicalType(self.x), } } } /// Is this type a variadic function type? pub fn is_variadic(&self) -> bool { unsafe { clang_isFunctionTypeVariadic(self.x) != 0 } } /// Given that this type is a function type, get the type of its return /// value. pub fn ret_type(&self) -> Option<Type> { let rt = Type { x: unsafe { clang_getResultType(self.x) }, }; if rt.is_valid() { Some(rt) } else { None } } /// Given that this type is a function type, get its calling convention. If /// this is not a function type, `CXCallingConv_Invalid` is returned. pub fn call_conv(&self) -> CXCallingConv { unsafe { clang_getFunctionTypeCallingConv(self.x) } } /// For elaborated types (types which use `class`, `struct`, or `union` to /// disambiguate types from local bindings), get the underlying type. pub fn named(&self) -> Type { unsafe { Type { x: if clang_Type_getNamedType::is_loaded() { clang_Type_getNamedType(self.x) } else { self.x }, } } } /// Is this a valid type? pub fn is_valid(&self) -> bool { self.kind() != CXType_Invalid } /// Is this a valid and exposed type? pub fn is_valid_and_exposed(&self) -> bool { self.is_valid() && self.kind() != CXType_Unexposed } /// Is this type a fully instantiated template? pub fn is_fully_instantiated_template(&self) -> bool { // Yep, the spelling of this containing type-parameter is extremely // nasty... But can happen in <type_traits>. Unfortunately I couldn't // reduce it enough :( self.template_args().map_or(false, |args| args.len() > 0) && match self.declaration().kind() { CXCursor_ClassTemplatePartialSpecialization | CXCursor_TypeAliasTemplateDecl | CXCursor_TemplateTemplateParameter => false, _ => true, } } /// Is this type an associated template type? Eg `T::Associated` in /// this example: /// /// ```c++ /// template <typename T> /// class Foo { /// typename T::Associated member; /// }; /// ``` pub fn is_associated_type(&self) -> bool { // This is terrible :( fn hacky_parse_associated_type<S: AsRef<str>>(spelling: S) -> bool { lazy_static! { static ref ASSOC_TYPE_RE: regex::Regex = regex::Regex::new(r"typename type\-parameter\-\d+\-\d+::.+").unwrap(); } ASSOC_TYPE_RE.is_match(spelling.as_ref()) } self.kind() == CXType_Unexposed && (hacky_parse_associated_type(self.spelling()) || hacky_parse_associated_type(self.canonical_type().spelling())) } } /// The `CanonicalTypeDeclaration` type exists as proof-by-construction that its /// cursor is the canonical declaration for its type. If you have a /// `CanonicalTypeDeclaration` instance, you know for sure that the type and /// cursor match up in a canonical declaration relationship, and it simply /// cannot be otherwise. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct CanonicalTypeDeclaration(Type, Cursor); impl CanonicalTypeDeclaration { /// Get the type. pub fn ty(&self) -> &Type { &self.0 } /// Get the type's canonical declaration cursor. pub fn cursor(&self) -> &Cursor { &self.1 } } /// An iterator for a type's template arguments. pub struct TypeTemplateArgIterator { x: CXType, length: u32, index: u32, } impl Iterator for TypeTemplateArgIterator { type Item = Type; fn next(&mut self) -> Option<Type> { if self.index < self.length { let idx = self.index as c_uint; self.index += 1; Some(Type { x: unsafe { clang_Type_getTemplateArgumentAsType(self.x, idx) }, }) } else { None } } } impl ExactSizeIterator for TypeTemplateArgIterator { fn len(&self) -> usize { assert!(self.index <= self.length); (self.length - self.index) as usize } } /// A `SourceLocation` is a file, line, column, and byte offset location for /// some source text. pub struct SourceLocation { x: CXSourceLocation, } impl SourceLocation { /// Get the (file, line, column, byte offset) tuple for this source /// location. pub fn location(&self) -> (File, usize, usize, usize) { unsafe { let mut file = mem::zeroed(); let mut line = 0; let mut col = 0; let mut off = 0; clang_getSpellingLocation( self.x, &mut file, &mut line, &mut col, &mut off, ); ( File { x: file, }, line as usize, col as usize, off as usize, ) } } } impl fmt::Display for SourceLocation { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let (file, line, col, _) = self.location(); if let Some(name) = file.name() { write!(f, "{}:{}:{}", name, line, col) } else { "builtin definitions".fmt(f) } } } /// A comment in the source text. /// /// Comments are sort of parsed by Clang, and have a tree structure. pub struct Comment { x: CXComment, } impl Comment { /// What kind of comment is this? pub fn kind(&self) -> CXCommentKind { unsafe { clang_Comment_getKind(self.x) } } /// Get this comment's children comment pub fn get_children(&self) -> CommentChildrenIterator { CommentChildrenIterator { parent: self.x, length: unsafe { clang_Comment_getNumChildren(self.x) }, index: 0, } } /// Given that this comment is the start or end of an HTML tag, get its tag /// name. pub fn get_tag_name(&self) -> String { unsafe { cxstring_into_string(clang_HTMLTagComment_getTagName(self.x)) } } /// Given that this comment is an HTML start tag, get its attributes. pub fn get_tag_attrs(&self) -> CommentAttributesIterator { CommentAttributesIterator { x: self.x, length: unsafe { clang_HTMLStartTag_getNumAttrs(self.x) }, index: 0, } } } /// An iterator for a comment's children pub struct CommentChildrenIterator { parent: CXComment, length: c_uint, index: c_uint, } impl Iterator for CommentChildrenIterator { type Item = Comment; fn next(&mut self) -> Option<Comment> { if self.index < self.length { let idx = self.index; self.index += 1; Some(Comment { x: unsafe { clang_Comment_getChild(self.parent, idx) }, }) } else { None } } } /// An HTML start tag comment attribute pub struct CommentAttribute { /// HTML start tag attribute name pub name: String, /// HTML start tag attribute value pub value: String, } /// An iterator for a comment's attributes pub struct CommentAttributesIterator { x: CXComment, length: c_uint, index: c_uint, } impl Iterator for CommentAttributesIterator { type Item = CommentAttribute; fn next(&mut self) -> Option<CommentAttribute> { if self.index < self.length { let idx = self.index; self.index += 1; Some(CommentAttribute { name: unsafe { cxstring_into_string( clang_HTMLStartTag_getAttrName(self.x, idx), ) }, value: unsafe { cxstring_into_string( clang_HTMLStartTag_getAttrValue(self.x, idx), ) }, }) } else { None } } } /// A source file. pub struct File { x: CXFile, } impl File { /// Get the name of this source file. pub fn name(&self) -> Option<String> { if self.x.is_null() { return None; } Some(unsafe { cxstring_into_string(clang_getFileName(self.x)) }) } } fn cxstring_to_string_leaky(s: CXString) -> String { if s.data.is_null() { return "".to_owned(); } let c_str = unsafe { CStr::from_ptr(clang_getCString(s) as *const _) }; c_str.to_string_lossy().into_owned() } fn cxstring_into_string(s: CXString) -> String { let ret = cxstring_to_string_leaky(s); unsafe { clang_disposeString(s) }; ret } /// An `Index` is an environment for a set of translation units that will /// typically end up linked together in one final binary. pub struct Index { x: CXIndex, } impl Index { /// Construct a new `Index`. /// /// The `pch` parameter controls whether declarations in pre-compiled /// headers are included when enumerating a translation unit's "locals". /// /// The `diag` parameter controls whether debugging diagnostics are enabled. pub fn new(pch: bool, diag: bool) -> Index { unsafe { Index { x: clang_createIndex(pch as c_int, diag as c_int), } } } } impl fmt::Debug for Index { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "Index {{ }}") } } impl Drop for Index { fn drop(&mut self) { unsafe { clang_disposeIndex(self.x); } } } /// A token emitted by clang's lexer. #[derive(Debug)] pub struct Token { /// The kind of token this is. pub kind: CXTokenKind, /// A display name for this token. pub spelling: String, } /// A translation unit (or "compilation unit"). pub struct TranslationUnit { x: CXTranslationUnit, } impl fmt::Debug for TranslationUnit { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "TranslationUnit {{ }}") } } impl TranslationUnit { /// Parse a source file into a translation unit. pub fn parse( ix: &Index, file: &str, cmd_args: &[String], unsaved: &[UnsavedFile], opts: CXTranslationUnit_Flags, ) -> Option<TranslationUnit> { let fname = CString::new(file).unwrap(); let _c_args: Vec<CString> = cmd_args .iter() .map(|s| CString::new(s.clone()).unwrap()) .collect(); let c_args: Vec<*const c_char> = _c_args.iter().map(|s| s.as_ptr()).collect(); let mut c_unsaved: Vec<CXUnsavedFile> = unsaved.iter().map(|f| f.x).collect(); let tu = unsafe { clang_parseTranslationUnit( ix.x, fname.as_ptr(), c_args.as_ptr(), c_args.len() as c_int, c_unsaved.as_mut_ptr(), c_unsaved.len() as c_uint, opts, ) }; if tu.is_null() { None } else { Some(TranslationUnit { x: tu, }) } } /// Get the Clang diagnostic information associated with this translation /// unit. pub fn diags(&self) -> Vec<Diagnostic> { unsafe { let num = clang_getNumDiagnostics(self.x) as usize; let mut diags = vec![]; for i in 0..num { diags.push(Diagnostic { x: clang_getDiagnostic(self.x, i as c_uint), }); } diags } } /// Get a cursor pointing to the root of this translation unit's AST. pub fn cursor(&self) -> Cursor { unsafe { Cursor { x: clang_getTranslationUnitCursor(self.x), } } } /// Is this the null translation unit? pub fn is_null(&self) -> bool { self.x.is_null() } } impl Drop for TranslationUnit { fn drop(&mut self) { unsafe { clang_disposeTranslationUnit(self.x); } } } /// A diagnostic message generated while parsing a translation unit. pub struct Diagnostic { x: CXDiagnostic, } impl Diagnostic { /// Format this diagnostic message as a string, using the given option bit /// flags. pub fn format(&self) -> String { unsafe { let opts = clang_defaultDiagnosticDisplayOptions(); cxstring_into_string(clang_formatDiagnostic(self.x, opts)) } } /// What is the severity of this diagnostic message? pub fn severity(&self) -> CXDiagnosticSeverity { unsafe { clang_getDiagnosticSeverity(self.x) } } } impl Drop for Diagnostic { /// Destroy this diagnostic message. fn drop(&mut self) { unsafe { clang_disposeDiagnostic(self.x); } } } /// A file which has not been saved to disk. pub struct UnsavedFile { x: CXUnsavedFile, /// The name of the unsaved file. Kept here to avoid leaving dangling pointers in /// `CXUnsavedFile`. pub name: CString, contents: CString, } impl UnsavedFile { /// Construct a new unsaved file with the given `name` and `contents`. pub fn new(name: &str, contents: &str) -> UnsavedFile { let name = CString::new(name).unwrap(); let contents = CString::new(contents).unwrap(); let x = CXUnsavedFile { Filename: name.as_ptr(), Contents: contents.as_ptr(), Length: contents.as_bytes().len() as c_ulong, }; UnsavedFile { x: x, name: name, contents: contents, } } } impl fmt::Debug for UnsavedFile { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!( fmt, "UnsavedFile(name: {:?}, contents: {:?})", self.name, self.contents ) } } /// Convert a cursor kind into a static string. pub fn kind_to_str(x: CXCursorKind) -> String { unsafe { cxstring_into_string(clang_getCursorKindSpelling(x)) } } /// Convert a type kind to a static string. pub fn type_to_str(x: CXTypeKind) -> String { unsafe { cxstring_into_string(clang_getTypeKindSpelling(x)) } } /// Dump the Clang AST to stdout for debugging purposes. pub fn ast_dump(c: &Cursor, depth: isize) -> CXChildVisitResult { fn print_indent<S: AsRef<str>>(depth: isize, s: S) { for _ in 0..depth { print!(" "); } println!("{}", s.as_ref()); } fn print_cursor<S: AsRef<str>>(depth: isize, prefix: S, c: &Cursor) { let prefix = prefix.as_ref(); print_indent( depth, format!(" {}kind = {}", prefix, kind_to_str(c.kind())), ); print_indent( depth, format!(" {}spelling = \"{}\"", prefix, c.spelling()), ); print_indent(depth, format!(" {}location = {}", prefix, c.location())); print_indent( depth, format!(" {}is-definition? {}", prefix, c.is_definition()), ); print_indent( depth, format!(" {}is-declaration? {}", prefix, c.is_declaration()), ); print_indent( depth, format!( " {}is-inlined-function? {}", prefix, c.is_inlined_function() ), ); let templ_kind = c.template_kind(); if templ_kind != CXCursor_NoDeclFound { print_indent( depth, format!(" {}template-kind = {}", prefix, kind_to_str(templ_kind)), ); } if let Some(usr) = c.usr() { print_indent(depth, format!(" {}usr = \"{}\"", prefix, usr)); } if let Ok(num) = c.num_args() { print_indent(depth, format!(" {}number-of-args = {}", prefix, num)); } if let Some(num) = c.num_template_args() { print_indent( depth, format!(" {}number-of-template-args = {}", prefix, num), ); } if let Some(width) = c.bit_width() { print_indent(depth, format!(" {}bit-width = {}", prefix, width)); } if let Some(ty) = c.enum_type() { print_indent( depth, format!(" {}enum-type = {}", prefix, type_to_str(ty.kind())), ); } if let Some(val) = c.enum_val_signed() { print_indent(depth, format!(" {}enum-val = {}", prefix, val)); } if let Some(ty) = c.typedef_type() { print_indent( depth, format!(" {}typedef-type = {}", prefix, type_to_str(ty.kind())), ); } if let Some(ty) = c.ret_type() { print_indent( depth, format!(" {}ret-type = {}", prefix, type_to_str(ty.kind())), ); } if let Some(refd) = c.referenced() { if refd != *c { println!(""); print_cursor( depth, String::from(prefix) + "referenced.", &refd, ); } } let canonical = c.canonical(); if canonical != *c { println!(""); print_cursor( depth, String::from(prefix) + "canonical.", &canonical, ); } if let Some(specialized) = c.specialized() { if specialized != *c { println!(""); print_cursor( depth, String::from(prefix) + "specialized.", &specialized, ); } } if let Some(parent) = c.fallible_semantic_parent() { println!(""); print_cursor( depth, String::from(prefix) + "semantic-parent.", &parent, ); } } fn print_type<S: AsRef<str>>(depth: isize, prefix: S, ty: &Type) { let prefix = prefix.as_ref(); let kind = ty.kind(); print_indent(depth, format!(" {}kind = {}", prefix, type_to_str(kind))); if kind == CXType_Invalid { return; } print_indent(depth, format!(" {}cconv = {}", prefix, ty.call_conv())); print_indent( depth, format!(" {}spelling = \"{}\"", prefix, ty.spelling()), ); let num_template_args = if clang_Type_getNumTemplateArguments::is_loaded() { unsafe { clang_Type_getNumTemplateArguments(ty.x) } } else { -1 }; if num_template_args >= 0 { print_indent( depth, format!( " {}number-of-template-args = {}", prefix, num_template_args ), ); } if let Some(num) = ty.num_elements() { print_indent( depth, format!(" {}number-of-elements = {}", prefix, num), ); } print_indent( depth, format!(" {}is-variadic? {}", prefix, ty.is_variadic()), ); let canonical = ty.canonical_type(); if canonical != *ty { println!(""); print_type(depth, String::from(prefix) + "canonical.", &canonical); } if let Some(pointee) = ty.pointee_type() { if pointee != *ty { println!(""); print_type(depth, String::from(prefix) + "pointee.", &pointee); } } if let Some(elem) = ty.elem_type() { if elem != *ty { println!(""); print_type(depth, String::from(prefix) + "elements.", &elem); } } if let Some(ret) = ty.ret_type() { if ret != *ty { println!(""); print_type(depth, String::from(prefix) + "return.", &ret); } } let named = ty.named(); if named != *ty && named.is_valid() { println!(""); print_type(depth, String::from(prefix) + "named.", &named); } } print_indent(depth, "("); print_cursor(depth, "", c); println!(""); let ty = c.cur_type(); print_type(depth, "type.", &ty); let declaration = ty.declaration(); if declaration != *c && declaration.kind() != CXCursor_NoDeclFound { println!(""); print_cursor(depth, "type.declaration.", &declaration); } // Recurse. let mut found_children = false; c.visit(|s| { if !found_children { println!(""); found_children = true; } ast_dump(&s, depth + 1) }); print_indent(depth, ")"); CXChildVisit_Continue } /// Try to extract the clang version to a string pub fn extract_clang_version() -> String { unsafe { cxstring_into_string(clang_getClangVersion()) } } /// A wrapper for the result of evaluating an expression. #[derive(Debug)] pub struct EvalResult { x: CXEvalResult, } impl EvalResult { /// Evaluate `cursor` and return the result. pub fn new(cursor: Cursor) -> Option<Self> { if !clang_Cursor_Evaluate::is_loaded() { return None; } // Clang has an internal assertion we can trigger if we try to evaluate // a cursor containing a variadic template type reference. Triggering // the assertion aborts the process, and we don't want that. Clang // *also* doesn't expose any API for finding variadic vs non-variadic // template type references, let alone whether a type referenced is a // template type, instead they seem to show up as type references to an // unexposed type. Our solution is to just flat out ban all // `CXType_Unexposed` from evaluation. let mut found_cant_eval = false; cursor.visit(|c| if c.kind() == CXCursor_TypeRef && c.cur_type().kind() == CXType_Unexposed { found_cant_eval = true; CXChildVisit_Break } else { CXChildVisit_Recurse }); if found_cant_eval { return None; } Some(EvalResult { x: unsafe { clang_Cursor_Evaluate(cursor.x) }, }) } fn kind(&self) -> CXEvalResultKind { unsafe { clang_EvalResult_getKind(self.x) } } /// Try to get back the result as a double. pub fn as_double(&self) -> Option<f64> { match self.kind() { CXEval_Float => { Some(unsafe { clang_EvalResult_getAsDouble(self.x) } as f64) } _ => None, } } /// Try to get back the result as an integer. pub fn as_int(&self) -> Option<i64> { if self.kind() != CXEval_Int { return None; } if !clang_EvalResult_isUnsignedInt::is_loaded() { // FIXME(emilio): There's no way to detect underflow here, and clang // will just happily give us a value. return Some(unsafe { clang_EvalResult_getAsInt(self.x) } as i64) } if unsafe { clang_EvalResult_isUnsignedInt(self.x) } != 0 { let value = unsafe { clang_EvalResult_getAsUnsigned(self.x) }; if value > i64::max_value() as c_ulonglong { return None; } return Some(value as i64) } let value = unsafe { clang_EvalResult_getAsLongLong(self.x) }; if value > i64::max_value() as c_longlong { return None; } if value < i64::min_value() as c_longlong { return None; } Some(value as i64) } /// Evaluates the expression as a literal string, that may or may not be /// valid utf-8. pub fn as_literal_string(&self) -> Option<Vec<u8>> { match self.kind() { CXEval_StrLiteral => { let ret = unsafe { CStr::from_ptr(clang_EvalResult_getAsStr(self.x)) }; Some(ret.to_bytes().to_vec()) } _ => None, } } } impl Drop for EvalResult { fn drop(&mut self) { unsafe { clang_EvalResult_dispose(self.x) }; } } /// Target information obtained from libclang. #[derive(Debug)] pub struct TargetInfo { /// The target triple. pub triple: String, /// The width of the pointer _in bits_. pub pointer_width: usize, } impl TargetInfo { /// Tries to obtain target information from libclang. pub fn new(tu: &TranslationUnit) -> Option<Self> { if !clang_getTranslationUnitTargetInfo::is_loaded() { return None; } let triple; let pointer_width; unsafe { let ti = clang_getTranslationUnitTargetInfo(tu.x); triple = cxstring_into_string(clang_TargetInfo_getTriple(ti)); pointer_width = clang_TargetInfo_getPointerWidth(ti); clang_TargetInfo_dispose(ti); } assert!(pointer_width > 0); assert_eq!(pointer_width % 8, 0); Some(TargetInfo { triple, pointer_width: pointer_width as usize, }) } }
30.399038
90
0.544327
90aa1f0856324b2ef751a29376fcfa1b81babf32
12,305
#[doc = "Register `CONFIG[%s]` reader"] pub struct R(crate::R<CONFIG_SPEC>); impl core::ops::Deref for R { type Target = crate::R<CONFIG_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<CONFIG_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<CONFIG_SPEC>) -> Self { R(reader) } } #[doc = "Register `CONFIG[%s]` writer"] pub struct W(crate::W<CONFIG_SPEC>); impl core::ops::Deref for W { type Target = crate::W<CONFIG_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for W { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<crate::W<CONFIG_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<CONFIG_SPEC>) -> Self { W(writer) } } #[doc = "Mode\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum MODE_A { #[doc = "0: Disabled."] DISABLED = 0, #[doc = "1: Channel configure in event mode."] EVENT = 1, #[doc = "3: Channel configure in task mode."] TASK = 3, } impl From<MODE_A> for u8 { #[inline(always)] fn from(variant: MODE_A) -> Self { variant as _ } } #[doc = "Field `MODE` reader - Mode"] pub struct MODE_R(crate::FieldReader<u8, MODE_A>); impl MODE_R { pub(crate) fn new(bits: u8) -> Self { MODE_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> Option<MODE_A> { match self.bits { 0 => Some(MODE_A::DISABLED), 1 => Some(MODE_A::EVENT), 3 => Some(MODE_A::TASK), _ => None, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { **self == MODE_A::DISABLED } #[doc = "Checks if the value of the field is `EVENT`"] #[inline(always)] pub fn is_event(&self) -> bool { **self == MODE_A::EVENT } #[doc = "Checks if the value of the field is `TASK`"] #[inline(always)] pub fn is_task(&self) -> bool { **self == MODE_A::TASK } } impl core::ops::Deref for MODE_R { type Target = crate::FieldReader<u8, MODE_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `MODE` writer - Mode"] pub struct MODE_W<'a> { w: &'a mut W, } impl<'a> MODE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MODE_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "Disabled."] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(MODE_A::DISABLED) } #[doc = "Channel configure in event mode."] #[inline(always)] pub fn event(self) -> &'a mut W { self.variant(MODE_A::EVENT) } #[doc = "Channel configure in task mode."] #[inline(always)] pub fn task(self) -> &'a mut W { self.variant(MODE_A::TASK) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x03) | (value as u32 & 0x03); self.w } } #[doc = "Field `PSEL` reader - Pin select."] pub struct PSEL_R(crate::FieldReader<u8, u8>); impl PSEL_R { pub(crate) fn new(bits: u8) -> Self { PSEL_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for PSEL_R { type Target = crate::FieldReader<u8, u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `PSEL` writer - Pin select."] pub struct PSEL_W<'a> { w: &'a mut W, } impl<'a> PSEL_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 & !(0x1f << 8)) | ((value as u32 & 0x1f) << 8); self.w } } #[doc = "Effects on output when in Task mode, or events on input that generates an event.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum POLARITY_A { #[doc = "0: No task or event."] NONE = 0, #[doc = "1: Low to high."] LOTOHI = 1, #[doc = "2: High to low."] HITOLO = 2, #[doc = "3: Toggle."] TOGGLE = 3, } impl From<POLARITY_A> for u8 { #[inline(always)] fn from(variant: POLARITY_A) -> Self { variant as _ } } #[doc = "Field `POLARITY` reader - Effects on output when in Task mode, or events on input that generates an event."] pub struct POLARITY_R(crate::FieldReader<u8, POLARITY_A>); impl POLARITY_R { pub(crate) fn new(bits: u8) -> Self { POLARITY_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> POLARITY_A { match self.bits { 0 => POLARITY_A::NONE, 1 => POLARITY_A::LOTOHI, 2 => POLARITY_A::HITOLO, 3 => POLARITY_A::TOGGLE, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `NONE`"] #[inline(always)] pub fn is_none(&self) -> bool { **self == POLARITY_A::NONE } #[doc = "Checks if the value of the field is `LOTOHI`"] #[inline(always)] pub fn is_lo_to_hi(&self) -> bool { **self == POLARITY_A::LOTOHI } #[doc = "Checks if the value of the field is `HITOLO`"] #[inline(always)] pub fn is_hi_to_lo(&self) -> bool { **self == POLARITY_A::HITOLO } #[doc = "Checks if the value of the field is `TOGGLE`"] #[inline(always)] pub fn is_toggle(&self) -> bool { **self == POLARITY_A::TOGGLE } } impl core::ops::Deref for POLARITY_R { type Target = crate::FieldReader<u8, POLARITY_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `POLARITY` writer - Effects on output when in Task mode, or events on input that generates an event."] pub struct POLARITY_W<'a> { w: &'a mut W, } impl<'a> POLARITY_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: POLARITY_A) -> &'a mut W { self.bits(variant.into()) } #[doc = "No task or event."] #[inline(always)] pub fn none(self) -> &'a mut W { self.variant(POLARITY_A::NONE) } #[doc = "Low to high."] #[inline(always)] pub fn lo_to_hi(self) -> &'a mut W { self.variant(POLARITY_A::LOTOHI) } #[doc = "High to low."] #[inline(always)] pub fn hi_to_lo(self) -> &'a mut W { self.variant(POLARITY_A::HITOLO) } #[doc = "Toggle."] #[inline(always)] pub fn toggle(self) -> &'a mut W { self.variant(POLARITY_A::TOGGLE) } #[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 << 16)) | ((value as u32 & 0x03) << 16); self.w } } #[doc = "Initial value of the output when the GPIOTE channel is configured as a Task.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum OUTINIT_A { #[doc = "0: Initial low output when in task mode."] LOW = 0, #[doc = "1: Initial high output when in task mode."] HIGH = 1, } impl From<OUTINIT_A> for bool { #[inline(always)] fn from(variant: OUTINIT_A) -> Self { variant as u8 != 0 } } #[doc = "Field `OUTINIT` reader - Initial value of the output when the GPIOTE channel is configured as a Task."] pub struct OUTINIT_R(crate::FieldReader<bool, OUTINIT_A>); impl OUTINIT_R { pub(crate) fn new(bits: bool) -> Self { OUTINIT_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> OUTINIT_A { match self.bits { false => OUTINIT_A::LOW, true => OUTINIT_A::HIGH, } } #[doc = "Checks if the value of the field is `LOW`"] #[inline(always)] pub fn is_low(&self) -> bool { **self == OUTINIT_A::LOW } #[doc = "Checks if the value of the field is `HIGH`"] #[inline(always)] pub fn is_high(&self) -> bool { **self == OUTINIT_A::HIGH } } impl core::ops::Deref for OUTINIT_R { type Target = crate::FieldReader<bool, OUTINIT_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `OUTINIT` writer - Initial value of the output when the GPIOTE channel is configured as a Task."] pub struct OUTINIT_W<'a> { w: &'a mut W, } impl<'a> OUTINIT_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: OUTINIT_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Initial low output when in task mode."] #[inline(always)] pub fn low(self) -> &'a mut W { self.variant(OUTINIT_A::LOW) } #[doc = "Initial high output when in task mode."] #[inline(always)] pub fn high(self) -> &'a mut W { self.variant(OUTINIT_A::HIGH) } #[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 } } impl R { #[doc = "Bits 0:1 - Mode"] #[inline(always)] pub fn mode(&self) -> MODE_R { MODE_R::new((self.bits & 0x03) as u8) } #[doc = "Bits 8:12 - Pin select."] #[inline(always)] pub fn psel(&self) -> PSEL_R { PSEL_R::new(((self.bits >> 8) & 0x1f) as u8) } #[doc = "Bits 16:17 - Effects on output when in Task mode, or events on input that generates an event."] #[inline(always)] pub fn polarity(&self) -> POLARITY_R { POLARITY_R::new(((self.bits >> 16) & 0x03) as u8) } #[doc = "Bit 20 - Initial value of the output when the GPIOTE channel is configured as a Task."] #[inline(always)] pub fn outinit(&self) -> OUTINIT_R { OUTINIT_R::new(((self.bits >> 20) & 0x01) != 0) } } impl W { #[doc = "Bits 0:1 - Mode"] #[inline(always)] pub fn mode(&mut self) -> MODE_W { MODE_W { w: self } } #[doc = "Bits 8:12 - Pin select."] #[inline(always)] pub fn psel(&mut self) -> PSEL_W { PSEL_W { w: self } } #[doc = "Bits 16:17 - Effects on output when in Task mode, or events on input that generates an event."] #[inline(always)] pub fn polarity(&mut self) -> POLARITY_W { POLARITY_W { w: self } } #[doc = "Bit 20 - Initial value of the output when the GPIOTE channel is configured as a Task."] #[inline(always)] pub fn outinit(&mut self) -> OUTINIT_W { OUTINIT_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.0.bits(bits); self } } #[doc = "Channel configuration registers.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [config](index.html) module"] pub struct CONFIG_SPEC; impl crate::RegisterSpec for CONFIG_SPEC { type Ux = u32; } #[doc = "`read()` method returns [config::R](R) reader structure"] impl crate::Readable for CONFIG_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [config::W](W) writer structure"] impl crate::Writable for CONFIG_SPEC { type Writer = W; } #[doc = "`reset()` method sets CONFIG[%s] to value 0"] impl crate::Resettable for CONFIG_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
30.307882
419
0.569037
914b64aec365e2034e665b2ca45954a9fea2ae82
1,485
// Copyright 2022 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::pin::Pin; use std::task::Poll; use pin_project::pin_project; use crate::Reader; #[pin_project] pub struct CallbackReader<F: FnMut(usize)> { #[pin] inner: Reader, f: F, } impl<F> CallbackReader<F> where F: FnMut(usize) { /// # TODO /// /// Mark as dead_code for now, we will use it sooner while implement streams support. #[allow(dead_code)] pub fn new(r: Reader, f: F) -> Self { CallbackReader { inner: r, f } } } impl<F> futures::AsyncRead for CallbackReader<F> where F: FnMut(usize) { fn poll_read( mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>, buf: &mut [u8], ) -> Poll<std::io::Result<usize>> { let this = self.as_mut().project(); let r = this.inner.poll_read(cx, buf); if let Poll::Ready(Ok(len)) = r { (self.f)(len); }; r } }
25.169492
89
0.632997
9b5bbde383ce412b0f6630de94fdc2bd01f3d374
14,085
//! Utilities for building HTTP endpoints in a library-agnostic manner pub mod graphiql; pub mod playground; use serde::{ de::Deserialize, ser::{self, Serialize, SerializeMap}, }; use serde_derive::{Deserialize, Serialize}; use crate::{ ast::InputValue, executor::{ExecutionError, ValuesStream}, value::{DefaultScalarValue, ScalarValue}, FieldError, GraphQLError, GraphQLSubscriptionType, GraphQLType, GraphQLTypeAsync, RootNode, Value, Variables, }; /// The expected structure of the decoded JSON document for either POST or GET requests. /// /// For POST, you can use Serde to deserialize the incoming JSON data directly /// into this struct - it derives Deserialize for exactly this reason. /// /// For GET, you will need to parse the query string and extract "query", /// "operationName", and "variables" manually. #[derive(Deserialize, Clone, Serialize, PartialEq, Debug)] pub struct GraphQLRequest<S = DefaultScalarValue> where S: ScalarValue, { query: String, #[serde(rename = "operationName")] operation_name: Option<String>, #[serde(bound(deserialize = "InputValue<S>: Deserialize<'de> + Serialize"))] variables: Option<InputValue<S>>, } impl<S> GraphQLRequest<S> where S: ScalarValue, { /// Returns the `operation_name` associated with this request. pub fn operation_name(&self) -> Option<&str> { self.operation_name.as_ref().map(|oper_name| &**oper_name) } fn variables(&self) -> Variables<S> { self.variables .as_ref() .and_then(|iv| { iv.to_object_value().map(|o| { o.into_iter() .map(|(k, v)| (k.to_owned(), v.clone())) .collect() }) }) .unwrap_or_default() } /// Construct a new GraphQL request from parts pub fn new( query: String, operation_name: Option<String>, variables: Option<InputValue<S>>, ) -> Self { GraphQLRequest { query, operation_name, variables, } } /// Execute a GraphQL request synchronously using the specified schema and context /// /// This is a simple wrapper around the `execute_sync` function exposed at the /// top level of this crate. pub fn execute_sync<'a, CtxT, QueryT, MutationT, SubscriptionT>( &'a self, root_node: &'a RootNode<QueryT, MutationT, SubscriptionT, S>, context: &CtxT, ) -> GraphQLResponse<'a, S> where S: ScalarValue, QueryT: GraphQLType<S, Context = CtxT>, MutationT: GraphQLType<S, Context = CtxT>, SubscriptionT: GraphQLType<S, Context = CtxT>, { GraphQLResponse(crate::execute_sync( &self.query, self.operation_name(), root_node, &self.variables(), context, )) } /// Execute a GraphQL request using the specified schema and context /// /// This is a simple wrapper around the `execute` function exposed at the /// top level of this crate. pub async fn execute<'a, CtxT, QueryT, MutationT, SubscriptionT>( &'a self, root_node: &'a RootNode<'a, QueryT, MutationT, SubscriptionT, S>, context: &'a CtxT, ) -> GraphQLResponse<'a, S> where S: ScalarValue + Send + Sync, QueryT: crate::GraphQLTypeAsync<S, Context = CtxT> + Send + Sync, QueryT::TypeInfo: Send + Sync, MutationT: crate::GraphQLTypeAsync<S, Context = CtxT> + Send + Sync, MutationT::TypeInfo: Send + Sync, SubscriptionT: GraphQLType<S, Context = CtxT> + Send + Sync, SubscriptionT::TypeInfo: Send + Sync, CtxT: Send + Sync, { let op = self.operation_name(); let vars = &self.variables(); let res = crate::execute(&self.query, op, root_node, vars, context).await; GraphQLResponse(res) } } /// Resolve a GraphQL subscription into `Value<ValuesStream<S>` using the /// specified schema and context. /// This is a wrapper around the `resolve_into_stream` function exposed at the top /// level of this crate. pub async fn resolve_into_stream<'req, 'rn, 'ctx, 'a, CtxT, QueryT, MutationT, SubscriptionT, S>( req: &'req GraphQLRequest<S>, root_node: &'rn RootNode<'a, QueryT, MutationT, SubscriptionT, S>, context: &'ctx CtxT, ) -> Result<(Value<ValuesStream<'a, S>>, Vec<ExecutionError<S>>), GraphQLError<'a>> where 'req: 'a, 'rn: 'a, 'ctx: 'a, S: ScalarValue + Send + Sync + 'static, QueryT: GraphQLTypeAsync<S, Context = CtxT> + Send + Sync, QueryT::TypeInfo: Send + Sync, MutationT: GraphQLTypeAsync<S, Context = CtxT> + Send + Sync, MutationT::TypeInfo: Send + Sync, SubscriptionT: GraphQLSubscriptionType<S, Context = CtxT> + Send + Sync, SubscriptionT::TypeInfo: Send + Sync, CtxT: Send + Sync, { let op = req.operation_name(); let vars = req.variables(); crate::resolve_into_stream(&req.query, op, root_node, &vars, context).await } /// Simple wrapper around the result from executing a GraphQL query /// /// This struct implements Serialize, so you can simply serialize this /// to JSON and send it over the wire. Use the `is_ok` method to determine /// whether to send a 200 or 400 HTTP status code. #[derive(Debug)] pub struct GraphQLResponse<'a, S = DefaultScalarValue>( Result<(Value<S>, Vec<ExecutionError<S>>), GraphQLError<'a>>, ); impl<'a, S> GraphQLResponse<'a, S> where S: ScalarValue, { /// Constructs new `GraphQLResponse` using the given result pub fn from_result(r: Result<(Value<S>, Vec<ExecutionError<S>>), GraphQLError<'a>>) -> Self { Self(r) } /// Constructs an error response outside of the normal execution flow pub fn error(error: FieldError<S>) -> Self { GraphQLResponse(Ok((Value::null(), vec![ExecutionError::at_origin(error)]))) } /// Was the request successful or not? /// /// Note that there still might be errors in the response even though it's /// considered OK. This is by design in GraphQL. pub fn is_ok(&self) -> bool { self.0.is_ok() } } impl<'a, T> Serialize for GraphQLResponse<'a, T> where T: Serialize + ScalarValue, Value<T>: Serialize, ExecutionError<T>: Serialize, GraphQLError<'a>: Serialize, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer, { match self.0 { Ok((ref res, ref err)) => { let mut map = serializer.serialize_map(None)?; map.serialize_key("data")?; map.serialize_value(res)?; if !err.is_empty() { map.serialize_key("errors")?; map.serialize_value(err)?; } map.end() } Err(ref err) => { let mut map = serializer.serialize_map(Some(1))?; map.serialize_key("errors")?; map.serialize_value(err)?; map.end() } } } } #[cfg(any(test, feature = "expose-test-schema"))] #[allow(missing_docs)] pub mod tests { use serde_json::{self, Value as Json}; /// Normalized response content we expect to get back from /// the http framework integration we are testing. #[derive(Debug)] pub struct TestResponse { pub status_code: i32, pub body: Option<String>, pub content_type: String, } /// Normalized way to make requests to the http framework /// integration we are testing. pub trait HTTPIntegration { fn get(&self, url: &str) -> TestResponse; fn post(&self, url: &str, body: &str) -> TestResponse; } #[allow(missing_docs)] pub fn run_http_test_suite<T: HTTPIntegration>(integration: &T) { println!("Running HTTP Test suite for integration"); println!(" - test_simple_get"); test_simple_get(integration); println!(" - test_encoded_get"); test_encoded_get(integration); println!(" - test_get_with_variables"); test_get_with_variables(integration); println!(" - test_simple_post"); test_simple_post(integration); println!(" - test_batched_post"); test_batched_post(integration); println!(" - test_invalid_json"); test_invalid_json(integration); println!(" - test_invalid_field"); test_invalid_field(integration); println!(" - test_duplicate_keys"); test_duplicate_keys(integration); } fn unwrap_json_response(response: &TestResponse) -> Json { serde_json::from_str::<Json>( response .body .as_ref() .expect("No data returned from request"), ) .expect("Could not parse JSON object") } fn test_simple_get<T: HTTPIntegration>(integration: &T) { // {hero{name}} let response = integration.get("/?query=%7Bhero%7Bname%7D%7D"); assert_eq!(response.status_code, 200); assert_eq!(response.content_type.as_str(), "application/json"); assert_eq!( unwrap_json_response(&response), serde_json::from_str::<Json>(r#"{"data": {"hero": {"name": "R2-D2"}}}"#) .expect("Invalid JSON constant in test") ); } fn test_encoded_get<T: HTTPIntegration>(integration: &T) { // query { human(id: "1000") { id, name, appearsIn, homePlanet } } let response = integration.get( "/?query=query%20%7B%20human(id%3A%20%221000%22)%20%7B%20id%2C%20name%2C%20appearsIn%2C%20homePlanet%20%7D%20%7D"); assert_eq!(response.status_code, 200); assert_eq!(response.content_type.as_str(), "application/json"); assert_eq!( unwrap_json_response(&response), serde_json::from_str::<Json>( r#"{ "data": { "human": { "appearsIn": [ "NEW_HOPE", "EMPIRE", "JEDI" ], "homePlanet": "Tatooine", "name": "Luke Skywalker", "id": "1000" } } }"# ) .expect("Invalid JSON constant in test") ); } fn test_get_with_variables<T: HTTPIntegration>(integration: &T) { // query($id: String!) { human(id: $id) { id, name, appearsIn, homePlanet } } // with variables = { "id": "1000" } let response = integration.get( "/?query=query(%24id%3A%20String!)%20%7B%20human(id%3A%20%24id)%20%7B%20id%2C%20name%2C%20appearsIn%2C%20homePlanet%20%7D%20%7D&variables=%7B%20%22id%22%3A%20%221000%22%20%7D"); assert_eq!(response.status_code, 200); assert_eq!(response.content_type, "application/json"); assert_eq!( unwrap_json_response(&response), serde_json::from_str::<Json>( r#"{ "data": { "human": { "appearsIn": [ "NEW_HOPE", "EMPIRE", "JEDI" ], "homePlanet": "Tatooine", "name": "Luke Skywalker", "id": "1000" } } }"# ) .expect("Invalid JSON constant in test") ); } fn test_simple_post<T: HTTPIntegration>(integration: &T) { let response = integration.post("/", r#"{"query": "{hero{name}}"}"#); assert_eq!(response.status_code, 200); assert_eq!(response.content_type, "application/json"); assert_eq!( unwrap_json_response(&response), serde_json::from_str::<Json>(r#"{"data": {"hero": {"name": "R2-D2"}}}"#) .expect("Invalid JSON constant in test") ); } fn test_batched_post<T: HTTPIntegration>(integration: &T) { let response = integration.post( "/", r#"[{"query": "{hero{name}}"}, {"query": "{hero{name}}"}]"#, ); assert_eq!(response.status_code, 200); assert_eq!(response.content_type, "application/json"); assert_eq!( unwrap_json_response(&response), serde_json::from_str::<Json>( r#"[{"data": {"hero": {"name": "R2-D2"}}}, {"data": {"hero": {"name": "R2-D2"}}}]"# ) .expect("Invalid JSON constant in test") ); } fn test_invalid_json<T: HTTPIntegration>(integration: &T) { let response = integration.get("/?query=blah"); assert_eq!(response.status_code, 400); let response = integration.post("/", r#"blah"#); assert_eq!(response.status_code, 400); } fn test_invalid_field<T: HTTPIntegration>(integration: &T) { // {hero{blah}} let response = integration.get("/?query=%7Bhero%7Bblah%7D%7D"); assert_eq!(response.status_code, 400); let response = integration.post("/", r#"{"query": "{hero{blah}}"}"#); assert_eq!(response.status_code, 400); } fn test_duplicate_keys<T: HTTPIntegration>(integration: &T) { // {hero{name}} let response = integration.get("/?query=%7B%22query%22%3A%20%22%7Bhero%7Bname%7D%7D%22%2C%20%22query%22%3A%20%22%7Bhero%7Bname%7D%7D%22%7D"); assert_eq!(response.status_code, 400); let response = integration.post( "/", r#" {"query": "{hero{name}}", "query": "{hero{name}}"} "#, ); assert_eq!(response.status_code, 400); } }
34.021739
189
0.562939
9c89daf09fb1435b6b6bc673c22cbf5bfe610dce
1,431
use std::collections::HashMap; // num_iters should be the total number of iterations, including the seed iterations fn memory_game(num_iters: usize, seed: &Vec<usize>) { let mut prev_num: usize = 0; // this initial value will never be used let mut occurrences: HashMap<usize, usize> = HashMap::new(); // start at 1 here because for the most part we'll be one-based // only zero-based thing here is indices of seed for i in 1..=num_iters { // first case if i == 0 { occurrences.insert(seed[i - 1], i); prev_num = seed[i - 1] } else { let curr_num = if (i as usize) <= seed.len() { seed[i - 1] } else { prev_num }; let next_num = occurrences .get(&curr_num) .and_then(|last_occurrence| Some(i - last_occurrence)) .unwrap_or(0); occurrences.insert(curr_num, i); if i == num_iters { // last number of the game println!("{}", prev_num); } else { prev_num = next_num; } } } } fn main() { // 0,6,1,7,2,19,20 let input: Vec<usize> = "0,6,1,7,2,19,20" .split(",") .map(|num| num.parse().unwrap()) .collect(); // memory_game(2020, &input); // part 1 memory_game(30000000, &input); // part 2 }
31.108696
84
0.51153
dd6f30580af15587148b51ffd8ddcc0765b14666
361
use cradle::*; fn main() { let StdoutTrimmed(git_version) = cmd!(%"git --version"); eprintln!("git version: {}", git_version); let (StdoutTrimmed(git_user), Exit(status)) = cmd!(%"git config --get user.name"); if status.success() { eprintln!("git user: {}", git_user); } else { eprintln!("git user not configured"); } }
27.769231
86
0.584488
485616869dd904fe787a2c7ebc62bd40af73cd66
3,882
// Copyright 2018 sqlparser-rs contributors. All rights reserved. // Copyright Materialize, Inc. and contributors. All rights reserved. // // This file is derived from the sqlparser-rs project, available at // https://github.com/andygrove/sqlparser-rs. It was incorporated // directly into Materialize on December 21, 2019. // // 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 in the LICENSE file at the // root of this repository, or online at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use tempfile::NamedTempFile; use coord::catalog::{Catalog, CatalogItem, Table}; use coord::session::Session; use expr::GlobalId; use ore::now::NOW_ZERO; use repr::RelationDesc; use sql::ast::{Expr, Statement}; use sql::names::{DatabaseSpecifier, FullName}; use sql::plan::{resolve_names, PlanContext, QueryContext, QueryLifetime, StatementContext}; // This morally tests the name resolution stuff, but we need access to a // catalog. #[tokio::test] async fn datadriven() { datadriven::walk_async("tests/testdata", |mut f| async { let catalog_file = NamedTempFile::new().unwrap(); let mut catalog = Catalog::open_debug(catalog_file.path(), NOW_ZERO.clone()) .await .unwrap(); let mut id: u32 = 1; f.run(|test_case| -> String { match test_case.directive.as_str() { "add-table" => { let _ = catalog.insert_item( GlobalId::User(id.into()), id, FullName { database: DatabaseSpecifier::Name("materialize".into()), schema: "public".into(), item: test_case.input.trim_end().to_string(), }, CatalogItem::Table(Table { create_sql: "TODO".to_string(), desc: RelationDesc::empty(), defaults: vec![Expr::null(); 0], conn_id: None, depends_on: vec![], persist_name: None, }), ); id += 1; format!("{}\n", GlobalId::User((id - 1).into())) } "resolve" => { // let catalog = catalog.for_system_session(); let sess = Session::dummy(); let catalog = catalog.for_session(&sess); let parsed = sql::parse::parse(&test_case.input).unwrap(); let pcx = &PlanContext::zero(); let scx = StatementContext::new(Some(pcx), &catalog); let mut qcx = QueryContext::root(&scx, QueryLifetime::OneShot(scx.pcx().unwrap())); let q = parsed[0].clone(); let q = match q { Statement::Select(s) => s.query, _ => unreachable!(), }; let resolved = resolve_names(&mut qcx, q); match resolved { Ok(q) => format!("{}\n", q), Err(e) => format!("error: {}\n", e), } } dir => panic!("unhandled directive {}", dir), } }); f }) .await; }
41.297872
93
0.518032
d5e48893d36320c091b0f843e0f1af7bd11395bd
1,979
//! config for staking //! carries variables that the stake program cares about #[deprecated( since = "1.8.0", note = "Please use `solana_sdk::stake::config` or `solana_program::stake::config` instead" )] pub use solana_sdk::stake::config::*; use { bincode::deserialize, solana_config_program::{create_config_account, get_config_data}, solana_sdk::{ account::{AccountSharedData, ReadableAccount, WritableAccount}, genesis_config::GenesisConfig, instruction::InstructionError, keyed_account::KeyedAccount, stake::config::{self, Config}, }, }; pub fn from<T: ReadableAccount>(account: &T) -> Option<Config> { get_config_data(account.data()) .ok() .and_then(|data| deserialize(data).ok()) } pub fn from_keyed_account(account: &KeyedAccount) -> Result<Config, InstructionError> { if !config::check_id(account.unsigned_key()) { return Err(InstructionError::InvalidArgument); } from(&*account.try_account_ref()?).ok_or(InstructionError::InvalidArgument) } pub fn create_account(lamports: u64, config: &Config) -> AccountSharedData { create_config_account(vec![], config, lamports) } pub fn add_genesis_account(genesis_config: &mut GenesisConfig) -> u64 { let mut account = create_config_account(vec![], &Config::default(), 0); let lamports = genesis_config.rent.minimum_balance(account.data().len()); account.set_lamports(lamports.max(1)); genesis_config.add_account(config::id(), account); lamports } #[cfg(test)] mod tests { use {super::*, solana_sdk::pubkey::Pubkey, std::cell::RefCell}; #[test] fn test() { let account = RefCell::new(create_account(0, &Config::default())); assert_eq!(from(&account.borrow()), Some(Config::default())); assert_eq!( from_keyed_account(&KeyedAccount::new(&Pubkey::default(), false, &account)), Err(InstructionError::InvalidArgument) ); } }
31.919355
94
0.671046
eb6f2bc39fc17d1e3ed76b8caea546c82bae33fb
60,761
//! This module takes care of lexing python source text. //! //! This means source code is translated into separate tokens. pub use super::token::Tok; use crate::ast::Location; use crate::error::{LexicalError, LexicalErrorType}; use num_bigint::BigInt; use num_traits::identities::Zero; use num_traits::Num; use std::char; use std::cmp::Ordering; use std::str::FromStr; use unic_emoji_char::is_emoji_presentation; use unic_ucd_ident::{is_xid_continue, is_xid_start}; #[derive(Clone, Copy, PartialEq, Debug, Default)] struct IndentationLevel { tabs: usize, spaces: usize, } impl IndentationLevel { fn compare_strict( &self, other: &IndentationLevel, location: Location, ) -> Result<Ordering, LexicalError> { // We only know for sure that we're smaller or bigger if tabs // and spaces both differ in the same direction. Otherwise we're // dependent on the size of tabs. match self.tabs.cmp(&other.tabs) { Ordering::Less => { if self.spaces <= other.spaces { Ok(Ordering::Less) } else { Err(LexicalError { location, error: LexicalErrorType::TabError, }) } } Ordering::Greater => { if self.spaces >= other.spaces { Ok(Ordering::Greater) } else { Err(LexicalError { location, error: LexicalErrorType::TabError, }) } } Ordering::Equal => Ok(self.spaces.cmp(&other.spaces)), } } } pub struct Lexer<T: Iterator<Item = char>> { chars: T, at_begin_of_line: bool, nesting: usize, // Amount of parenthesis indentation_stack: Vec<IndentationLevel>, pending: Vec<Spanned>, chr0: Option<char>, chr1: Option<char>, chr2: Option<char>, location: Location, } pub static KEYWORDS: phf::Map<&'static str, Tok> = phf::phf_map! { // Alphabetical keywords: "..." => Tok::Ellipsis, "False" => Tok::False, "None" => Tok::None, "True" => Tok::True, "and" => Tok::And, "as" => Tok::As, "assert" => Tok::Assert, "async" => Tok::Async, "await" => Tok::Await, "break" => Tok::Break, "class" => Tok::Class, "continue" => Tok::Continue, "def" => Tok::Def, "del" => Tok::Del, "elif" => Tok::Elif, "else" => Tok::Else, "except" => Tok::Except, "finally" => Tok::Finally, "for" => Tok::For, "from" => Tok::From, "global" => Tok::Global, "if" => Tok::If, "import" => Tok::Import, "in" => Tok::In, "is" => Tok::Is, "lambda" => Tok::Lambda, "nonlocal" => Tok::Nonlocal, "not" => Tok::Not, "or" => Tok::Or, "pass" => Tok::Pass, "raise" => Tok::Raise, "return" => Tok::Return, "try" => Tok::Try, "while" => Tok::While, "with" => Tok::With, "yield" => Tok::Yield, }; pub type Spanned = (Location, Tok, Location); pub type LexResult = Result<Spanned, LexicalError>; #[inline] pub fn make_tokenizer(source: &str) -> impl Iterator<Item = LexResult> + '_ { make_tokenizer_located(source, Location::new(0, 0)) } pub fn make_tokenizer_located( source: &str, start_location: Location, ) -> impl Iterator<Item = LexResult> + '_ { let nlh = NewlineHandler::new(source.chars()); Lexer::new(nlh, start_location) } // The newline handler is an iterator which collapses different newline // types into \n always. pub struct NewlineHandler<T: Iterator<Item = char>> { source: T, chr0: Option<char>, chr1: Option<char>, } impl<T> NewlineHandler<T> where T: Iterator<Item = char>, { pub fn new(source: T) -> Self { let mut nlh = NewlineHandler { source, chr0: None, chr1: None, }; nlh.shift(); nlh.shift(); nlh } fn shift(&mut self) -> Option<char> { let result = self.chr0; self.chr0 = self.chr1; self.chr1 = self.source.next(); result } } impl<T> Iterator for NewlineHandler<T> where T: Iterator<Item = char>, { type Item = char; fn next(&mut self) -> Option<Self::Item> { // Collapse \r\n into \n loop { if self.chr0 == Some('\r') { if self.chr1 == Some('\n') { // Transform windows EOL into \n self.shift(); } else { // Transform MAC EOL into \n self.chr0 = Some('\n') } } else { break; } } self.shift() } } impl<T> Lexer<T> where T: Iterator<Item = char>, { pub fn new(input: T, start: Location) -> Self { let mut lxr = Lexer { chars: input, at_begin_of_line: true, nesting: 0, indentation_stack: vec![Default::default()], pending: Vec::new(), chr0: None, location: start, chr1: None, chr2: None, }; lxr.next_char(); lxr.next_char(); lxr.next_char(); // Start at top row (=1) left column (=1) lxr.location.reset(); lxr } // Lexer helper functions: fn lex_identifier(&mut self) -> LexResult { let mut name = String::new(); let start_pos = self.get_pos(); // Detect potential string like rb'' b'' f'' u'' r'' let mut saw_b = false; let mut saw_r = false; let mut saw_u = false; let mut saw_f = false; loop { // Detect r"", f"", b"" and u"" if !(saw_b || saw_u || saw_f) && matches!(self.chr0, Some('b') | Some('B')) { saw_b = true; } else if !(saw_b || saw_r || saw_u || saw_f) && matches!(self.chr0, Some('u') | Some('U')) { saw_u = true; } else if !(saw_r || saw_u) && (self.chr0 == Some('r') || self.chr0 == Some('R')) { saw_r = true; } else if !(saw_b || saw_u || saw_f) && (self.chr0 == Some('f') || self.chr0 == Some('F')) { saw_f = true; } else { break; } // Take up char into name: name.push(self.next_char().unwrap()); // Check if we have a string: if self.chr0 == Some('"') || self.chr0 == Some('\'') { return self.lex_string(saw_b, saw_r, saw_u, saw_f); } } while self.is_identifier_continuation() { name.push(self.next_char().unwrap()); } let end_pos = self.get_pos(); if let Some(tok) = KEYWORDS.get(name.as_str()) { Ok((start_pos, tok.clone(), end_pos)) } else { Ok((start_pos, Tok::Name { name }, end_pos)) } } /// Numeric lexing. The feast can start! fn lex_number(&mut self) -> LexResult { let start_pos = self.get_pos(); if self.chr0 == Some('0') { if self.chr1 == Some('x') || self.chr1 == Some('X') { // Hex! self.next_char(); self.next_char(); self.lex_number_radix(start_pos, 16) } else if self.chr1 == Some('o') || self.chr1 == Some('O') { // Octal style! self.next_char(); self.next_char(); self.lex_number_radix(start_pos, 8) } else if self.chr1 == Some('b') || self.chr1 == Some('B') { // Binary! self.next_char(); self.next_char(); self.lex_number_radix(start_pos, 2) } else { self.lex_normal_number() } } else { self.lex_normal_number() } } /// Lex a hex/octal/decimal/binary number without a decimal point. fn lex_number_radix(&mut self, start_pos: Location, radix: u32) -> LexResult { let value_text = self.radix_run(radix); let end_pos = self.get_pos(); let value = BigInt::from_str_radix(&value_text, radix).map_err(|e| LexicalError { error: LexicalErrorType::OtherError(format!("{:?}", e)), location: start_pos, })?; Ok((start_pos, Tok::Int { value }, end_pos)) } /// Lex a normal number, that is, no octal, hex or binary number. fn lex_normal_number(&mut self) -> LexResult { let start_pos = self.get_pos(); let start_is_zero = self.chr0 == Some('0'); // Normal number: let mut value_text = self.radix_run(10); // If float: if self.chr0 == Some('.') || self.at_exponent() { // Take '.': if self.chr0 == Some('.') { if self.chr1 == Some('_') { return Err(LexicalError { error: LexicalErrorType::OtherError("Invalid Syntax".to_owned()), location: self.get_pos(), }); } value_text.push(self.next_char().unwrap()); value_text.push_str(&self.radix_run(10)); } // 1e6 for example: if self.chr0 == Some('e') || self.chr0 == Some('E') { value_text.push(self.next_char().unwrap().to_ascii_lowercase()); // Optional +/- if self.chr0 == Some('-') || self.chr0 == Some('+') { value_text.push(self.next_char().unwrap()); } value_text.push_str(&self.radix_run(10)); } let value = f64::from_str(&value_text).unwrap(); // Parse trailing 'j': if self.chr0 == Some('j') || self.chr0 == Some('J') { self.next_char(); let end_pos = self.get_pos(); Ok(( start_pos, Tok::Complex { real: 0.0, imag: value, }, end_pos, )) } else { let end_pos = self.get_pos(); Ok((start_pos, Tok::Float { value }, end_pos)) } } else { // Parse trailing 'j': if self.chr0 == Some('j') || self.chr0 == Some('J') { self.next_char(); let end_pos = self.get_pos(); let imag = f64::from_str(&value_text).unwrap(); Ok((start_pos, Tok::Complex { real: 0.0, imag }, end_pos)) } else { let end_pos = self.get_pos(); let value = value_text.parse::<BigInt>().unwrap(); if start_is_zero && !value.is_zero() { return Err(LexicalError { error: LexicalErrorType::OtherError("Invalid Token".to_owned()), location: self.get_pos(), }); } Ok((start_pos, Tok::Int { value }, end_pos)) } } } /// Consume a sequence of numbers with the given radix, /// the digits can be decorated with underscores /// like this: '1_2_3_4' == '1234' fn radix_run(&mut self, radix: u32) -> String { let mut value_text = String::new(); loop { if let Some(c) = self.take_number(radix) { value_text.push(c); } else if self.chr0 == Some('_') && Lexer::<T>::is_digit_of_radix(self.chr1, radix) { self.next_char(); } else { break; } } value_text } /// Consume a single character with the given radix. fn take_number(&mut self, radix: u32) -> Option<char> { let take_char = Lexer::<T>::is_digit_of_radix(self.chr0, radix); if take_char { Some(self.next_char().unwrap()) } else { None } } /// Test if a digit is of a certain radix. fn is_digit_of_radix(c: Option<char>, radix: u32) -> bool { match radix { 2 => matches!(c, Some('0'..='1')), 8 => matches!(c, Some('0'..='7')), 10 => matches!(c, Some('0'..='9')), 16 => matches!(c, Some('0'..='9') | Some('a'..='f') | Some('A'..='F')), other => unimplemented!("Radix not implemented: {}", other), } } /// Test if we face '[eE][-+]?[0-9]+' fn at_exponent(&self) -> bool { match self.chr0 { Some('e') | Some('E') => match self.chr1 { Some('+') | Some('-') => matches!(self.chr2, Some('0'..='9')), Some('0'..='9') => true, _ => false, }, _ => false, } } /// Skip everything until end of line fn lex_comment(&mut self) { self.next_char(); loop { match self.chr0 { Some('\n') => return, Some(_) => {} None => return, } self.next_char(); } } fn unicode_literal(&mut self, literal_number: usize) -> Result<char, LexicalError> { let mut p: u32 = 0u32; let unicode_error = LexicalError { error: LexicalErrorType::UnicodeError, location: self.get_pos(), }; for i in 1..=literal_number { match self.next_char() { Some(c) => match c.to_digit(16) { Some(d) => p += d << ((literal_number - i) * 4), None => return Err(unicode_error), }, None => return Err(unicode_error), } } match p { 0xD800..=0xDFFF => Ok(std::char::REPLACEMENT_CHARACTER), _ => std::char::from_u32(p).ok_or(unicode_error), } } fn parse_octet(&mut self, first: char) -> char { let mut octet_content = String::new(); octet_content.push(first); while octet_content.len() < 3 { if let Some('0'..='7') = self.chr0 { octet_content.push(self.next_char().unwrap()) } else { break; } } let value = u32::from_str_radix(&octet_content, 8).unwrap(); char::from_u32(value).unwrap() } fn parse_unicode_name(&mut self) -> Result<char, LexicalError> { let start_pos = self.get_pos(); match self.next_char() { Some('{') => {} _ => { return Err(LexicalError { error: LexicalErrorType::StringError, location: start_pos, }) } } let start_pos = self.get_pos(); let mut name = String::new(); loop { match self.next_char() { Some('}') => break, Some(c) => name.push(c), None => { return Err(LexicalError { error: LexicalErrorType::StringError, location: self.get_pos(), }) } } } unicode_names2::character(&name).ok_or(LexicalError { error: LexicalErrorType::UnicodeError, location: start_pos, }) } fn lex_string( &mut self, is_bytes: bool, is_raw: bool, _is_unicode: bool, is_fstring: bool, ) -> LexResult { let quote_char = self.next_char().unwrap(); let mut string_content = String::new(); let start_pos = self.get_pos(); // If the next two characters are also the quote character, then we have a triple-quoted // string; consume those two characters and ensure that we require a triple-quote to close let triple_quoted = if self.chr0 == Some(quote_char) && self.chr1 == Some(quote_char) { self.next_char(); self.next_char(); true } else { false }; loop { match self.next_char() { Some('\\') => { if self.chr0 == Some(quote_char) && !is_raw { string_content.push(quote_char); self.next_char(); } else if is_raw { string_content.push('\\'); if let Some(c) = self.next_char() { string_content.push(c) } else { return Err(LexicalError { error: LexicalErrorType::StringError, location: self.get_pos(), }); } } else { match self.next_char() { Some('\\') => { string_content.push('\\'); } Some('\'') => string_content.push('\''), Some('\"') => string_content.push('\"'), Some('\n') => { // Ignore Unix EOL character } Some('a') => string_content.push('\x07'), Some('b') => string_content.push('\x08'), Some('f') => string_content.push('\x0c'), Some('n') => { string_content.push('\n'); } Some('r') => string_content.push('\r'), Some('t') => { string_content.push('\t'); } Some('v') => string_content.push('\x0b'), Some(o @ '0'..='7') => string_content.push(self.parse_octet(o)), Some('x') => string_content.push(self.unicode_literal(2)?), Some('u') if !is_bytes => string_content.push(self.unicode_literal(4)?), Some('U') if !is_bytes => string_content.push(self.unicode_literal(8)?), Some('N') if !is_bytes => { string_content.push(self.parse_unicode_name()?) } Some(c) => { string_content.push('\\'); string_content.push(c); } None => { return Err(LexicalError { error: LexicalErrorType::StringError, location: self.get_pos(), }); } } } } Some(c) => { if c == quote_char { if triple_quoted { // Look ahead at the next two characters; if we have two more // quote_chars, it's the end of the string; consume the remaining // closing quotes and break the loop if self.chr0 == Some(quote_char) && self.chr1 == Some(quote_char) { self.next_char(); self.next_char(); break; } string_content.push(c); } else { break; } } else { if (c == '\n' && !triple_quoted) || (is_bytes && !c.is_ascii()) { return Err(LexicalError { error: LexicalErrorType::StringError, location: self.get_pos(), }); } string_content.push(c); } } None => { return Err(LexicalError { error: LexicalErrorType::StringError, location: self.get_pos(), }); } } } let end_pos = self.get_pos(); let tok = if is_bytes { Tok::Bytes { value: string_content.chars().map(|c| c as u8).collect(), } } else { Tok::String { value: string_content, is_fstring, } }; Ok((start_pos, tok, end_pos)) } fn is_identifier_start(&self, c: char) -> bool { c == '_' || is_xid_start(c) } fn is_identifier_continuation(&self) -> bool { if let Some(c) = self.chr0 { match c { '_' | '0'..='9' => true, c => is_xid_continue(c), } } else { false } } /// This is the main entry point. Call this function to retrieve the next token. /// This function is used by the iterator implementation. fn inner_next(&mut self) -> LexResult { // top loop, keep on processing, until we have something pending. while self.pending.is_empty() { // Detect indentation levels if self.at_begin_of_line { self.handle_indentations()?; } self.consume_normal()?; } Ok(self.pending.remove(0)) } /// Given we are at the start of a line, count the number of spaces and/or tabs until the first character. fn eat_indentation(&mut self) -> Result<IndentationLevel, LexicalError> { // Determine indentation: let mut spaces: usize = 0; let mut tabs: usize = 0; loop { match self.chr0 { Some(' ') => { /* if tabs != 0 { // Don't allow spaces after tabs as part of indentation. // This is technically stricter than python3 but spaces after // tabs is even more insane than mixing spaces and tabs. return Some(Err(LexicalError { error: LexicalErrorType::OtherError("Spaces not allowed as part of indentation after tabs".to_owned()), location: self.get_pos(), })); } */ self.next_char(); spaces += 1; } Some('\t') => { if spaces != 0 { // Don't allow tabs after spaces as part of indentation. // This is technically stricter than python3 but spaces before // tabs is even more insane than mixing spaces and tabs. return Err(LexicalError { error: LexicalErrorType::TabsAfterSpaces, location: self.get_pos(), }); } self.next_char(); tabs += 1; } Some('#') => { self.lex_comment(); spaces = 0; tabs = 0; } Some('\x0C') => { // Form feed character! // Reset indentation for the Emacs user. self.next_char(); spaces = 0; tabs = 0; } Some('\n') => { // Empty line! self.next_char(); spaces = 0; tabs = 0; } None => { spaces = 0; tabs = 0; break; } _ => { self.at_begin_of_line = false; break; } } } Ok(IndentationLevel { tabs, spaces }) } fn handle_indentations(&mut self) -> Result<(), LexicalError> { let indentation_level = self.eat_indentation()?; if self.nesting == 0 { // Determine indent or dedent: let current_indentation = self.indentation_stack.last().unwrap(); let ordering = indentation_level.compare_strict(current_indentation, self.get_pos())?; match ordering { Ordering::Equal => { // Same same } Ordering::Greater => { // New indentation level: self.indentation_stack.push(indentation_level); let tok_pos = self.get_pos(); self.emit((tok_pos, Tok::Indent, tok_pos)); } Ordering::Less => { // One or more dedentations // Pop off other levels until col is found: loop { let current_indentation = self.indentation_stack.last().unwrap(); let ordering = indentation_level .compare_strict(current_indentation, self.get_pos())?; match ordering { Ordering::Less => { self.indentation_stack.pop(); let tok_pos = self.get_pos(); self.emit((tok_pos, Tok::Dedent, tok_pos)); } Ordering::Equal => { // We arrived at proper level of indentation. break; } Ordering::Greater => { return Err(LexicalError { error: LexicalErrorType::IndentationError, location: self.get_pos(), }); } } } } } } Ok(()) } /// Take a look at the next character, if any, and decide upon the next steps. fn consume_normal(&mut self) -> Result<(), LexicalError> { // Check if we have some character: if let Some(c) = self.chr0 { // First check identifier: if self.is_identifier_start(c) { let identifier = self.lex_identifier()?; self.emit(identifier); } else if is_emoji_presentation(c) { let tok_start = self.get_pos(); self.next_char(); let tok_end = self.get_pos(); self.emit(( tok_start, Tok::Name { name: c.to_string(), }, tok_end, )); } else { self.consume_character(c)?; } } else { // We reached end of file. let tok_pos = self.get_pos(); // First of all, we need all nestings to be finished. if self.nesting > 0 { return Err(LexicalError { error: LexicalErrorType::NestingError, location: tok_pos, }); } // Next, insert a trailing newline, if required. if !self.at_begin_of_line { self.at_begin_of_line = true; self.emit((tok_pos, Tok::Newline, tok_pos)); } // Next, flush the indentation stack to zero. while self.indentation_stack.len() > 1 { self.indentation_stack.pop(); self.emit((tok_pos, Tok::Dedent, tok_pos)); } self.emit((tok_pos, Tok::EndOfFile, tok_pos)); } Ok(()) } /// Okay, we are facing a weird character, what is it? Determine that. fn consume_character(&mut self, c: char) -> Result<(), LexicalError> { match c { '0'..='9' => { let number = self.lex_number()?; self.emit(number); } '#' => { self.lex_comment(); } '"' | '\'' => { let string = self.lex_string(false, false, false, false)?; self.emit(string); } '=' => { let tok_start = self.get_pos(); self.next_char(); match self.chr0 { Some('=') => { self.next_char(); let tok_end = self.get_pos(); self.emit((tok_start, Tok::EqEqual, tok_end)); } _ => { let tok_end = self.get_pos(); self.emit((tok_start, Tok::Equal, tok_end)); } } } '+' => { let tok_start = self.get_pos(); self.next_char(); if let Some('=') = self.chr0 { self.next_char(); let tok_end = self.get_pos(); self.emit((tok_start, Tok::PlusEqual, tok_end)); } else { let tok_end = self.get_pos(); self.emit((tok_start, Tok::Plus, tok_end)); } } '*' => { let tok_start = self.get_pos(); self.next_char(); match self.chr0 { Some('=') => { self.next_char(); let tok_end = self.get_pos(); self.emit((tok_start, Tok::StarEqual, tok_end)); } Some('*') => { self.next_char(); match self.chr0 { Some('=') => { self.next_char(); let tok_end = self.get_pos(); self.emit((tok_start, Tok::DoubleStarEqual, tok_end)); } _ => { let tok_end = self.get_pos(); self.emit((tok_start, Tok::DoubleStar, tok_end)); } } } _ => { let tok_end = self.get_pos(); self.emit((tok_start, Tok::Star, tok_end)); } } } '/' => { let tok_start = self.get_pos(); self.next_char(); match self.chr0 { Some('=') => { self.next_char(); let tok_end = self.get_pos(); self.emit((tok_start, Tok::SlashEqual, tok_end)); } Some('/') => { self.next_char(); match self.chr0 { Some('=') => { self.next_char(); let tok_end = self.get_pos(); self.emit((tok_start, Tok::DoubleSlashEqual, tok_end)); } _ => { let tok_end = self.get_pos(); self.emit((tok_start, Tok::DoubleSlash, tok_end)); } } } _ => { let tok_end = self.get_pos(); self.emit((tok_start, Tok::Slash, tok_end)); } } } '%' => { let tok_start = self.get_pos(); self.next_char(); if let Some('=') = self.chr0 { self.next_char(); let tok_end = self.get_pos(); self.emit((tok_start, Tok::PercentEqual, tok_end)); } else { let tok_end = self.get_pos(); self.emit((tok_start, Tok::Percent, tok_end)); } } '|' => { let tok_start = self.get_pos(); self.next_char(); if let Some('=') = self.chr0 { self.next_char(); let tok_end = self.get_pos(); self.emit((tok_start, Tok::VbarEqual, tok_end)); } else { let tok_end = self.get_pos(); self.emit((tok_start, Tok::Vbar, tok_end)); } } '^' => { let tok_start = self.get_pos(); self.next_char(); if let Some('=') = self.chr0 { self.next_char(); let tok_end = self.get_pos(); self.emit((tok_start, Tok::CircumflexEqual, tok_end)); } else { let tok_end = self.get_pos(); self.emit((tok_start, Tok::CircumFlex, tok_end)); } } '&' => { let tok_start = self.get_pos(); self.next_char(); if let Some('=') = self.chr0 { self.next_char(); let tok_end = self.get_pos(); self.emit((tok_start, Tok::AmperEqual, tok_end)); } else { let tok_end = self.get_pos(); self.emit((tok_start, Tok::Amper, tok_end)); } } '-' => { let tok_start = self.get_pos(); self.next_char(); match self.chr0 { Some('=') => { self.next_char(); let tok_end = self.get_pos(); self.emit((tok_start, Tok::MinusEqual, tok_end)); } Some('>') => { self.next_char(); let tok_end = self.get_pos(); self.emit((tok_start, Tok::Rarrow, tok_end)); } _ => { let tok_end = self.get_pos(); self.emit((tok_start, Tok::Minus, tok_end)); } } } '@' => { let tok_start = self.get_pos(); self.next_char(); if let Some('=') = self.chr0 { self.next_char(); let tok_end = self.get_pos(); self.emit((tok_start, Tok::AtEqual, tok_end)); } else { let tok_end = self.get_pos(); self.emit((tok_start, Tok::At, tok_end)); } } '!' => { let tok_start = self.get_pos(); self.next_char(); if let Some('=') = self.chr0 { self.next_char(); let tok_end = self.get_pos(); self.emit((tok_start, Tok::NotEqual, tok_end)); } else { return Err(LexicalError { error: LexicalErrorType::UnrecognizedToken { tok: '!' }, location: tok_start, }); } } '~' => { self.eat_single_char(Tok::Tilde); } '(' => { self.eat_single_char(Tok::Lpar); self.nesting += 1; } ')' => { self.eat_single_char(Tok::Rpar); if self.nesting == 0 { return Err(LexicalError { error: LexicalErrorType::NestingError, location: self.get_pos(), }); } self.nesting -= 1; } '[' => { self.eat_single_char(Tok::Lsqb); self.nesting += 1; } ']' => { self.eat_single_char(Tok::Rsqb); if self.nesting == 0 { return Err(LexicalError { error: LexicalErrorType::NestingError, location: self.get_pos(), }); } self.nesting -= 1; } '{' => { self.eat_single_char(Tok::Lbrace); self.nesting += 1; } '}' => { self.eat_single_char(Tok::Rbrace); if self.nesting == 0 { return Err(LexicalError { error: LexicalErrorType::NestingError, location: self.get_pos(), }); } self.nesting -= 1; } ':' => { let tok_start = self.get_pos(); self.next_char(); if let Some('=') = self.chr0 { self.next_char(); let tok_end = self.get_pos(); self.emit((tok_start, Tok::ColonEqual, tok_end)); } else { let tok_end = self.get_pos(); self.emit((tok_start, Tok::Colon, tok_end)); } } ';' => { self.eat_single_char(Tok::Semi); } '<' => { let tok_start = self.get_pos(); self.next_char(); match self.chr0 { Some('<') => { self.next_char(); match self.chr0 { Some('=') => { self.next_char(); let tok_end = self.get_pos(); self.emit((tok_start, Tok::LeftShiftEqual, tok_end)); } _ => { let tok_end = self.get_pos(); self.emit((tok_start, Tok::LeftShift, tok_end)); } } } Some('=') => { self.next_char(); let tok_end = self.get_pos(); self.emit((tok_start, Tok::LessEqual, tok_end)); } _ => { let tok_end = self.get_pos(); self.emit((tok_start, Tok::Less, tok_end)); } } } '>' => { let tok_start = self.get_pos(); self.next_char(); match self.chr0 { Some('>') => { self.next_char(); match self.chr0 { Some('=') => { self.next_char(); let tok_end = self.get_pos(); self.emit((tok_start, Tok::RightShiftEqual, tok_end)); } _ => { let tok_end = self.get_pos(); self.emit((tok_start, Tok::RightShift, tok_end)); } } } Some('=') => { self.next_char(); let tok_end = self.get_pos(); self.emit((tok_start, Tok::GreaterEqual, tok_end)); } _ => { let tok_end = self.get_pos(); self.emit((tok_start, Tok::Greater, tok_end)); } } } ',' => { let tok_start = self.get_pos(); self.next_char(); let tok_end = self.get_pos(); self.emit((tok_start, Tok::Comma, tok_end)); } '.' => { if let Some('0'..='9') = self.chr1 { let number = self.lex_number()?; self.emit(number); } else { let tok_start = self.get_pos(); self.next_char(); if let (Some('.'), Some('.')) = (&self.chr0, &self.chr1) { self.next_char(); self.next_char(); let tok_end = self.get_pos(); self.emit((tok_start, Tok::Ellipsis, tok_end)); } else { let tok_end = self.get_pos(); self.emit((tok_start, Tok::Dot, tok_end)); } } } '\n' => { let tok_start = self.get_pos(); self.next_char(); let tok_end = self.get_pos(); // Depending on the nesting level, we emit newline or not: if self.nesting == 0 { self.at_begin_of_line = true; self.emit((tok_start, Tok::Newline, tok_end)); } } ' ' | '\t' | '\x0C' => { // Skip whitespaces self.next_char(); while self.chr0 == Some(' ') || self.chr0 == Some('\t') || self.chr0 == Some('\x0C') { self.next_char(); } } '\\' => { self.next_char(); if let Some('\n') = self.chr0 { self.next_char(); } else { return Err(LexicalError { error: LexicalErrorType::LineContinuationError, location: self.get_pos(), }); } if self.chr0.is_none() { return Err(LexicalError { error: LexicalErrorType::Eof, location: self.get_pos(), }); } } _ => { let c = self.next_char(); return Err(LexicalError { error: LexicalErrorType::UnrecognizedToken { tok: c.unwrap() }, location: self.get_pos(), }); } // Ignore all the rest.. } Ok(()) } fn eat_single_char(&mut self, ty: Tok) { let tok_start = self.get_pos(); self.next_char().unwrap(); let tok_end = self.get_pos(); self.emit((tok_start, ty, tok_end)); } /// Helper function to go to the next character coming up. fn next_char(&mut self) -> Option<char> { let c = self.chr0; let nxt = self.chars.next(); self.chr0 = self.chr1; self.chr1 = self.chr2; self.chr2 = nxt; if c == Some('\n') { self.location.newline(); } else { self.location.go_right(); } c } /// Helper function to retrieve the current position. fn get_pos(&self) -> Location { self.location } /// Helper function to emit a lexed token to the queue of tokens. fn emit(&mut self, spanned: Spanned) { self.pending.push(spanned); } } /* Implement iterator pattern for the get_tok function. Calling the next element in the iterator will yield the next lexical token. */ impl<T> Iterator for Lexer<T> where T: Iterator<Item = char>, { type Item = LexResult; fn next(&mut self) -> Option<Self::Item> { // Idea: create some sort of hash map for single char tokens: // let mut X = HashMap::new(); // X.insert('=', Tok::Equal); let token = self.inner_next(); trace!( "Lex token {:?}, nesting={:?}, indent stack: {:?}", token, self.nesting, self.indentation_stack ); match token { Ok((_, Tok::EndOfFile, _)) => None, r => Some(r), } } } #[cfg(test)] mod tests { use super::{make_tokenizer, NewlineHandler, Tok}; use num_bigint::BigInt; const WINDOWS_EOL: &str = "\r\n"; const MAC_EOL: &str = "\r"; const UNIX_EOL: &str = "\n"; pub fn lex_source(source: &str) -> Vec<Tok> { let lexer = make_tokenizer(source); lexer.map(|x| x.unwrap().1).collect() } #[test] fn test_newline_processor() { // Escape \ followed by \n (by removal): let src = "b\\\r\n"; assert_eq!(4, src.len()); let nlh = NewlineHandler::new(src.chars()); let x: Vec<char> = nlh.collect(); assert_eq!(vec!['b', '\\', '\n'], x); } #[test] fn test_raw_string() { let source = "r\"\\\\\" \"\\\\\""; let tokens = lex_source(source); assert_eq!( tokens, vec![ Tok::String { value: "\\\\".to_owned(), is_fstring: false, }, Tok::String { value: "\\".to_owned(), is_fstring: false, }, Tok::Newline, ] ); } #[test] fn test_numbers() { let source = "0x2f 0b1101 0 123 0.2 2j 2.2j"; let tokens = lex_source(source); assert_eq!( tokens, vec![ Tok::Int { value: BigInt::from(47), }, Tok::Int { value: BigInt::from(13), }, Tok::Int { value: BigInt::from(0), }, Tok::Int { value: BigInt::from(123), }, Tok::Float { value: 0.2 }, Tok::Complex { real: 0.0, imag: 2.0, }, Tok::Complex { real: 0.0, imag: 2.2, }, Tok::Newline, ] ); } macro_rules! test_line_comment { ($($name:ident: $eol:expr,)*) => { $( #[test] fn $name() { let source = format!(r"99232 # {}", $eol); let tokens = lex_source(&source); assert_eq!(tokens, vec![Tok::Int { value: BigInt::from(99232) }, Tok::Newline]); } )* } } test_line_comment! { test_line_comment_long: " foo", test_line_comment_whitespace: " ", test_line_comment_single_whitespace: " ", test_line_comment_empty: "", } macro_rules! test_comment_until_eol { ($($name:ident: $eol:expr,)*) => { $( #[test] fn $name() { let source = format!("123 # Foo{}456", $eol); let tokens = lex_source(&source); assert_eq!( tokens, vec![ Tok::Int { value: BigInt::from(123) }, Tok::Newline, Tok::Int { value: BigInt::from(456) }, Tok::Newline, ] ) } )* } } test_comment_until_eol! { test_comment_until_windows_eol: WINDOWS_EOL, test_comment_until_mac_eol: MAC_EOL, test_comment_until_unix_eol: UNIX_EOL, } #[test] fn test_assignment() { let source = r"avariable = 99 + 2-0"; let tokens = lex_source(source); assert_eq!( tokens, vec![ Tok::Name { name: String::from("avariable"), }, Tok::Equal, Tok::Int { value: BigInt::from(99) }, Tok::Plus, Tok::Int { value: BigInt::from(2) }, Tok::Minus, Tok::Int { value: BigInt::from(0) }, Tok::Newline, ] ); } macro_rules! test_indentation_with_eol { ($($name:ident: $eol:expr,)*) => { $( #[test] fn $name() { let source = format!("def foo():{} return 99{}{}", $eol, $eol, $eol); let tokens = lex_source(&source); assert_eq!( tokens, vec![ Tok::Def, Tok::Name { name: String::from("foo"), }, Tok::Lpar, Tok::Rpar, Tok::Colon, Tok::Newline, Tok::Indent, Tok::Return, Tok::Int { value: BigInt::from(99) }, Tok::Newline, Tok::Dedent, ] ); } )* }; } test_indentation_with_eol! { test_indentation_windows_eol: WINDOWS_EOL, test_indentation_mac_eol: MAC_EOL, test_indentation_unix_eol: UNIX_EOL, } macro_rules! test_double_dedent_with_eol { ($($name:ident: $eol:expr,)*) => { $( #[test] fn $name() { let source = format!("def foo():{} if x:{}{} return 99{}{}", $eol, $eol, $eol, $eol, $eol); let tokens = lex_source(&source); assert_eq!( tokens, vec![ Tok::Def, Tok::Name { name: String::from("foo"), }, Tok::Lpar, Tok::Rpar, Tok::Colon, Tok::Newline, Tok::Indent, Tok::If, Tok::Name { name: String::from("x"), }, Tok::Colon, Tok::Newline, Tok::Indent, Tok::Return, Tok::Int { value: BigInt::from(99) }, Tok::Newline, Tok::Dedent, Tok::Dedent, ] ); } )* } } macro_rules! test_double_dedent_with_tabs { ($($name:ident: $eol:expr,)*) => { $( #[test] fn $name() { let source = format!("def foo():{}\tif x:{}{}\t return 99{}{}", $eol, $eol, $eol, $eol, $eol); let tokens = lex_source(&source); assert_eq!( tokens, vec![ Tok::Def, Tok::Name { name: String::from("foo"), }, Tok::Lpar, Tok::Rpar, Tok::Colon, Tok::Newline, Tok::Indent, Tok::If, Tok::Name { name: String::from("x"), }, Tok::Colon, Tok::Newline, Tok::Indent, Tok::Return, Tok::Int { value: BigInt::from(99) }, Tok::Newline, Tok::Dedent, Tok::Dedent, ] ); } )* } } test_double_dedent_with_eol! { test_double_dedent_windows_eol: WINDOWS_EOL, test_double_dedent_mac_eol: MAC_EOL, test_double_dedent_unix_eol: UNIX_EOL, } test_double_dedent_with_tabs! { test_double_dedent_tabs_windows_eol: WINDOWS_EOL, test_double_dedent_tabs_mac_eol: MAC_EOL, test_double_dedent_tabs_unix_eol: UNIX_EOL, } macro_rules! test_newline_in_brackets { ($($name:ident: $eol:expr,)*) => { $( #[test] fn $name() { let source = format!("x = [{} 1,2{}]{}", $eol, $eol, $eol); let tokens = lex_source(&source); assert_eq!( tokens, vec![ Tok::Name { name: String::from("x"), }, Tok::Equal, Tok::Lsqb, Tok::Int { value: BigInt::from(1) }, Tok::Comma, Tok::Int { value: BigInt::from(2) }, Tok::Rsqb, Tok::Newline, ] ); } )* }; } test_newline_in_brackets! { test_newline_in_brackets_windows_eol: WINDOWS_EOL, test_newline_in_brackets_mac_eol: MAC_EOL, test_newline_in_brackets_unix_eol: UNIX_EOL, } #[test] fn test_operators() { let source = "//////=/ /"; let tokens = lex_source(source); assert_eq!( tokens, vec![ Tok::DoubleSlash, Tok::DoubleSlash, Tok::DoubleSlashEqual, Tok::Slash, Tok::Slash, Tok::Newline, ] ); } #[test] fn test_string() { let source = r#""double" 'single' 'can\'t' "\\\"" '\t\r\n' '\g' r'raw\'' '\420' '\200\0a'"#; let tokens = lex_source(source); assert_eq!( tokens, vec![ Tok::String { value: String::from("double"), is_fstring: false, }, Tok::String { value: String::from("single"), is_fstring: false, }, Tok::String { value: String::from("can't"), is_fstring: false, }, Tok::String { value: String::from("\\\""), is_fstring: false, }, Tok::String { value: String::from("\t\r\n"), is_fstring: false, }, Tok::String { value: String::from("\\g"), is_fstring: false, }, Tok::String { value: String::from("raw\\'"), is_fstring: false, }, Tok::String { value: String::from("Đ"), is_fstring: false, }, Tok::String { value: String::from("\u{80}\u{0}a"), is_fstring: false, }, Tok::Newline, ] ); } macro_rules! test_string_continuation { ($($name:ident: $eol:expr,)*) => { $( #[test] fn $name() { let source = format!("\"abc\\{}def\"", $eol); let tokens = lex_source(&source); assert_eq!( tokens, vec![ Tok::String { value: String::from("abcdef"), is_fstring: false, }, Tok::Newline, ] ) } )* } } test_string_continuation! { test_string_continuation_windows_eol: WINDOWS_EOL, test_string_continuation_mac_eol: MAC_EOL, test_string_continuation_unix_eol: UNIX_EOL, } #[test] fn test_single_quoted_byte() { // single quote let source = r##"b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff'"##; let tokens = lex_source(source); let res = (0..=255).collect::<Vec<u8>>(); assert_eq!(tokens, vec![Tok::Bytes { value: res }, Tok::Newline]); } #[test] fn test_double_quoted_byte() { // double quote let source = r##"b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff""##; let tokens = lex_source(source); let res = (0..=255).collect::<Vec<u8>>(); assert_eq!(tokens, vec![Tok::Bytes { value: res }, Tok::Newline]); } #[test] fn test_escape_char_in_byte_literal() { // backslash doesnt escape let source = r##"b"omkmok\Xaa""##; let tokens = lex_source(source); let res = vec![111, 109, 107, 109, 111, 107, 92, 88, 97, 97]; assert_eq!(tokens, vec![Tok::Bytes { value: res }, Tok::Newline]); } #[test] fn test_raw_byte_literal() { let source = r"rb'\x1z'"; let tokens = lex_source(source); assert_eq!( tokens, vec![ Tok::Bytes { value: b"\\x1z".to_vec() }, Tok::Newline ] ); let source = r"rb'\\'"; let tokens = lex_source(source); assert_eq!( tokens, vec![ Tok::Bytes { value: b"\\\\".to_vec() }, Tok::Newline ] ) } #[test] fn test_escape_octet() { let source = r##"b'\43a\4\1234'"##; let tokens = lex_source(source); assert_eq!( tokens, vec![ Tok::Bytes { value: b"#a\x04S4".to_vec() }, Tok::Newline ] ) } #[test] fn test_escape_unicode_name() { let source = r#""\N{EN SPACE}""#; let tokens = lex_source(source); assert_eq!( tokens, vec![ Tok::String { value: "\u{2002}".to_owned(), is_fstring: false, }, Tok::Newline ] ) } }
34.562571
767
0.405507
e5d0681e5acab83bd2ed7ead08c818612003fe84
15,867
// Copyright (c) Aptos // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] mod error; mod executed_chunk; pub use error::Error; use anyhow::Result; use aptos_crypto::{ ed25519::Ed25519Signature, hash::{EventAccumulatorHasher, TransactionAccumulatorHasher, ACCUMULATOR_PLACEHOLDER_HASH}, HashValue, }; use aptos_state_view::StateViewId; use aptos_types::{ contract_event::ContractEvent, epoch_state::EpochState, ledger_info::LedgerInfoWithSignatures, nibble::nibble_path::NibblePath, proof::{accumulator::InMemoryAccumulator, AccumulatorExtensionProof}, state_store::{state_key::StateKey, state_value::StateValue}, transaction::{ Transaction, TransactionInfo, TransactionListWithProof, TransactionOutputListWithProof, TransactionStatus, Version, }, write_set::WriteSet, }; use scratchpad::ProofRead; use serde::{Deserialize, Serialize}; use std::{cmp::max, collections::HashMap, sync::Arc}; use storage_interface::DbReader; pub use executed_chunk::ExecutedChunk; use storage_interface::{in_memory_state::InMemoryState, verified_state_view::VerifiedStateView}; type SparseMerkleProof = aptos_types::proof::SparseMerkleProof<StateValue>; pub trait ChunkExecutorTrait: Send + Sync { /// Verifies the transactions based on the provided proofs and ledger info. If the transactions /// are valid, executes them and returns the executed result for commit. fn execute_chunk( &self, txn_list_with_proof: TransactionListWithProof, // Target LI that has been verified independently: the proofs are relative to this version. verified_target_li: &LedgerInfoWithSignatures, epoch_change_li: Option<&LedgerInfoWithSignatures>, ) -> Result<()>; /// Similar to `execute_chunk`, but instead of executing transactions, apply the transaction /// outputs directly to get the executed result. fn apply_chunk( &self, txn_output_list_with_proof: TransactionOutputListWithProof, // Target LI that has been verified independently: the proofs are relative to this version. verified_target_li: &LedgerInfoWithSignatures, epoch_change_li: Option<&LedgerInfoWithSignatures>, ) -> anyhow::Result<()>; /// Commit a previously executed chunk. Returns a vector of reconfiguration /// events in the chunk and the transactions that were committed. fn commit_chunk(&self) -> Result<(Vec<ContractEvent>, Vec<Transaction>)>; fn execute_and_commit_chunk( &self, txn_list_with_proof: TransactionListWithProof, verified_target_li: &LedgerInfoWithSignatures, epoch_change_li: Option<&LedgerInfoWithSignatures>, ) -> Result<(Vec<ContractEvent>, Vec<Transaction>)>; fn apply_and_commit_chunk( &self, txn_output_list_with_proof: TransactionOutputListWithProof, verified_target_li: &LedgerInfoWithSignatures, epoch_change_li: Option<&LedgerInfoWithSignatures>, ) -> Result<(Vec<ContractEvent>, Vec<Transaction>)>; /// Resets the chunk executor by synchronizing state with storage. fn reset(&self) -> Result<()>; } pub trait BlockExecutorTrait: Send + Sync { /// Get the latest committed block id fn committed_block_id(&self) -> HashValue; /// Reset the internal state including cache with newly fetched latest committed block from storage. fn reset(&self) -> Result<(), Error>; /// Executes a block. fn execute_block( &self, block: (HashValue, Vec<Transaction>), parent_block_id: HashValue, ) -> Result<StateComputeResult, Error>; /// Saves eligible blocks to persistent storage. /// If we have multiple blocks and not all of them have signatures, we may send them to storage /// in a few batches. For example, if we have /// ```text /// A <- B <- C <- D <- E /// ``` /// and only `C` and `E` have signatures, we will send `A`, `B` and `C` in the first batch, /// then `D` and `E` later in the another batch. /// Commits a block and all its ancestors in a batch manner. fn commit_blocks( &self, block_ids: Vec<HashValue>, ledger_info_with_sigs: LedgerInfoWithSignatures, ) -> Result<(), Error>; } pub trait TransactionReplayer: Send { fn replay( &self, transactions: Vec<Transaction>, transaction_infos: Vec<TransactionInfo>, ) -> Result<()>; fn commit(&self) -> Result<Arc<ExecutedChunk>>; } /// A structure that summarizes the result of the execution needed for consensus to agree on. /// The execution is responsible for generating the ID of the new state, which is returned in the /// result. /// /// Not every transaction in the payload succeeds: the returned vector keeps the boolean status /// of success / failure of the transactions. /// Note that the specific details of compute_status are opaque to StateMachineReplication, /// which is going to simply pass the results between StateComputer and TxnManager. #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)] pub struct StateComputeResult { /// transaction accumulator root hash is identified as `state_id` in Consensus. root_hash: HashValue, /// Represents the roots of all the full subtrees from left to right in this accumulator /// after the execution. For details, please see [`InMemoryAccumulator`](accumulator::InMemoryAccumulator). frozen_subtree_roots: Vec<HashValue>, /// The frozen subtrees roots of the parent block, parent_frozen_subtree_roots: Vec<HashValue>, /// The number of leaves of the transaction accumulator after executing a proposed block. /// This state must be persisted to ensure that on restart that the version is calculated correctly. num_leaves: u64, /// The number of leaves after executing the parent block, parent_num_leaves: u64, /// If set, this is the new epoch info that should be changed to if this block is committed. epoch_state: Option<EpochState>, /// The compute status (success/failure) of the given payload. The specific details are opaque /// for StateMachineReplication, which is merely passing it between StateComputer and /// TxnManager. compute_status: Vec<TransactionStatus>, /// The transaction info hashes of all success txns. transaction_info_hashes: Vec<HashValue>, /// The signature of the VoteProposal corresponding to this block. signature: Option<Ed25519Signature>, reconfig_events: Vec<ContractEvent>, } impl StateComputeResult { pub fn new( root_hash: HashValue, frozen_subtree_roots: Vec<HashValue>, num_leaves: u64, parent_frozen_subtree_roots: Vec<HashValue>, parent_num_leaves: u64, epoch_state: Option<EpochState>, compute_status: Vec<TransactionStatus>, transaction_info_hashes: Vec<HashValue>, reconfig_events: Vec<ContractEvent>, ) -> Self { Self { root_hash, frozen_subtree_roots, num_leaves, parent_frozen_subtree_roots, parent_num_leaves, epoch_state, compute_status, transaction_info_hashes, reconfig_events, signature: None, } } /// generate a new dummy state compute result with a given root hash. /// this function is used in RandomComputeResultStateComputer to assert that the compute /// function is really called. pub fn new_dummy_with_root_hash(root_hash: HashValue) -> Self { Self { root_hash, frozen_subtree_roots: vec![], num_leaves: 0, parent_frozen_subtree_roots: vec![], parent_num_leaves: 0, epoch_state: None, compute_status: vec![], transaction_info_hashes: vec![], reconfig_events: vec![], signature: None, } } /// generate a new dummy state compute result with ACCUMULATOR_PLACEHOLDER_HASH as the root hash. /// this function is used in ordering_state_computer as a dummy state compute result, /// where the real compute result is generated after ordering_state_computer.commit pushes /// the blocks and the finality proof to the execution phase. pub fn new_dummy() -> Self { StateComputeResult::new_dummy_with_root_hash(*ACCUMULATOR_PLACEHOLDER_HASH) } } impl StateComputeResult { pub fn version(&self) -> Version { max(self.num_leaves, 1) .checked_sub(1) .expect("Integer overflow occurred") } pub fn root_hash(&self) -> HashValue { self.root_hash } pub fn compute_status(&self) -> &Vec<TransactionStatus> { &self.compute_status } pub fn epoch_state(&self) -> &Option<EpochState> { &self.epoch_state } pub fn extension_proof(&self) -> AccumulatorExtensionProof<TransactionAccumulatorHasher> { AccumulatorExtensionProof::<TransactionAccumulatorHasher>::new( self.parent_frozen_subtree_roots.clone(), self.parent_num_leaves(), self.transaction_info_hashes().clone(), ) } pub fn transaction_info_hashes(&self) -> &Vec<HashValue> { &self.transaction_info_hashes } pub fn num_leaves(&self) -> u64 { self.num_leaves } pub fn frozen_subtree_roots(&self) -> &Vec<HashValue> { &self.frozen_subtree_roots } pub fn parent_num_leaves(&self) -> u64 { self.parent_num_leaves } pub fn parent_frozen_subtree_roots(&self) -> &Vec<HashValue> { &self.parent_frozen_subtree_roots } pub fn has_reconfiguration(&self) -> bool { self.epoch_state.is_some() } pub fn reconfig_events(&self) -> &[ContractEvent] { &self.reconfig_events } pub fn signature(&self) -> &Option<Ed25519Signature> { &self.signature } pub fn set_signature(&mut self, sig: Ed25519Signature) { self.signature = Some(sig); } } /// A wrapper of the in-memory state sparse merkle tree and the transaction accumulator that /// represent a specific state collectively. Usually it is a state after executing a block. #[derive(Clone, Debug)] pub struct ExecutedTrees { /// The in-memory representation of state after execution. state: InMemoryState, /// The in-memory Merkle Accumulator representing a blockchain state consistent with the /// `state_tree`. transaction_accumulator: Arc<InMemoryAccumulator<TransactionAccumulatorHasher>>, } impl ExecutedTrees { pub fn state(&self) -> &InMemoryState { &self.state } pub fn txn_accumulator(&self) -> &Arc<InMemoryAccumulator<TransactionAccumulatorHasher>> { &self.transaction_accumulator } pub fn version(&self) -> Option<Version> { let num_elements = self.txn_accumulator().num_leaves() as u64; num_elements.checked_sub(1) } pub fn state_id(&self) -> HashValue { self.txn_accumulator().root_hash() } pub fn new( state: InMemoryState, transaction_accumulator: Arc<InMemoryAccumulator<TransactionAccumulatorHasher>>, ) -> Self { Self { state, transaction_accumulator, } } pub fn new_at_state_checkpoint( state_root_hash: HashValue, frozen_subtrees_in_accumulator: Vec<HashValue>, num_leaves_in_accumulator: u64, ) -> Self { let state = InMemoryState::new_at_checkpoint(state_root_hash, num_leaves_in_accumulator); let transaction_accumulator = Arc::new( InMemoryAccumulator::new(frozen_subtrees_in_accumulator, num_leaves_in_accumulator) .expect("The startup info read from storage should be valid."), ); Self::new(state, transaction_accumulator) } pub fn new_empty() -> Self { Self::new( InMemoryState::new_empty(), Arc::new(InMemoryAccumulator::new_empty()), ) } pub fn is_same_view(&self, rhs: &Self) -> bool { self.transaction_accumulator.root_hash() == rhs.transaction_accumulator.root_hash() } pub fn state_view( &self, persisted_view: &Self, id: StateViewId, reader: Arc<dyn DbReader>, ) -> VerifiedStateView { VerifiedStateView::new( id, reader.clone(), persisted_view.state.checkpoint_version(), persisted_view.state.checkpoint_root_hash(), self.state.current.clone(), ) } } impl Default for ExecutedTrees { fn default() -> Self { Self::new_empty() } } pub struct ProofReader { proofs: HashMap<HashValue, SparseMerkleProof>, } impl ProofReader { pub fn new(proofs: HashMap<HashValue, SparseMerkleProof>) -> Self { ProofReader { proofs } } pub fn new_empty() -> Self { Self::new(HashMap::new()) } } impl ProofRead<StateValue> for ProofReader { fn get_proof(&self, key: HashValue) -> Option<&SparseMerkleProof> { self.proofs.get(&key) } } /// The entire set of data associated with a transaction. In addition to the output generated by VM /// which includes the write set and events, this also has the in-memory trees. #[derive(Clone, Debug)] pub struct TransactionData { /// Each entry in this map represents the new value of a store store object touched by this /// transaction. state_updates: HashMap<StateKey, StateValue>, /// Each entry in this map represents the the hash of a newly generated jellyfish node /// and its corresponding nibble path. jf_node_hashes: HashMap<NibblePath, HashValue>, /// The writeset generated from this transaction. write_set: WriteSet, /// The list of events emitted during this transaction. events: Vec<ContractEvent>, /// List of reconfiguration events emitted during this transaction. reconfig_events: Vec<ContractEvent>, /// The execution status set by the VM. status: TransactionStatus, /// The in-memory Merkle Accumulator that has all events emitted by this transaction. event_tree: Arc<InMemoryAccumulator<EventAccumulatorHasher>>, /// The amount of gas used. gas_used: u64, /// TransactionInfo txn_info: TransactionInfo, /// TransactionInfo.hash() txn_info_hash: HashValue, } impl TransactionData { pub fn new( state_updates: HashMap<StateKey, StateValue>, jf_node_hashes: HashMap<NibblePath, HashValue>, write_set: WriteSet, events: Vec<ContractEvent>, reconfig_events: Vec<ContractEvent>, status: TransactionStatus, event_tree: Arc<InMemoryAccumulator<EventAccumulatorHasher>>, gas_used: u64, txn_info: TransactionInfo, txn_info_hash: HashValue, ) -> Self { TransactionData { state_updates, jf_node_hashes, write_set, events, reconfig_events, status, event_tree, gas_used, txn_info, txn_info_hash, } } pub fn state_updates(&self) -> &HashMap<StateKey, StateValue> { &self.state_updates } pub fn jf_node_hashes(&self) -> &HashMap<NibblePath, HashValue> { &self.jf_node_hashes } pub fn write_set(&self) -> &WriteSet { &self.write_set } pub fn events(&self) -> &[ContractEvent] { &self.events } pub fn status(&self) -> &TransactionStatus { &self.status } pub fn event_root_hash(&self) -> HashValue { self.event_tree.root_hash() } pub fn gas_used(&self) -> u64 { self.gas_used } pub fn txn_info_hash(&self) -> HashValue { self.txn_info_hash } }
32.648148
111
0.668683
feb027ed7456df16f3c867499861afd66c630a75
6,541
//! //! Examples of coloring the terminal. //! extern crate crossterm; use self::crossterm::style::{color, style, Color}; use self::crossterm::{terminal, Screen}; /// print some red font | demonstration. pub fn paint_foreground() { // Create a styled object. // Call the method `with()` on the object given by `style()` and pass in any Color from the Color enum. let styledobject = style("Red foreground").with(Color::Red); // Print the object to the given screen and. println!("Colored text: {}", styledobject); // Or print inline println!( "Colored text: {}", style("Blue foreground").with(Color::Blue) ); } /// print some font on red background | demonstration. pub fn paint_background() { // Create a styled object. // Call the method `with()` on the object given by `style()` and pass in any Color from the Color enum. let styledobject = style("Red foreground").on(Color::Red); // Print the object to the given screen and. println!("Colored text: {}", styledobject); // Or print inline println!("Colored text: {}", style("Red foreground").on(Color::Blue)); } /// Print all available foreground colors | demonstration. pub fn print_all_foreground_colors() { println!( "{}", style(format!("Black : \t\t {} \n", "■")).with(Color::Black) ); println!( "{}", style(format!("Red : \t\t {} \n", "■")).with(Color::Red) ); println!( "{}", style(format!("Cyan : \t\t {} \n", "■")).with(Color::Cyan) ); println!( "{}", style(format!("DarkCyan : \t {} \n", "■")).with(Color::DarkCyan) ); println!( "{}", style(format!("DarkRed : \t {} \n", "■")).with(Color::DarkRed) ); println!( "{}", style(format!("Green : \t {} \n", "■")).with(Color::Green) ); println!( "{}", style(format!("DarkGreen : \t {} \n", "■")).with(Color::DarkGreen) ); println!( "{}", style(format!("Blue : \t\t {} \n", "■")).with(Color::Blue) ); println!( "{}", style(format!("DarkBlue : \t {} \n", "■")).with(Color::DarkBlue) ); println!( "{}", style(format!("Magenta : \t {} \n", "■")).with(Color::Magenta) ); println!( "{}", style(format!("DarkMagenta : \t {} \n", "■")).with(Color::DarkMagenta) ); println!( "{}", style(format!("Yellow : \t {} \n", "■")).with(Color::Yellow) ); println!( "{}", style(format!("DarkYellow : \t {} \n", "■")).with(Color::DarkYellow) ); println!( "{}", style(format!("Grey : \t\t {} \n", "■")).with(Color::Grey) ); println!( "{}", style(format!("White : \t {} \n", "■")).with(Color::White) ); #[cfg(unix)] println!( "{}", style("RGB color (10,10,10) ").with(Color::Rgb { r: 10, g: 10, b: 10 }) ); #[cfg(unix)] println!( "{}", style("RGB color (10,10,10) ").with(Color::AnsiValue(50)) ); } /// Print all available foreground colors | demonstration. pub fn print_all_background_colors() { println!( "{}", style(format!("Black : \t {} \n", "■")).on(Color::Black) ); println!( "{}", style(format!("Red : \t\t {} \n", "■")).on(Color::Red) ); println!( "{}", style(format!("Cyan : \t\t {} \n", "■")).on(Color::Cyan) ); println!( "{}", style(format!("DarkCyan : \t {} \n", "■")).on(Color::DarkCyan) ); println!( "{}", style(format!("DarkRed : \t {} \n", "■")).on(Color::DarkRed) ); println!( "{}", style(format!("Green : \t {} \n", "■")).on(Color::Green) ); println!( "{}", style(format!("DarkGreen : \t {} \n", "■")).on(Color::DarkGreen) ); println!( "{}", style(format!("Blue : \t\t {} \n", "■")).on(Color::Blue) ); println!( "{}", style(format!("DarkBlue : \t {} \n", "■")).on(Color::DarkBlue) ); println!( "{}", style(format!("Magenta : \t {} \n", "■")).on(Color::Magenta) ); println!( "{}", style(format!("DarkMagenta : \t {} \n", "■")).on(Color::DarkMagenta) ); println!( "{}", style(format!("Yellow : \t {} \n", "■")).on(Color::Yellow) ); println!( "{}", style(format!("DarkYellow : \t {} \n", "■")).on(Color::DarkYellow) ); println!( "{}", style(format!("Grey : \t\t {} \n", "■")).on(Color::Grey) ); println!( "{}", style(format!("White : \t {} \n", "■")).on(Color::White) ); #[cfg(unix)] println!( "{}", style("RGB color (10,10,10) ").on(Color::Rgb { r: 10, g: 10, b: 10 }) ); #[cfg(unix)] println!( "{}", style("RGB color (10,10,10) ").on(Color::AnsiValue(50)) ); } /// Print font with all available attributes. Note that this can only be used at unix systems and that some are not supported widely | demonstration.. #[cfg(unix)] pub fn print_font_with_attributes() { println!("{}", style("Normal text")); println!("{}", style("Bold text").bold()); println!("{}", style("Italic text").italic()); println!("{}", style("Slow blinking text").slow_blink()); println!("{}", style("Rapid blinking text").rapid_blink()); println!("{}", style("Hidden text").hidden()); println!("{}", style("Underlined text").underlined()); println!("{}", style("Reversed text").reverse()); println!("{}", style("Dim text").dim()); println!("{}", style("Crossed out font").crossed_out()); } /// Print font with all available attributes. Note that this can only be used at unix systems and that some are not supported widely | demonstration.. #[cfg(windows)] pub fn print_font_with_attributes() { println!("{}", style("Normal text")); println!("{}", style("Bold text").bold()); println!("{}", style("Underlined text").underlined()); println!("{}", style("Negative text").negative()); } /// Print all supported RGB colors | demonstration. #[cfg(unix)] pub fn print_supported_colors() { let count = color().get_available_color_count().unwrap(); for i in 0..count { println!( "{}", style(format!("White : \t {}", i)).on(Color::AnsiValue(i as u8)) ); } }
27.952991
150
0.497936
abd417485f5e59933b0a5e361204d4402a1a3965
1,249
use ndarray::*; use ndarray_linalg::*; fn test(a: Array2<f64>, one: f64, inf: f64, fro: f64) { println!("ONE = {:?}", a.opnorm_one()); println!("INF = {:?}", a.opnorm_inf()); println!("FRO = {:?}", a.opnorm_fro()); assert_rclose!(a.opnorm_one().unwrap(), one, 1e-7; "One norm"); assert_rclose!(a.opnorm_inf().unwrap(), inf, 1e-7; "Infinity norm"); assert_rclose!(a.opnorm_fro().unwrap(), fro, 1e-7; "Frobenius norm"); } fn gen(i: usize, j: usize, rev: bool) -> Array2<f64> { let n = (i * j + 1) as f64; if rev { Array::range(1., n, 1.) .into_shape((j, i)) .unwrap() .reversed_axes() } else { Array::range(1., n, 1.).into_shape((i, j)).unwrap() } } #[test] fn opnorm_square() { test(gen(3, 3, false), 18.0, 24.0, 285.0.sqrt()); } #[test] fn opnorm_square_t() { test(gen(3, 3, true), 24.0, 18.0, 285.0.sqrt()); } #[test] fn opnorm_3x4() { test(gen(3, 4, false), 24.0, 42.0, 650.0.sqrt()); } #[test] fn opnorm_3x4_t() { test(gen(3, 4, true), 33.0, 30.0, 650.0.sqrt()); } #[test] fn opnorm_4x3() { test(gen(4, 3, false), 30.0, 33.0, 650.0.sqrt()); } #[test] fn opnorm_4x3_t() { test(gen(4, 3, true), 42.0, 24.0, 650.0.sqrt()); }
23.12963
73
0.533227
f5bdecbc2233a468ac00bca6ad214fb539f1591f
6,084
// Generated from definition io.k8s.api.extensions.v1beta1.ReplicaSetSpec /// ReplicaSetSpec is the specification of a ReplicaSet. #[derive(Clone, Debug, Default, PartialEq)] pub struct ReplicaSetSpec { /// Minimum number of seconds for which a newly created pod should be ready without any of its container crashing, for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready) pub min_ready_seconds: Option<i32>, /// Replicas is the number of desired replicas. This is a pointer to distinguish between explicit zero and unspecified. Defaults to 1. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller/#what-is-a-replicationcontroller pub replicas: Option<i32>, /// Selector is a label query over pods that should match the replica count. If the selector is empty, it is defaulted to the labels present on the pod template. Label keys and values that must match in order to be controlled by this replica set. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors pub selector: Option<crate::v1_16::apimachinery::pkg::apis::meta::v1::LabelSelector>, /// Template is the object that describes the pod that will be created if insufficient replicas are detected. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#pod-template pub template: Option<crate::v1_16::api::core::v1::PodTemplateSpec>, } impl<'de> serde::Deserialize<'de> for ReplicaSetSpec { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> { #[allow(non_camel_case_types)] enum Field { Key_min_ready_seconds, Key_replicas, Key_selector, Key_template, Other, } impl<'de> serde::Deserialize<'de> for Field { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> { struct Visitor; impl<'de> serde::de::Visitor<'de> for Visitor { type Value = Field; fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "field identifier") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error { Ok(match v { "minReadySeconds" => Field::Key_min_ready_seconds, "replicas" => Field::Key_replicas, "selector" => Field::Key_selector, "template" => Field::Key_template, _ => Field::Other, }) } } deserializer.deserialize_identifier(Visitor) } } struct Visitor; impl<'de> serde::de::Visitor<'de> for Visitor { type Value = ReplicaSetSpec; fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "struct ReplicaSetSpec") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: serde::de::MapAccess<'de> { let mut value_min_ready_seconds: Option<i32> = None; let mut value_replicas: Option<i32> = None; let mut value_selector: Option<crate::v1_16::apimachinery::pkg::apis::meta::v1::LabelSelector> = None; let mut value_template: Option<crate::v1_16::api::core::v1::PodTemplateSpec> = None; while let Some(key) = serde::de::MapAccess::next_key::<Field>(&mut map)? { match key { Field::Key_min_ready_seconds => value_min_ready_seconds = serde::de::MapAccess::next_value(&mut map)?, Field::Key_replicas => value_replicas = serde::de::MapAccess::next_value(&mut map)?, Field::Key_selector => value_selector = serde::de::MapAccess::next_value(&mut map)?, Field::Key_template => value_template = serde::de::MapAccess::next_value(&mut map)?, Field::Other => { let _: serde::de::IgnoredAny = serde::de::MapAccess::next_value(&mut map)?; }, } } Ok(ReplicaSetSpec { min_ready_seconds: value_min_ready_seconds, replicas: value_replicas, selector: value_selector, template: value_template, }) } } deserializer.deserialize_struct( "ReplicaSetSpec", &[ "minReadySeconds", "replicas", "selector", "template", ], Visitor, ) } } impl serde::Serialize for ReplicaSetSpec { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer { let mut state = serializer.serialize_struct( "ReplicaSetSpec", self.min_ready_seconds.as_ref().map_or(0, |_| 1) + self.replicas.as_ref().map_or(0, |_| 1) + self.selector.as_ref().map_or(0, |_| 1) + self.template.as_ref().map_or(0, |_| 1), )?; if let Some(value) = &self.min_ready_seconds { serde::ser::SerializeStruct::serialize_field(&mut state, "minReadySeconds", value)?; } if let Some(value) = &self.replicas { serde::ser::SerializeStruct::serialize_field(&mut state, "replicas", value)?; } if let Some(value) = &self.selector { serde::ser::SerializeStruct::serialize_field(&mut state, "selector", value)?; } if let Some(value) = &self.template { serde::ser::SerializeStruct::serialize_field(&mut state, "template", value)?; } serde::ser::SerializeStruct::end(state) } }
47.905512
351
0.577416
4b8f584efbedcc9865ced8977341d4fd76c17ed9
3,560
//! Signatory Ed25519 provider for the [ed25519-dalek] crate. //! //! For a usage example, see the toplevel Signatory docs: //! <https://docs.rs/signatory/latest/signatory/ed25519/index.html> //! //! [ed25519-dalek]: https://github.com/dalek-cryptography/ed25519-dalek #![no_std] #![forbid(unsafe_code)] #![warn(missing_docs, rust_2018_idioms, unused_qualifications)] #![doc( html_logo_url = "https://raw.githubusercontent.com/tendermint/signatory/develop/img/signatory-rustacean.png", html_root_url = "https://docs.rs/signatory-dalek/0.16.0" )] #[cfg(test)] #[macro_use] extern crate signatory; use sha2::Sha512; use signatory::{ ed25519, public_key::PublicKeyed, signature::{DigestSigner, DigestVerifier, Error, Signature, Signer, Verifier}, }; /// Ed25519 signature provider for ed25519-dalek pub struct Ed25519Signer(ed25519_dalek::Keypair); impl<'a> From<&'a ed25519::Seed> for Ed25519Signer { /// Create a new DalekSigner from an unexpanded seed value fn from(seed: &'a ed25519::Seed) -> Self { Ed25519Signer(keypair_from_seed(seed)) } } impl PublicKeyed<ed25519::PublicKey> for Ed25519Signer { fn public_key(&self) -> Result<ed25519::PublicKey, Error> { Ok(ed25519::PublicKey::from_bytes(self.0.public.as_bytes()).unwrap()) } } impl Signer<ed25519::Signature> for Ed25519Signer { fn try_sign(&self, msg: &[u8]) -> Result<ed25519::Signature, Error> { let signature = self.0.sign(msg).to_bytes(); Ok(ed25519::Signature::from_bytes(&signature[..]).unwrap()) } } // TODO: tests! impl DigestSigner<Sha512, ed25519::Signature> for Ed25519Signer { fn try_sign_digest(&self, digest: Sha512) -> Result<ed25519::Signature, Error> { // TODO: context support let context: Option<&'static [u8]> = None; let signature = ed25519::Signature::from_bytes(&self.0.sign_prehashed(digest, context).to_bytes()[..]) .unwrap(); Ok(signature) } } /// Ed25519 verifier provider for ed25519-dalek #[derive(Clone, Debug, Eq, PartialEq)] pub struct Ed25519Verifier(ed25519_dalek::PublicKey); impl<'a> From<&'a ed25519::PublicKey> for Ed25519Verifier { fn from(public_key: &'a ed25519::PublicKey) -> Self { Ed25519Verifier(ed25519_dalek::PublicKey::from_bytes(public_key.as_ref()).unwrap()) } } impl Verifier<ed25519::Signature> for Ed25519Verifier { fn verify(&self, msg: &[u8], sig: &ed25519::Signature) -> Result<(), Error> { let dalek_sig = ed25519_dalek::Signature::from_bytes(sig.as_ref()).unwrap(); self.0.verify(msg, &dalek_sig).map_err(|_| Error::new()) } } // TODO: tests! impl DigestVerifier<Sha512, ed25519::Signature> for Ed25519Verifier { fn verify_digest(&self, digest: Sha512, sig: &ed25519::Signature) -> Result<(), Error> { // TODO: context support let context: Option<&'static [u8]> = None; let dalek_sig = ed25519_dalek::Signature::from_bytes(sig.as_ref()).unwrap(); self.0 .verify_prehashed(digest, context, &dalek_sig) .map_err(|_| Error::new()) } } /// Convert a Signatory seed into a Dalek keypair fn keypair_from_seed(seed: &ed25519::Seed) -> ed25519_dalek::Keypair { let secret = ed25519_dalek::SecretKey::from_bytes(seed.as_secret_slice()).unwrap(); let public = ed25519_dalek::PublicKey::from(&secret); ed25519_dalek::Keypair { secret, public } } #[cfg(test)] mod tests { use super::{Ed25519Signer, Ed25519Verifier}; ed25519_tests!(Ed25519Signer, Ed25519Verifier); }
33.904762
113
0.680056
87fe1a68ba1d02171f4f2841b11620148d715970
59,719
use futures::stream::poll_fn; use futures::{Async, Poll, Stream}; use graphql_parser::schema as s; use lazy_static::lazy_static; use mockall::predicate::*; use mockall::*; use serde::{Deserialize, Serialize}; use stable_hash::prelude::*; use std::env; use std::fmt; use std::str::FromStr; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, RwLock}; use std::time::{Duration, Instant}; use std::{ collections::{BTreeMap, HashMap, HashSet}, fmt::Display, }; use thiserror::Error; use web3::types::{Address, H256}; use crate::blockchain::Blockchain; use crate::data::subgraph::status; use crate::data::{store::*, subgraph::Source}; use crate::prelude::*; use crate::util::lfu_cache::LfuCache; use crate::{ blockchain::DataSource, data::{query::QueryTarget, subgraph::schema::*}, }; use crate::components::server::index_node::VersionInfo; lazy_static! { pub static ref SUBSCRIPTION_THROTTLE_INTERVAL: Duration = env::var("SUBSCRIPTION_THROTTLE_INTERVAL") .ok() .map(|s| u64::from_str(&s).unwrap_or_else(|_| panic!( "failed to parse env var SUBSCRIPTION_THROTTLE_INTERVAL" ))) .map(Duration::from_millis) .unwrap_or_else(|| Duration::from_millis(1000)); } /// The type name of an entity. This is the string that is used in the /// subgraph's GraphQL schema as `type NAME @entity { .. }` #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct EntityType(String); impl EntityType { /// Construct a new entity type. Ideally, this is only called when /// `entity_type` either comes from the GraphQL schema, or from /// the database from fields that are known to contain a valid entity type pub fn new(entity_type: String) -> Self { Self(entity_type) } pub fn as_str(&self) -> &str { &self.0 } pub fn into_string(self) -> String { self.0 } } impl fmt::Display for EntityType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) } } impl<'a> From<&s::ObjectType<'a, String>> for EntityType { fn from(object_type: &s::ObjectType<'a, String>) -> Self { EntityType::new(object_type.name.to_owned()) } } impl<'a> From<&s::InterfaceType<'a, String>> for EntityType { fn from(interface_type: &s::InterfaceType<'a, String>) -> Self { EntityType::new(interface_type.name.to_owned()) } } // This conversion should only be used in tests since it makes it too // easy to convert random strings into entity types #[cfg(debug_assertions)] impl From<&str> for EntityType { fn from(s: &str) -> Self { EntityType::new(s.to_owned()) } } impl CheapClone for EntityType {} // Note: Do not modify fields without making a backward compatible change to // the StableHash impl (below) /// Key by which an individual entity in the store can be accessed. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct EntityKey { /// ID of the subgraph. pub subgraph_id: DeploymentHash, /// Name of the entity type. pub entity_type: EntityType, /// ID of the individual entity. pub entity_id: String, } impl StableHash for EntityKey { fn stable_hash<H: StableHasher>(&self, mut sequence_number: H::Seq, state: &mut H) { self.subgraph_id .stable_hash(sequence_number.next_child(), state); self.entity_type .as_str() .stable_hash(sequence_number.next_child(), state); self.entity_id .stable_hash(sequence_number.next_child(), state); } } impl EntityKey { pub fn data(subgraph_id: DeploymentHash, entity_type: String, entity_id: String) -> Self { Self { subgraph_id, entity_type: EntityType::new(entity_type), entity_id, } } } #[test] fn key_stable_hash() { use stable_hash::crypto::SetHasher; use stable_hash::utils::stable_hash; #[track_caller] fn hashes_to(key: &EntityKey, exp: &str) { let hash = hex::encode(stable_hash::<SetHasher, _>(&key)); assert_eq!(exp, hash.as_str()); } let id = DeploymentHash::new("QmP9MRvVzwHxr3sGvujihbvJzcTz2LYLMfi5DyihBg6VUd").unwrap(); let key = EntityKey::data(id.clone(), "Account".to_string(), "0xdeadbeef".to_string()); hashes_to( &key, "905b57035d6f98cff8281e7b055e10570a2bd31190507341c6716af2d3c1ad98", ); } /// Supported types of store filters. #[derive(Clone, Debug, PartialEq)] pub enum EntityFilter { And(Vec<EntityFilter>), Or(Vec<EntityFilter>), Equal(Attribute, Value), Not(Attribute, Value), GreaterThan(Attribute, Value), LessThan(Attribute, Value), GreaterOrEqual(Attribute, Value), LessOrEqual(Attribute, Value), In(Attribute, Vec<Value>), NotIn(Attribute, Vec<Value>), Contains(Attribute, Value), NotContains(Attribute, Value), StartsWith(Attribute, Value), NotStartsWith(Attribute, Value), EndsWith(Attribute, Value), NotEndsWith(Attribute, Value), } // Define some convenience methods impl EntityFilter { pub fn new_equal( attribute_name: impl Into<Attribute>, attribute_value: impl Into<Value>, ) -> Self { EntityFilter::Equal(attribute_name.into(), attribute_value.into()) } pub fn new_in( attribute_name: impl Into<Attribute>, attribute_values: Vec<impl Into<Value>>, ) -> Self { EntityFilter::In( attribute_name.into(), attribute_values.into_iter().map(Into::into).collect(), ) } pub fn and_maybe(self, other: Option<Self>) -> Self { use EntityFilter as f; match other { Some(other) => match (self, other) { (f::And(mut fs1), f::And(mut fs2)) => { fs1.append(&mut fs2); f::And(fs1) } (f::And(mut fs1), f2) => { fs1.push(f2); f::And(fs1) } (f1, f::And(mut fs2)) => { fs2.push(f1); f::And(fs2) } (f1, f2) => f::And(vec![f1, f2]), }, None => self, } } } /// The order in which entities should be restored from a store. #[derive(Clone, Debug, PartialEq)] pub enum EntityOrder { /// Order ascending by the given attribute. Use `id` as a tie-breaker Ascending(String, ValueType), /// Order descending by the given attribute. Use `id` as a tie-breaker Descending(String, ValueType), /// Order by the `id` of the entities Default, /// Do not order at all. This speeds up queries where we know that /// order does not matter Unordered, } /// How many entities to return, how many to skip etc. #[derive(Clone, Debug, PartialEq)] pub struct EntityRange { /// Limit on how many entities to return. pub first: Option<u32>, /// How many entities to skip. pub skip: u32, } impl EntityRange { /// Query for the first `n` entities. pub fn first(n: u32) -> Self { Self { first: Some(n), skip: 0, } } } /// The attribute we want to window by in an `EntityWindow`. We have to /// distinguish between scalar and list attributes since we need to use /// different queries for them, and the JSONB storage scheme can not /// determine that by itself #[derive(Clone, Debug, PartialEq)] pub enum WindowAttribute { Scalar(String), List(String), } impl WindowAttribute { pub fn name(&self) -> &str { match self { WindowAttribute::Scalar(name) => name, WindowAttribute::List(name) => name, } } } /// How to connect children to their parent when the child table does not /// store parent id's #[derive(Clone, Debug, PartialEq)] pub enum ParentLink { /// The parent stores a list of child ids. The ith entry in the outer /// vector contains the id of the children for `EntityWindow.ids[i]` List(Vec<Vec<String>>), /// The parent stores the id of one child. The ith entry in the /// vector contains the id of the child of the parent with id /// `EntityWindow.ids[i]` Scalar(Vec<String>), } /// How many children a parent can have when the child stores /// the id of the parent #[derive(Clone, Copy, Debug, PartialEq)] pub enum ChildMultiplicity { Single, Many, } /// How to select children for their parents depending on whether the /// child stores parent ids (`Direct`) or the parent /// stores child ids (`Parent`) #[derive(Clone, Debug, PartialEq)] pub enum EntityLink { /// The parent id is stored in this child attribute Direct(WindowAttribute, ChildMultiplicity), /// Join with the parents table to get at the parent id Parent(ParentLink), } /// Window results of an `EntityQuery` query along the parent's id: /// the `order_by`, `order_direction`, and `range` of the query apply to /// entities that belong to the same parent. Only entities that belong to /// one of the parents listed in `ids` will be included in the query result. /// /// Note that different windows can vary both by the entity type and id of /// the children, but also by how to get from a child to its parent, i.e., /// it is possible that two windows access the same entity type, but look /// at different attributes to connect to parent entities #[derive(Clone, Debug, PartialEq)] pub struct EntityWindow { /// The entity type for this window pub child_type: EntityType, /// The ids of parents that should be considered for this window pub ids: Vec<String>, /// How to get the parent id pub link: EntityLink, } /// The base collections from which we are going to get entities for use in /// `EntityQuery`; the result of the query comes from applying the query's /// filter and order etc. to the entities described in this collection. For /// a windowed collection order and range are applied to each individual /// window #[derive(Clone, Debug, PartialEq)] pub enum EntityCollection { /// Use all entities of the given types All(Vec<EntityType>), /// Use entities according to the windows. The set of entities that we /// apply order and range to is formed by taking all entities matching /// the window, and grouping them by the attribute of the window. Entities /// that have the same value in the `attribute` field of their window are /// grouped together. Note that it is possible to have one window for /// entity type `A` and attribute `a`, and another for entity type `B` and /// column `b`; they will be grouped by using `A.a` and `B.b` as the keys Window(Vec<EntityWindow>), } /// The type we use for block numbers. This has to be a signed integer type /// since Postgres does not support unsigned integer types. But 2G ought to /// be enough for everybody pub type BlockNumber = i32; pub const BLOCK_NUMBER_MAX: BlockNumber = std::i32::MAX; /// A query for entities in a store. /// /// Details of how query generation for `EntityQuery` works can be found /// at https://github.com/graphprotocol/rfcs/blob/master/engineering-plans/0001-graphql-query-prefetching.md #[derive(Clone, Debug)] pub struct EntityQuery { /// ID of the subgraph. pub subgraph_id: DeploymentHash, /// The block height at which to execute the query. Set this to /// `BLOCK_NUMBER_MAX` to run the query at the latest available block. /// If the subgraph uses JSONB storage, anything but `BLOCK_NUMBER_MAX` /// will cause an error as JSONB storage does not support querying anything /// but the latest block pub block: BlockNumber, /// The names of the entity types being queried. The result is the union /// (with repetition) of the query for each entity. pub collection: EntityCollection, /// Filter to filter entities by. pub filter: Option<EntityFilter>, /// How to order the entities pub order: EntityOrder, /// A range to limit the size of the result. pub range: EntityRange, /// Optional logger for anything related to this query pub logger: Option<Logger>, pub query_id: Option<String>, _force_use_of_new: (), } impl EntityQuery { pub fn new( subgraph_id: DeploymentHash, block: BlockNumber, collection: EntityCollection, ) -> Self { EntityQuery { subgraph_id, block, collection, filter: None, order: EntityOrder::Default, range: EntityRange::first(100), logger: None, query_id: None, _force_use_of_new: (), } } pub fn filter(mut self, filter: EntityFilter) -> Self { self.filter = Some(filter); self } pub fn order(mut self, order: EntityOrder) -> Self { self.order = order; self } pub fn range(mut self, range: EntityRange) -> Self { self.range = range; self } pub fn first(mut self, first: u32) -> Self { self.range.first = Some(first); self } pub fn skip(mut self, skip: u32) -> Self { self.range.skip = skip; self } pub fn simplify(mut self) -> Self { // If there is one window, with one id, in a direct relation to the // entities, we can simplify the query by changing the filter and // getting rid of the window if let EntityCollection::Window(windows) = &self.collection { if windows.len() == 1 { let window = windows.first().expect("we just checked"); if window.ids.len() == 1 { let id = window.ids.first().expect("we just checked"); if let EntityLink::Direct(attribute, _) = &window.link { let filter = match attribute { WindowAttribute::Scalar(name) => { EntityFilter::Equal(name.to_owned(), id.into()) } WindowAttribute::List(name) => { EntityFilter::Contains(name.to_owned(), Value::from(vec![id])) } }; self.filter = Some(filter.and_maybe(self.filter)); self.collection = EntityCollection::All(vec![window.child_type.to_owned()]); } } } } self } } /// Operation types that lead to entity changes. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)] #[serde(rename_all = "lowercase")] pub enum EntityChangeOperation { /// An entity was added or updated Set, /// An existing entity was removed. Removed, } /// Entity change events emitted by [Store](trait.Store.html) implementations. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)] pub enum EntityChange { Data { subgraph_id: DeploymentHash, /// Entity type name of the changed entity. entity_type: EntityType, }, Assignment { deployment: DeploymentLocator, operation: EntityChangeOperation, }, } impl EntityChange { pub fn for_data(key: EntityKey) -> Self { Self::Data { subgraph_id: key.subgraph_id, entity_type: key.entity_type, } } pub fn for_assignment(deployment: DeploymentLocator, operation: EntityChangeOperation) -> Self { Self::Assignment { deployment, operation, } } pub fn as_filter(&self) -> SubscriptionFilter { use EntityChange::*; match self { Data { subgraph_id, entity_type, .. } => SubscriptionFilter::Entities(subgraph_id.clone(), entity_type.clone()), Assignment { .. } => SubscriptionFilter::Assignment, } } } #[derive(Clone, Debug, Serialize, Deserialize)] /// The store emits `StoreEvents` to indicate that some entities have changed. /// For block-related data, at most one `StoreEvent` is emitted for each block /// that is processed. The `changes` vector contains the details of what changes /// were made, and to which entity. /// /// Since the 'subgraph of subgraphs' is special, and not directly related to /// any specific blocks, `StoreEvents` for it are generated as soon as they are /// written to the store. pub struct StoreEvent { // The tag is only there to make it easier to track StoreEvents in the // logs as they flow through the system pub tag: usize, pub changes: HashSet<EntityChange>, } impl<'a> FromIterator<&'a EntityModification> for StoreEvent { fn from_iter<I: IntoIterator<Item = &'a EntityModification>>(mods: I) -> Self { let changes: Vec<_> = mods .into_iter() .map(|op| { use self::EntityModification::*; match op { Insert { key, .. } | Overwrite { key, .. } | Remove { key } => { EntityChange::for_data(key.clone()) } } }) .collect(); StoreEvent::new(changes) } } impl StoreEvent { pub fn new(changes: Vec<EntityChange>) -> StoreEvent { static NEXT_TAG: AtomicUsize = AtomicUsize::new(0); let tag = NEXT_TAG.fetch_add(1, Ordering::Relaxed); let changes = changes.into_iter().collect(); StoreEvent { tag, changes } } /// Extend `ev1` with `ev2`. If `ev1` is `None`, just set it to `ev2` fn accumulate(logger: &Logger, ev1: &mut Option<StoreEvent>, ev2: StoreEvent) { if let Some(e) = ev1 { trace!(logger, "Adding changes to event"; "from" => ev2.tag, "to" => e.tag); e.changes.extend(ev2.changes); } else { *ev1 = Some(ev2); } } pub fn extend(mut self, other: StoreEvent) -> Self { self.changes.extend(other.changes); self } } impl fmt::Display for StoreEvent { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "StoreEvent[{}](changes: {})", self.tag, self.changes.len() ) } } impl PartialEq for StoreEvent { fn eq(&self, other: &StoreEvent) -> bool { // Ignore tag for equality self.changes == other.changes } } /// A `StoreEventStream` produces the `StoreEvents`. Various filters can be applied /// to it to reduce which and how many events are delivered by the stream. pub struct StoreEventStream<S> { source: S, } /// A boxed `StoreEventStream` pub type StoreEventStreamBox = StoreEventStream<Box<dyn Stream<Item = Arc<StoreEvent>, Error = ()> + Send>>; impl<S> Stream for StoreEventStream<S> where S: Stream<Item = Arc<StoreEvent>, Error = ()> + Send, { type Item = Arc<StoreEvent>; type Error = (); fn poll(&mut self) -> Result<Async<Option<Self::Item>>, Self::Error> { self.source.poll() } } impl<S> StoreEventStream<S> where S: Stream<Item = Arc<StoreEvent>, Error = ()> + Send + 'static, { // Create a new `StoreEventStream` from another such stream pub fn new(source: S) -> Self { StoreEventStream { source } } /// Filter a `StoreEventStream` by subgraph and entity. Only events that have /// at least one change to one of the given (subgraph, entity) combinations /// will be delivered by the filtered stream. pub fn filter_by_entities(self, filters: Vec<SubscriptionFilter>) -> StoreEventStreamBox { let source = self.source.filter(move |event| { event .changes .iter() .any(|change| filters.iter().any(|filter| filter.matches(change))) }); StoreEventStream::new(Box::new(source)) } /// Reduce the frequency with which events are generated while a /// subgraph deployment is syncing. While the given `deployment` is not /// synced yet, events from `source` are reported at most every /// `interval`. At the same time, no event is held for longer than /// `interval`. The `StoreEvents` that arrive during an interval appear /// on the returned stream as a single `StoreEvent`; the events are /// combined by using the maximum of all sources and the concatenation /// of the changes of the `StoreEvents` received during the interval. pub fn throttle_while_syncing( self, logger: &Logger, store: Arc<dyn QueryStore>, interval: Duration, ) -> StoreEventStreamBox { // We refresh the synced flag every SYNC_REFRESH_FREQ*interval to // avoid hitting the database too often to see if the subgraph has // been synced in the meantime. The only downside of this approach is // that we might continue throttling subscription updates for a little // bit longer than we really should static SYNC_REFRESH_FREQ: u32 = 4; // Check whether a deployment is marked as synced in the store let mut synced = store.is_deployment_synced().unwrap_or(false); let synced_check_interval = interval.checked_mul(SYNC_REFRESH_FREQ).unwrap(); let mut synced_last_refreshed = Instant::now(); let mut pending_event: Option<StoreEvent> = None; let mut source = self.source.fuse(); let mut had_err = false; let mut delay = tokio::time::delay_for(interval) .unit_error() .boxed() .compat(); let logger = logger.clone(); let source = Box::new(poll_fn(move || -> Poll<Option<Arc<StoreEvent>>, ()> { if had_err { // We had an error the last time through, but returned the pending // event first. Indicate the error now had_err = false; return Err(()); } if !synced && synced_last_refreshed.elapsed() > synced_check_interval { synced = store.is_deployment_synced().unwrap_or(false); synced_last_refreshed = Instant::now(); } if synced { return source.poll(); } // Check if interval has passed since the last time we sent something. // If it has, start a new delay timer let should_send = match futures::future::Future::poll(&mut delay) { Ok(Async::NotReady) => false, // Timer errors are harmless. Treat them as if the timer had // become ready. Ok(Async::Ready(())) | Err(_) => { delay = tokio::time::delay_for(interval) .unit_error() .boxed() .compat(); true } }; // Get as many events as we can off of the source stream loop { match source.poll() { Ok(Async::NotReady) => { if should_send && pending_event.is_some() { let event = pending_event.take().map(|event| Arc::new(event)); return Ok(Async::Ready(event)); } else { return Ok(Async::NotReady); } } Ok(Async::Ready(None)) => { let event = pending_event.take().map(|event| Arc::new(event)); return Ok(Async::Ready(event)); } Ok(Async::Ready(Some(event))) => { StoreEvent::accumulate(&logger, &mut pending_event, (*event).clone()); } Err(()) => { // Before we report the error, deliver what we have accumulated so far. // We will report the error the next time poll() is called if pending_event.is_some() { had_err = true; let event = pending_event.take().map(|event| Arc::new(event)); return Ok(Async::Ready(event)); } else { return Err(()); } } }; } })); StoreEventStream::new(source) } } /// An entity operation that can be transacted into the store. #[derive(Clone, Debug, PartialEq)] pub enum EntityOperation { /// Locates the entity specified by `key` and sets its attributes according to the contents of /// `data`. If no entity exists with this key, creates a new entity. Set { key: EntityKey, data: Entity }, /// Removes an entity with the specified key, if one exists. Remove { key: EntityKey }, } #[derive(Error, Debug)] pub enum StoreError { #[error("store error: {0}")] Unknown(Error), #[error( "tried to set entity of type `{0}` with ID \"{1}\" but an entity of type `{2}`, \ which has an interface in common with `{0}`, exists with the same ID" )] ConflictingId(String, String, String), // (entity, id, conflicting_entity) #[error("unknown field '{0}'")] UnknownField(String), #[error("unknown table '{0}'")] UnknownTable(String), #[error("malformed directive '{0}'")] MalformedDirective(String), #[error("query execution failed: {0}")] QueryExecutionError(String), #[error("invalid identifier: {0}")] InvalidIdentifier(String), #[error( "subgraph `{0}` has already processed block `{1}`; \ there are most likely two (or more) nodes indexing this subgraph" )] DuplicateBlockProcessing(DeploymentHash, BlockNumber), /// An internal error where we expected the application logic to enforce /// some constraint, e.g., that subgraph names are unique, but found that /// constraint to not hold #[error("internal constraint violated: {0}")] ConstraintViolation(String), #[error("deployment not found: {0}")] DeploymentNotFound(String), #[error("shard not found: {0} (this usually indicates a misconfiguration)")] UnknownShard(String), #[error("Fulltext search not yet deterministic")] FulltextSearchNonDeterministic, #[error("operation was canceled")] Canceled, } // Convenience to report a constraint violation #[macro_export] macro_rules! constraint_violation { ($msg:expr) => {{ StoreError::ConstraintViolation(format!("{}", $msg)) }}; ($fmt:expr, $($arg:tt)*) => {{ StoreError::ConstraintViolation(format!($fmt, $($arg)*)) }} } impl From<::diesel::result::Error> for StoreError { fn from(e: ::diesel::result::Error) -> Self { StoreError::Unknown(e.into()) } } impl From<::diesel::r2d2::PoolError> for StoreError { fn from(e: ::diesel::r2d2::PoolError) -> Self { StoreError::Unknown(e.into()) } } impl From<Error> for StoreError { fn from(e: Error) -> Self { StoreError::Unknown(e) } } impl From<serde_json::Error> for StoreError { fn from(e: serde_json::Error) -> Self { StoreError::Unknown(e.into()) } } impl From<QueryExecutionError> for StoreError { fn from(e: QueryExecutionError) -> Self { StoreError::QueryExecutionError(e.to_string()) } } pub struct StoredDynamicDataSource { pub name: String, pub source: Source, pub context: Option<String>, pub creation_block: Option<BlockNumber>, } pub trait SubscriptionManager: Send + Sync + 'static { /// Subscribe to changes for specific subgraphs and entities. /// /// Returns a stream of store events that match the input arguments. fn subscribe(&self, entities: Vec<SubscriptionFilter>) -> StoreEventStreamBox; } /// An internal identifer for the specific instance of a deployment. The /// identifier only has meaning in the context of a specific instance of /// graph-node. Only store code should ever construct or consume it; all /// other code passes it around as an opaque token. #[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)] pub struct DeploymentId(pub i32); impl Display for DeploymentId { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { write!(f, "{}", self.0) } } impl DeploymentId { pub fn new(id: i32) -> Self { Self(id) } } /// A unique identifier for a deployment that specifies both its external /// identifier (`hash`) and its unique internal identifier (`id`) which /// ensures we are talking about a unique location for the deployment's data /// in the store #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)] pub struct DeploymentLocator { pub id: DeploymentId, pub hash: DeploymentHash, } impl CheapClone for DeploymentLocator {} impl slog::Value for DeploymentLocator { fn serialize( &self, record: &slog::Record, key: slog::Key, serializer: &mut dyn slog::Serializer, ) -> slog::Result { slog::Value::serialize(&self.to_string(), record, key, serializer) } } impl DeploymentLocator { pub fn new(id: DeploymentId, hash: DeploymentHash) -> Self { Self { id, hash } } } impl Display for DeploymentLocator { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}[{}]", self.hash, self.id) } } /// Common trait for store implementations. #[async_trait] pub trait SubgraphStore: Send + Sync + 'static { /// Find the reverse of keccak256 for `hash` through looking it up in the /// rainbow table. fn find_ens_name(&self, _hash: &str) -> Result<Option<String>, QueryExecutionError>; /// Check if the store is accepting queries for the specified subgraph. /// May return true even if the specified subgraph is not currently assigned to an indexing /// node, as the store will still accept queries. fn is_deployed(&self, id: &DeploymentHash) -> Result<bool, Error>; /// Create a new deployment for the subgraph `name`. If the deployment /// already exists (as identified by the `schema.id`), reuse that, otherwise /// create a new deployment, and point the current or pending version of /// `name` at it, depending on the `mode` fn create_subgraph_deployment( &self, name: SubgraphName, schema: &Schema, deployment: SubgraphDeploymentEntity, node_id: NodeId, network: String, mode: SubgraphVersionSwitchingMode, ) -> Result<DeploymentLocator, StoreError>; /// Create a new subgraph with the given name. If one already exists, use /// the existing one. Return the `id` of the newly created or existing /// subgraph fn create_subgraph(&self, name: SubgraphName) -> Result<String, StoreError>; /// Remove a subgraph and all its versions; if deployments that were used /// by this subgraph do not need to be indexed anymore, also remove /// their assignment, but keep the deployments themselves around fn remove_subgraph(&self, name: SubgraphName) -> Result<(), StoreError>; /// Assign the subgraph with `id` to the node `node_id`. If there is no /// assignment for the given deployment, report an error. fn reassign_subgraph( &self, deployment: &DeploymentLocator, node_id: &NodeId, ) -> Result<(), StoreError>; fn assigned_node(&self, deployment: &DeploymentLocator) -> Result<Option<NodeId>, StoreError>; fn assignments(&self, node: &NodeId) -> Result<Vec<DeploymentLocator>, StoreError>; /// Return `true` if a subgraph `name` exists, regardless of whether the /// subgraph has any deployments attached to it fn subgraph_exists(&self, name: &SubgraphName) -> Result<bool, StoreError>; /// Return the GraphQL schema supplied by the user fn input_schema(&self, subgraph_id: &DeploymentHash) -> Result<Arc<Schema>, StoreError>; /// Return the GraphQL schema that was derived from the user's schema by /// adding a root query type etc. to it fn api_schema(&self, subgraph_id: &DeploymentHash) -> Result<Arc<ApiSchema>, StoreError>; /// Return a `WritableStore` that is used for indexing subgraphs. Only /// code that is part of indexing a subgraph should ever use this. fn writable( &self, deployment: &DeploymentLocator, ) -> Result<Arc<dyn WritableStore>, StoreError>; /// The network indexer does not follow the normal flow of how subgraphs /// are indexed, and therefore needs a special way to get a /// `WritableStore`. This method should not be used outside of that, and /// `writable` should be used instead fn writable_for_network_indexer( &self, id: &DeploymentHash, ) -> Result<Arc<dyn WritableStore>, StoreError>; /// Return the minimum block pointer of all deployments with this `id` /// that we would use to query or copy from; in particular, this will /// ignore any instances of this deployment that are in the process of /// being set up fn least_block_ptr(&self, id: &DeploymentHash) -> Result<Option<BlockPtr>, Error>; /// Find the deployment locators for the subgraph with the given hash fn locators(&self, hash: &str) -> Result<Vec<DeploymentLocator>, StoreError>; } #[async_trait] pub trait WritableStore: Send + Sync + 'static { /// Get a pointer to the most recently processed block in the subgraph. fn block_ptr(&self) -> Result<Option<BlockPtr>, Error>; /// Start an existing subgraph deployment. fn start_subgraph_deployment(&self, logger: &Logger) -> Result<(), StoreError>; /// Revert the entity changes from a single block atomically in the store, and update the /// subgraph block pointer to `block_ptr_to`. /// /// `block_ptr_to` must point to the parent block of the subgraph block pointer. fn revert_block_operations(&self, block_ptr_to: BlockPtr) -> Result<(), StoreError>; /// Remove the fatal error from a subgraph and check if it is healthy or unhealthy. fn unfail(&self) -> Result<(), StoreError>; /// Set subgraph status to failed with the given error as the cause. async fn fail_subgraph(&self, error: SubgraphError) -> Result<(), StoreError>; fn supports_proof_of_indexing<'a>(self: Arc<Self>) -> DynTryFuture<'a, bool>; /// Looks up an entity using the given store key at the latest block. fn get(&self, key: EntityKey) -> Result<Option<Entity>, QueryExecutionError>; /// Transact the entity changes from a single block atomically into the store, and update the /// subgraph block pointer to `block_ptr_to`. /// /// `block_ptr_to` must point to a child block of the current subgraph block pointer. fn transact_block_operations( &self, block_ptr_to: BlockPtr, mods: Vec<EntityModification>, stopwatch: StopwatchMetrics, data_sources: Vec<StoredDynamicDataSource>, deterministic_errors: Vec<SubgraphError>, ) -> Result<(), StoreError>; /// Look up multiple entities as of the latest block. Returns a map of /// entities by type. fn get_many( &self, ids_for_type: BTreeMap<&EntityType, Vec<&str>>, ) -> Result<BTreeMap<EntityType, Vec<Entity>>, StoreError>; /// The deployment `id` finished syncing, mark it as synced in the database /// and promote it to the current version in the subgraphs where it was the /// pending version so far fn deployment_synced(&self) -> Result<(), Error>; /// Return true if the deployment with the given id is fully synced, /// and return false otherwise. Errors from the store are passed back up fn is_deployment_synced(&self) -> Result<bool, Error>; fn unassign_subgraph(&self) -> Result<(), StoreError>; /// Load the dynamic data sources for the given deployment async fn load_dynamic_data_sources(&self) -> Result<Vec<StoredDynamicDataSource>, StoreError>; } #[async_trait] pub trait QueryStoreManager: Send + Sync + 'static { /// Get a new `QueryStore`. A `QueryStore` is tied to a DB replica, so if Graph Node is /// configured to use secondary DB servers the queries will be distributed between servers. /// /// The query store is specific to a deployment, and `id` must indicate /// which deployment will be queried. It is not possible to use the id of the /// metadata subgraph, though the resulting store can be used to query /// metadata about the deployment `id` (but not metadata about other deployments). /// /// If `for_subscription` is true, the main replica will always be used. async fn query_store( &self, target: QueryTarget, for_subscription: bool, ) -> Result<Arc<dyn QueryStore + Send + Sync>, QueryExecutionError>; } mock! { pub Store { fn get_many_mock<'a>( &self, _ids_for_type: BTreeMap<&'a EntityType, Vec<&'a str>>, ) -> Result<BTreeMap<EntityType, Vec<Entity>>, StoreError>; } } // The type that the connection pool uses to track wait times for // connection checkouts pub type PoolWaitStats = Arc<RwLock<MovingStats>>; // The store trait must be implemented manually because mockall does not support async_trait, nor borrowing from arguments. #[async_trait] impl SubgraphStore for MockStore { fn find_ens_name(&self, _hash: &str) -> Result<Option<String>, QueryExecutionError> { unimplemented!() } fn create_subgraph_deployment( &self, _: SubgraphName, _: &Schema, _: SubgraphDeploymentEntity, _: NodeId, _: String, _: SubgraphVersionSwitchingMode, ) -> Result<DeploymentLocator, StoreError> { unimplemented!() } fn create_subgraph(&self, _: SubgraphName) -> Result<String, StoreError> { unimplemented!() } fn remove_subgraph(&self, _: SubgraphName) -> Result<(), StoreError> { unimplemented!() } fn reassign_subgraph(&self, _: &DeploymentLocator, _: &NodeId) -> Result<(), StoreError> { unimplemented!() } fn assigned_node(&self, _: &DeploymentLocator) -> Result<Option<NodeId>, StoreError> { unimplemented!() } fn assignments(&self, _: &NodeId) -> Result<Vec<DeploymentLocator>, StoreError> { unimplemented!() } fn subgraph_exists(&self, _: &SubgraphName) -> Result<bool, StoreError> { unimplemented!() } fn input_schema(&self, _: &DeploymentHash) -> Result<Arc<Schema>, StoreError> { unimplemented!() } fn api_schema(&self, _: &DeploymentHash) -> Result<Arc<ApiSchema>, StoreError> { unimplemented!() } fn writable(&self, _: &DeploymentLocator) -> Result<Arc<dyn WritableStore>, StoreError> { Ok(Arc::new(MockStore::new())) } fn is_deployed(&self, _: &DeploymentHash) -> Result<bool, Error> { unimplemented!() } fn least_block_ptr(&self, _: &DeploymentHash) -> Result<Option<BlockPtr>, Error> { unimplemented!() } fn writable_for_network_indexer( &self, _: &DeploymentHash, ) -> Result<Arc<dyn WritableStore>, StoreError> { unimplemented!() } fn locators(&self, _: &str) -> Result<Vec<DeploymentLocator>, StoreError> { unimplemented!() } } // The store trait must be implemented manually because mockall does not support async_trait, nor borrowing from arguments. #[async_trait] impl WritableStore for MockStore { fn block_ptr(&self) -> Result<Option<BlockPtr>, Error> { unimplemented!() } fn start_subgraph_deployment(&self, _: &Logger) -> Result<(), StoreError> { unimplemented!() } fn revert_block_operations(&self, _: BlockPtr) -> Result<(), StoreError> { unimplemented!() } fn unfail(&self) -> Result<(), StoreError> { unimplemented!() } async fn fail_subgraph(&self, _: SubgraphError) -> Result<(), StoreError> { unimplemented!() } fn supports_proof_of_indexing<'a>(self: Arc<Self>) -> DynTryFuture<'a, bool> { unimplemented!() } fn get(&self, _: EntityKey) -> Result<Option<Entity>, QueryExecutionError> { unimplemented!() } fn transact_block_operations( &self, _: BlockPtr, _: Vec<EntityModification>, _: StopwatchMetrics, _: Vec<StoredDynamicDataSource>, _: Vec<SubgraphError>, ) -> Result<(), StoreError> { unimplemented!() } fn get_many( &self, ids_for_type: BTreeMap<&EntityType, Vec<&str>>, ) -> Result<BTreeMap<EntityType, Vec<Entity>>, StoreError> { self.get_many_mock(ids_for_type) } fn is_deployment_synced(&self) -> Result<bool, Error> { unimplemented!() } fn unassign_subgraph(&self) -> Result<(), StoreError> { unimplemented!() } async fn load_dynamic_data_sources(&self) -> Result<Vec<StoredDynamicDataSource>, StoreError> { unimplemented!() } fn deployment_synced(&self) -> Result<(), Error> { unimplemented!() } } pub trait BlockStore: Send + Sync + 'static { type ChainStore: ChainStore; fn chain_store(&self, network: &str) -> Option<Arc<Self::ChainStore>>; } pub trait CallCache: Send + Sync + 'static { type EthereumCallCache: EthereumCallCache; fn ethereum_call_cache(&self, network: &str) -> Option<Arc<Self::EthereumCallCache>>; } /// Common trait for blockchain store implementations. #[automock] #[async_trait] pub trait ChainStore: Send + Sync + 'static { /// Get a pointer to this blockchain's genesis block. fn genesis_block_ptr(&self) -> Result<BlockPtr, Error>; /// Insert a block into the store (or update if they are already present). async fn upsert_block(&self, block: EthereumBlock) -> Result<(), Error>; fn upsert_light_blocks(&self, blocks: Vec<LightEthereumBlock>) -> Result<(), Error>; /// Try to update the head block pointer to the block with the highest block number. /// /// Only updates pointer if there is a block with a higher block number than the current head /// block, and the `ancestor_count` most recent ancestors of that block are in the store. /// Note that this means if the Ethereum node returns a different "latest block" with a /// different hash but same number, we do not update the chain head pointer. /// This situation can happen on e.g. Infura where requests are load balanced across many /// Ethereum nodes, in which case it's better not to continuously revert and reapply the latest /// blocks. /// /// If the pointer was updated, returns `Ok(vec![])`, and fires a HeadUpdateEvent. /// /// If no block has a number higher than the current head block, returns `Ok(vec![])`. /// /// If the candidate new head block had one or more missing ancestors, returns /// `Ok(missing_blocks)`, where `missing_blocks` is a nonexhaustive list of missing blocks. async fn attempt_chain_head_update( self: Arc<Self>, ancestor_count: BlockNumber, ) -> Result<Option<H256>, Error>; /// Get the current head block pointer for this chain. /// Any changes to the head block pointer will be to a block with a larger block number, never /// to a block with a smaller or equal block number. /// /// The head block pointer will be None on initial set up. fn chain_head_ptr(&self) -> Result<Option<BlockPtr>, Error>; /// Returns the blocks present in the store. fn blocks(&self, hashes: Vec<H256>) -> Result<Vec<LightEthereumBlock>, Error>; /// Get the `offset`th ancestor of `block_hash`, where offset=0 means the block matching /// `block_hash` and offset=1 means its parent. Returns None if unable to complete due to /// missing blocks in the chain store. /// /// Returns an error if the offset would reach past the genesis block. fn ancestor_block( &self, block_ptr: BlockPtr, offset: BlockNumber, ) -> Result<Option<EthereumBlock>, Error>; /// Remove old blocks from the cache we maintain in the database and /// return a pair containing the number of the oldest block retained /// and the number of blocks deleted. /// We will never remove blocks that are within `ancestor_count` of /// the chain head. fn cleanup_cached_blocks( &self, ancestor_count: BlockNumber, ) -> Result<Option<(BlockNumber, usize)>, Error>; /// Return the hashes of all blocks with the given number fn block_hashes_by_block_number(&self, number: BlockNumber) -> Result<Vec<H256>, Error>; /// Confirm that block number `number` has hash `hash` and that the store /// may purge any other blocks with that number fn confirm_block_hash(&self, number: BlockNumber, hash: &H256) -> Result<usize, Error>; /// Find the block with `block_hash` and return the network name and number fn block_number(&self, block_hash: H256) -> Result<Option<(String, BlockNumber)>, StoreError>; } pub trait EthereumCallCache: Send + Sync + 'static { /// Cached return value. fn get_call( &self, contract_address: ethabi::Address, encoded_call: &[u8], block: BlockPtr, ) -> Result<Option<Vec<u8>>, Error>; // Add entry to the cache. fn set_call( &self, contract_address: ethabi::Address, encoded_call: &[u8], block: BlockPtr, return_value: &[u8], ) -> Result<(), Error>; } /// Store operations used when serving queries for a specific deployment #[async_trait] pub trait QueryStore: Send + Sync { fn find_query_values( &self, query: EntityQuery, ) -> Result<Vec<BTreeMap<String, q::Value>>, QueryExecutionError>; fn is_deployment_synced(&self) -> Result<bool, Error>; fn block_ptr(&self) -> Result<Option<BlockPtr>, Error>; fn block_number(&self, block_hash: H256) -> Result<Option<BlockNumber>, StoreError>; fn wait_stats(&self) -> &PoolWaitStats; /// If `block` is `None`, assumes the latest block. async fn has_non_fatal_errors(&self, block: Option<BlockNumber>) -> Result<bool, StoreError>; /// Find the current state for the subgraph deployment `id` and /// return details about it needed for executing queries async fn deployment_state(&self) -> Result<DeploymentState, QueryExecutionError>; fn api_schema(&self) -> Result<Arc<ApiSchema>, QueryExecutionError>; fn network_name(&self) -> &str; } /// A view of the store that can provide information about the indexing status /// of any subgraph and any deployment pub trait StatusStore: Send + Sync + 'static { fn status(&self, filter: status::Filter) -> Result<Vec<status::Info>, StoreError>; /// Support for the explorer-specific API fn version_info(&self, version_id: &str) -> Result<VersionInfo, StoreError>; /// Support for the explorer-specific API; note that `subgraph_id` must be /// the id of an entry in `subgraphs.subgraph`, not that of a deployment. /// The return values are the ids of the `subgraphs.subgraph_version` for /// the current and pending versions of the subgraph fn versions_for_subgraph_id( &self, subgraph_id: &str, ) -> Result<(Option<String>, Option<String>), StoreError>; /// A value of None indicates that the table is not available. Re-deploying /// the subgraph fixes this. It is undesirable to force everything to /// re-sync from scratch, so existing deployments will continue without a /// Proof of Indexing. Once all subgraphs have been re-deployed the Option /// can be removed. fn get_proof_of_indexing<'a>( self: Arc<Self>, subgraph_id: &'a DeploymentHash, indexer: &'a Option<Address>, block: BlockPtr, ) -> DynTryFuture<'a, Option<[u8; 32]>>; } /// An entity operation that can be transacted into the store; as opposed to /// `EntityOperation`, we already know whether a `Set` should be an `Insert` /// or `Update` #[derive(Clone, Debug, PartialEq, Eq)] pub enum EntityModification { /// Insert the entity Insert { key: EntityKey, data: Entity }, /// Update the entity by overwriting it Overwrite { key: EntityKey, data: Entity }, /// Remove the entity Remove { key: EntityKey }, } impl EntityModification { pub fn entity_key(&self) -> &EntityKey { use EntityModification::*; match self { Insert { key, .. } | Overwrite { key, .. } | Remove { key } => key, } } pub fn is_remove(&self) -> bool { match self { EntityModification::Remove { .. } => true, _ => false, } } } /// A representation of entity operations that can be accumulated. #[derive(Debug, Clone)] enum EntityOp { Remove, Update(Entity), Overwrite(Entity), } impl EntityOp { fn apply_to(self, entity: Option<Entity>) -> Option<Entity> { use EntityOp::*; match (self, entity) { (Remove, _) => None, (Overwrite(new), _) | (Update(new), None) => Some(new), (Update(updates), Some(mut entity)) => { entity.merge_remove_null_fields(updates); Some(entity) } } } fn accumulate(&mut self, next: EntityOp) { use EntityOp::*; let update = match next { // Remove and Overwrite ignore the current value. Remove | Overwrite(_) => { *self = next; return; } Update(update) => update, }; // We have an update, apply it. match self { // This is how `Overwrite` is constructed, by accumulating `Update` onto `Remove`. Remove => *self = Overwrite(update), Update(current) | Overwrite(current) => current.merge(update), } } } /// A cache for entities from the store that provides the basic functionality /// needed for the store interactions in the host exports. This struct tracks /// how entities are modified, and caches all entities looked up from the /// store. The cache makes sure that /// (1) no entity appears in more than one operation /// (2) only entities that will actually be changed from what they /// are in the store are changed pub struct EntityCache { /// The state of entities in the store. An entry of `None` /// means that the entity is not present in the store current: LfuCache<EntityKey, Option<Entity>>, /// The accumulated changes to an entity. updates: HashMap<EntityKey, EntityOp>, // Updates for a currently executing handler. handler_updates: HashMap<EntityKey, EntityOp>, // Marks whether updates should go in `handler_updates`. in_handler: bool, data_sources: Vec<StoredDynamicDataSource>, /// The store is only used to read entities. pub store: Arc<dyn WritableStore>, } impl Debug for EntityCache { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("EntityCache") .field("current", &self.current) .field("updates", &self.updates) .finish() } } pub struct ModificationsAndCache { pub modifications: Vec<EntityModification>, pub data_sources: Vec<StoredDynamicDataSource>, pub entity_lfu_cache: LfuCache<EntityKey, Option<Entity>>, } impl EntityCache { pub fn new(store: Arc<dyn WritableStore>) -> Self { Self { current: LfuCache::new(), updates: HashMap::new(), handler_updates: HashMap::new(), in_handler: false, data_sources: vec![], store, } } pub fn with_current( store: Arc<dyn WritableStore>, current: LfuCache<EntityKey, Option<Entity>>, ) -> EntityCache { EntityCache { current, updates: HashMap::new(), handler_updates: HashMap::new(), in_handler: false, data_sources: vec![], store, } } pub(crate) fn enter_handler(&mut self) { assert!(!self.in_handler); self.in_handler = true; } pub(crate) fn exit_handler(&mut self) { assert!(self.in_handler); self.in_handler = false; // Apply all handler updates to the main `updates`. let handler_updates = Vec::from_iter(self.handler_updates.drain()); for (key, op) in handler_updates { self.entity_op(key, op) } } pub(crate) fn exit_handler_and_discard_changes(&mut self) { assert!(self.in_handler); self.in_handler = false; self.handler_updates.clear(); } pub fn get(&mut self, key: &EntityKey) -> Result<Option<Entity>, QueryExecutionError> { // Get the current entity, apply any updates from `updates`, then from `handler_updates`. let mut entity = self.current.get_entity(&*self.store, &key)?; if let Some(op) = self.updates.get(&key).cloned() { entity = op.apply_to(entity) } if let Some(op) = self.handler_updates.get(&key).cloned() { entity = op.apply_to(entity) } Ok(entity) } pub fn remove(&mut self, key: EntityKey) { self.entity_op(key, EntityOp::Remove); } pub fn set(&mut self, key: EntityKey, entity: Entity) { self.entity_op(key, EntityOp::Update(entity)) } pub fn append(&mut self, operations: Vec<EntityOperation>) { assert!(!self.in_handler); for operation in operations { match operation { EntityOperation::Set { key, data } => { self.entity_op(key, EntityOp::Update(data)); } EntityOperation::Remove { key } => { self.entity_op(key, EntityOp::Remove); } } } } /// Add a dynamic data source pub fn add_data_source<C: Blockchain>(&mut self, data_source: &impl DataSource<C>) { self.data_sources .push(data_source.as_stored_dynamic_data_source()); } fn entity_op(&mut self, key: EntityKey, op: EntityOp) { use std::collections::hash_map::Entry; let updates = match self.in_handler { true => &mut self.handler_updates, false => &mut self.updates, }; match updates.entry(key) { Entry::Vacant(entry) => { entry.insert(op); } Entry::Occupied(mut entry) => entry.get_mut().accumulate(op), } } pub(crate) fn extend(&mut self, other: EntityCache) { assert!(!other.in_handler); self.current.extend(other.current); for (key, op) in other.updates { self.entity_op(key, op); } } /// Return the changes that have been made via `set` and `remove` as /// `EntityModification`, making sure to only produce one when a change /// to the current state is actually needed. /// /// Also returns the updated `LfuCache`. pub fn as_modifications(mut self) -> Result<ModificationsAndCache, QueryExecutionError> { assert!(!self.in_handler); // The first step is to make sure all entities being set are in `self.current`. // For each subgraph, we need a map of entity type to missing entity ids. let missing = self .updates .keys() .filter(|key| !self.current.contains_key(key)); let mut missing_by_subgraph: BTreeMap<_, BTreeMap<&EntityType, Vec<&str>>> = BTreeMap::new(); for key in missing { missing_by_subgraph .entry(&key.subgraph_id) .or_default() .entry(&key.entity_type) .or_default() .push(&key.entity_id); } for (subgraph_id, keys) in missing_by_subgraph { for (entity_type, entities) in self.store.get_many(keys)? { for entity in entities { let key = EntityKey { subgraph_id: subgraph_id.clone(), entity_type: entity_type.clone(), entity_id: entity.id().unwrap(), }; self.current.insert(key, Some(entity)); } } } let mut mods = Vec::new(); for (key, update) in self.updates { use EntityModification::*; let current = self.current.remove(&key).and_then(|entity| entity); let modification = match (current, update) { // Entity was created (None, EntityOp::Update(updates)) | (None, EntityOp::Overwrite(updates)) => { // Merging with an empty entity removes null fields. let mut data = Entity::new(); data.merge_remove_null_fields(updates); self.current.insert(key.clone(), Some(data.clone())); Some(Insert { key, data }) } // Entity may have been changed (Some(current), EntityOp::Update(updates)) => { let mut data = current.clone(); data.merge_remove_null_fields(updates); self.current.insert(key.clone(), Some(data.clone())); if current != data { Some(Overwrite { key, data }) } else { None } } // Entity was removed and then updated, so it will be overwritten (Some(current), EntityOp::Overwrite(data)) => { self.current.insert(key.clone(), Some(data.clone())); if current != data { Some(Overwrite { key, data }) } else { None } } // Existing entity was deleted (Some(_), EntityOp::Remove) => { self.current.insert(key.clone(), None); Some(Remove { key }) } // Entity was deleted, but it doesn't exist in the store (None, EntityOp::Remove) => None, }; if let Some(modification) = modification { mods.push(modification) } } Ok(ModificationsAndCache { modifications: mods, data_sources: self.data_sources, entity_lfu_cache: self.current, }) } } impl LfuCache<EntityKey, Option<Entity>> { // Helper for cached lookup of an entity. fn get_entity( &mut self, store: &(impl WritableStore + ?Sized), key: &EntityKey, ) -> Result<Option<Entity>, QueryExecutionError> { match self.get(&key) { None => { let mut entity = store.get(key.clone())?; if let Some(entity) = &mut entity { // `__typename` is for queries not for mappings. entity.remove("__typename"); } self.insert(key.clone(), entity.clone()); Ok(entity) } Some(data) => Ok(data.to_owned()), } } }
34.943827
123
0.612569
891e9eb2e125279c2b972d71b889055d14001167
978
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use common_exception::exception::Result; use crate::NodeInfo; #[test] fn test_node_info_ip_port() -> Result<()> { let n = NodeInfo { id: "".to_string(), cpu_nums: 1, version: 1, flight_address: "1.2.3.4:123".to_string(), }; let (ip, port) = n.ip_port()?; assert_eq!("1.2.3.4".to_string(), ip); assert_eq!(123, port); Ok(()) }
28.764706
75
0.668712
e451eaf73163df2360f8087746592e5f31dcb170
11,923
use std::fmt; #[cfg(unix)] use std::collections::HashSet; use futures::stream::Stream; use serde::{Deserialize, Serialize}; /// A Unix signal for triggering graceful shutdown. /// /// Each variant corresponds to a Unix process signal which can be used to /// trigger a graceful shutdown. See [`Shutdown`] for details. /// /// ## (De)serialization /// /// A `Sig` variant serializes and deserializes as a lowercase string equal to /// the name of the variant: `"alrm"` for [`Sig::Alrm`], `"chld"` for /// [`Sig::Chld`], and so on. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Sig { /// The `SIGALRM` Unix signal. Alrm, /// The `SIGCHLD` Unix signal. Chld, /// The `SIGHUP` Unix signal. Hup, /// The `SIGINT` Unix signal. Int, /// The `SIGIO` Unix signal. Io, /// The `SIGPIPE` Unix signal. Pipe, /// The `SIGQUIT` Unix signal. Quit, /// The `SIGTERM` Unix signal. Term, /// The `SIGUSR1` Unix signal. Usr1, /// The `SIGUSR2` Unix signal. Usr2 } impl fmt::Display for Sig { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let s = match self { Sig::Alrm => "SIGALRM", Sig::Chld => "SIGCHLD", Sig::Hup => "SIGHUP", Sig::Int => "SIGINT", Sig::Io => "SIGIO", Sig::Pipe => "SIGPIPE", Sig::Quit => "SIGQUIT", Sig::Term => "SIGTERM", Sig::Usr1 => "SIGUSR1", Sig::Usr2 => "SIGUSR2", }; s.fmt(f) } } /// Graceful shutdown configuration. /// /// # Summary /// /// This structure configures when and how graceful shutdown occurs. The `ctrlc` /// and `signals` properties control _when_ and the `grace` and `mercy` /// properties control _how_. /// /// When a shutdown is triggered by an externally or internally initiated /// [`Shutdown::notify()`], Rocket allows application I/O to make progress for /// at most `grace` seconds before initiating connection-level shutdown. /// Connection shutdown forcibly terminates _application_ I/O, but connections /// are allowed an additional `mercy` seconds to shutdown before being /// forcefully terminated. This implies that a _cooperating_ and active remote /// client maintaining an open connection can stall shutdown for at most `grace` /// seconds, while an _uncooperative_ remote client can stall shutdown for at /// most `grace + mercy` seconds. /// /// # Triggers /// /// _All_ graceful shutdowns are initiated via [`Shutdown::notify()`]. Rocket /// can be configured to call [`Shutdown::notify()`] automatically on certain /// conditions, specified via the `ctrlc` and `signals` properties of this /// structure. More specifically, if `ctrlc` is `true` (the default), `ctrl-c` /// (`SIGINT`) initiates a server shutdown, and on Unix, `signals` specifies a /// list of IPC signals that trigger a shutdown (`["term"]` by default). /// /// [`Shutdown::notify()`]: crate::Shutdown::notify() /// /// # Grace Period /// /// Once a shutdown is triggered, Rocket stops accepting new connections and /// waits at most `grace` seconds before initiating connection shutdown. /// Applications can `await` the [`Shutdown`](crate::Shutdown) future to detect /// a shutdown and cancel any server-initiated I/O, such as from [infinite /// responders](crate::response::stream#graceful-shutdown), to avoid abrupt I/O /// cancellation. /// /// # Mercy Period /// /// After the grace period has elapsed, Rocket initiates connection shutdown, /// allowing connection-level I/O termination such as TLS's `close_notify` to /// proceed nominally. Rocket waits at most `mercy` seconds for connections to /// shutdown before forcefully terminating all connections. /// /// # Runaway I/O /// /// If tasks are _still_ executing after both periods _and_ a Rocket configured /// async runtime is in use, Rocket waits an unspecified amount of time (not to /// exceed 1s) and forcefully exits the current process with an exit code of /// `1`. This guarantees that the server process terminates, prohibiting /// uncooperative, runaway I/O from preventing shutdown altogether. /// /// A "Rocket configured runtime" is one started by the `#[rocket::main]` and /// `#[launch]` attributes. Rocket _never_ forcefully terminates a server that /// is running inside of a custom runtime. A server that creates its own async /// runtime must take care to terminate itself if tasks it spawns fail to /// cooperate. /// /// Under normal circumstances, forced termination should never occur. No use of /// "normal" cooperative I/O (that is, via `.await` or `task::spawn()`) should /// trigger abrupt termination. Instead, forced cancellation is intended to /// prevent _buggy_ code, such as an unintended infinite loop or unknown use of /// blocking I/O, from preventing shutdown. /// /// This behavior can be disabled by setting [`Shutdown::force`] to `false`. /// /// # Example /// /// As with all Rocket configuration options, when using the default /// [`Config::figment()`](crate::Config::figment()), `Shutdown` can be /// configured via a `Rocket.toml` file. As always, defaults are provided /// (documented below), and thus configuration only needs to provided to change /// defaults. /// /// ```rust /// # use rocket::figment::{Figment, providers::{Format, Toml}}; /// use rocket::Config; /// /// // If these are the contents of `Rocket.toml`... /// # let toml = Toml::string(r#" /// [default.shutdown] /// ctrlc = false /// signals = ["term", "hup"] /// grace = 10 /// mercy = 5 /// # force = false /// # "#).nested(); /// /// // The config parses as follows: /// # let config = Config::from(Figment::from(Config::debug_default()).merge(toml)); /// assert_eq!(config.shutdown.ctrlc, false); /// assert_eq!(config.shutdown.grace, 10); /// assert_eq!(config.shutdown.mercy, 5); /// # assert_eq!(config.shutdown.force, false); /// /// # #[cfg(unix)] { /// use rocket::config::Sig; /// /// assert_eq!(config.shutdown.signals.len(), 2); /// assert!(config.shutdown.signals.contains(&Sig::Term)); /// assert!(config.shutdown.signals.contains(&Sig::Hup)); /// # } /// ``` /// /// Or, as with all configuration options, programatically: /// /// ```rust /// # use rocket::figment::{Figment, providers::{Format, Toml}}; /// use rocket::config::{Config, Shutdown}; /// /// #[cfg(unix)] /// use rocket::config::Sig; /// /// let config = Config { /// shutdown: Shutdown { /// ctrlc: false, /// #[cfg(unix)] /// signals: { /// let mut set = std::collections::HashSet::new(); /// set.insert(Sig::Term); /// set.insert(Sig::Hup); /// set /// }, /// grace: 10, /// mercy: 5, /// force: true, /// ..Default::default() /// }, /// ..Config::default() /// }; /// /// assert_eq!(config.shutdown.ctrlc, false); /// assert_eq!(config.shutdown.grace, 10); /// assert_eq!(config.shutdown.mercy, 5); /// assert_eq!(config.shutdown.force, true); /// /// #[cfg(unix)] { /// assert_eq!(config.shutdown.signals.len(), 2); /// assert!(config.shutdown.signals.contains(&Sig::Term)); /// assert!(config.shutdown.signals.contains(&Sig::Hup)); /// } /// ``` #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Shutdown { /// Whether `ctrl-c` (`SIGINT`) initiates a server shutdown. /// /// **default: `true`** #[serde(deserialize_with = "figment::util::bool_from_str_or_int")] pub ctrlc: bool, /// On Unix, a set of signal which trigger a shutdown. On non-Unix, this /// option is unavailable and silently ignored. /// /// **default: { [`Sig::Term`] }** #[cfg(unix)] #[cfg_attr(nightly, doc(cfg(unix)))] pub signals: HashSet<Sig>, /// The grace period: number of seconds to continue to try to finish /// outstanding _server_ I/O for before forcibly terminating it. /// /// **default: `2`** pub grace: u32, /// The mercy period: number of seconds to continue to try to finish /// outstanding _connection_ I/O for before forcibly terminating it. /// /// **default: `3`** pub mercy: u32, /// Whether to force termination of a process that refuses to cooperatively /// shutdown. /// /// Rocket _never_ forcefully terminates a server that is running inside of /// a custom runtime irrespective of this value. A server that creates its /// own async runtime must take care to terminate itself if it fails to /// cooperate. /// /// **default: `true`** #[serde(deserialize_with = "figment::util::bool_from_str_or_int")] pub force: bool, /// PRIVATE: This structure may grow (but never change otherwise) in a /// non-breaking release. As such, constructing this structure should /// _always_ be done using a public constructor or update syntax: /// /// ```rust /// use rocket::config::Shutdown; /// /// let config = Shutdown { /// grace: 5, /// mercy: 10, /// ..Default::default() /// }; /// ``` #[doc(hidden)] #[serde(skip)] pub __non_exhaustive: (), } impl fmt::Display for Shutdown { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "ctrlc = {}, force = {}, ", self.ctrlc, self.force)?; #[cfg(unix)] { write!(f, "signals = [")?; for (i, sig) in self.signals.iter().enumerate() { if i != 0 { write!(f, ", ")?; } write!(f, "{}", sig)?; } write!(f, "], ")?; } write!(f, "grace = {}s, mercy = {}s", self.grace, self.mercy)?; Ok(()) } } impl Default for Shutdown { fn default() -> Self { Shutdown { ctrlc: true, #[cfg(unix)] signals: { let mut set = HashSet::new(); set.insert(Sig::Term); set }, grace: 2, mercy: 3, force: true, __non_exhaustive: (), } } } impl Shutdown { #[cfg(unix)] pub(crate) fn signal_stream(&self) -> Option<impl Stream<Item = Sig>> { use tokio_stream::{StreamExt, StreamMap, wrappers::SignalStream}; use tokio::signal::unix::{signal, SignalKind}; if !self.ctrlc && self.signals.is_empty() { return None; } let mut signals = self.signals.clone(); if self.ctrlc { signals.insert(Sig::Int); } let mut map = StreamMap::new(); for sig in signals { let sigkind = match sig { Sig::Alrm => SignalKind::alarm(), Sig::Chld => SignalKind::child(), Sig::Hup => SignalKind::hangup(), Sig::Int => SignalKind::interrupt(), Sig::Io => SignalKind::io(), Sig::Pipe => SignalKind::pipe(), Sig::Quit => SignalKind::quit(), Sig::Term => SignalKind::terminate(), Sig::Usr1 => SignalKind::user_defined1(), Sig::Usr2 => SignalKind::user_defined2() }; match signal(sigkind) { Ok(signal) => { map.insert(sig, SignalStream::new(signal)); }, Err(e) => warn!("Failed to enable `{}` shutdown signal: {}", sig, e), } } Some(map.map(|(k, _)| k)) } #[cfg(not(unix))] pub(crate) fn signal_stream(&self) -> Option<impl Stream<Item = Sig>> { use tokio_stream::StreamExt; use futures::stream::once; self.ctrlc.then(|| tokio::signal::ctrl_c()) .map(|signal| once(Box::pin(signal))) .map(|stream| stream.filter_map(|result| { result.map(|_| Sig::Int) .map_err(|e| warn!("Failed to enable `ctrl-c` shutdown signal: {}", e)) .ok() })) } }
34.659884
91
0.596997
e29b5e400339f25b7e956ba24b4a26a6cf7e8041
123
#!/usr/bin/env car fn main() { println!("Hello, world!\nThis is a Rust source file with the file extension '.rs'.") }
20.5
88
0.642276
5db0c67beb92c6fb41859c4be84bd036cd554bd6
2,026
// Copyright 2015 The Gfx-rs 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. extern crate gfx; extern crate gfx_window_sdl; extern crate sdl2; use gfx::Device; use sdl2::event::Event; use sdl2::keyboard::Keycode; use gfx::format::{Rgba8, DepthStencil}; const CLEAR_COLOR: [f32; 4] = [0.1, 0.2, 0.3, 1.0]; pub fn main() { let sdl_context = sdl2::init().unwrap(); let video = sdl_context.video().unwrap(); // Request opengl core 3.2 for example: video.gl_attr().set_context_profile(sdl2::video::GLProfile::Core); video.gl_attr().set_context_version(3, 2); let builder = video.window("SDL Window", 1024, 768); let (window, _gl_context, mut device, mut factory, main_color, _main_depth) = gfx_window_sdl::init::<Rgba8, DepthStencil>(&video, builder).unwrap(); let mut encoder: gfx::Encoder<_, _> = factory.create_command_buffer().into(); let mut events = sdl_context.event_pump().unwrap(); let mut running = true; while running { // handle events for event in events.poll_iter() { match event { Event::Quit { .. } | Event::KeyUp { keycode: Some(Keycode::Escape), .. } => { running = false; } _ => {} } } // draw a frame encoder.clear(&main_color, CLEAR_COLOR); // <- draw actual stuff here encoder.flush(&mut device); window.gl_swap_window(); device.cleanup(); } }
33.766667
81
0.634255
4bcab63c9f7fe1fff248bec33f22e406ae580a3d
3,206
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::sync::Arc; use common_arrow::arrow::datatypes::DataType as ArrowType; use common_exception::ErrorCode; use common_exception::Result; use super::data_type::DataType; use super::data_type::DataTypePtr; use super::type_id::TypeID; use crate::prelude::*; #[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize)] pub struct StructType { names: Vec<String>, types: Vec<DataTypePtr>, } impl StructType { pub fn create(names: Vec<String>, types: Vec<DataTypePtr>) -> Self { debug_assert!(names.len() == types.len()); StructType { names, types } } pub fn names(&self) -> &Vec<String> { &self.names } pub fn types(&self) -> &Vec<DataTypePtr> { &self.types } } #[typetag::serde] impl DataType for StructType { fn data_type_id(&self) -> TypeID { TypeID::Struct } #[inline] fn as_any(&self) -> &dyn std::any::Any { self } fn default_value(&self) -> DataValue { let c: Vec<DataValue> = self.types.iter().map(|t| t.default_value()).collect(); DataValue::Struct(c) } fn create_constant_column(&self, data: &DataValue, size: usize) -> Result<ColumnRef> { if let DataValue::Struct(value) = data { debug_assert!(value.len() == self.types.len()); let cols = value .iter() .zip(self.types.iter()) .map(|(v, typ)| typ.create_constant_column(v, size)) .collect::<Result<Vec<_>>>()?; let struct_column = StructColumn::from_data(cols, Arc::new(self.clone())); return Ok(Arc::new(ConstColumn::new(Arc::new(struct_column), size))); } return Result::Err(ErrorCode::BadDataValueType(format!( "Unexpected type:{:?} to generate list column", data.value_type() ))); } fn arrow_type(&self) -> ArrowType { let fields = self .names .iter() .zip(self.types.iter()) .map(|(name, type_)| type_.to_arrow_field(name)) .collect(); ArrowType::Struct(fields) } fn create_serializer(&self) -> Box<dyn TypeSerializer> { let inners = self.types.iter().map(|v| v.create_serializer()).collect(); Box::new(StructSerializer { inners, types: self.types.clone(), }) } fn create_deserializer(&self, _capacity: usize) -> Box<dyn TypeDeserializer> { todo!() } fn create_column(&self, _data: &[DataValue]) -> common_exception::Result<ColumnRef> { todo!() } }
29.685185
90
0.606987
1cecaf01548eef73b96ff59ab162b92ac06b0733
25,448
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. use std::future::Future; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use super::make_rpc_error; use collections::HashSet; use engine_traits::{KvEngine, CF_WRITE}; use file_system::{set_io_type, IOType}; use futures::executor::{ThreadPool, ThreadPoolBuilder}; use futures::sink::SinkExt; use futures::stream::TryStreamExt; use futures::TryFutureExt; use grpcio::{ ClientStreamingSink, RequestStream, RpcContext, ServerStreamingSink, UnarySink, WriteFlags, }; use kvproto::encryptionpb::EncryptionMethod; use kvproto::{errorpb, kvrpcpb::Context}; use kvproto::import_sstpb::RawWriteRequest_oneof_chunk as RawChunk; use kvproto::import_sstpb::WriteRequest_oneof_chunk as Chunk; use kvproto::import_sstpb::*; use kvproto::raft_cmdpb::*; use crate::server::CONFIG_ROCKSDB_GAUGE; use raftstore::router::RaftStoreRouter; use raftstore::store::{Callback, RaftCmdExtraOpts, RegionSnapshot}; use tikv_util::future::create_stream_with_buffer; use tikv_util::future::paired_future_callback; use tikv_util::time::{Instant, Limiter}; use crate::import::duplicate_detect::DuplicateDetector; use sst_importer::metrics::*; use sst_importer::{error_inc, sst_meta_to_path, Config, Error, Result, SSTImporter}; /// ImportSSTService provides tikv-server with the ability to ingest SST files. /// /// It saves the SST sent from client to a file and then sends a command to /// raftstore to trigger the ingest process. #[derive(Clone)] pub struct ImportSSTService<E, Router> where E: KvEngine, { cfg: Config, engine: E, router: Router, threads: ThreadPool, importer: Arc<SSTImporter>, limiter: Limiter, task_slots: Arc<Mutex<HashSet<PathBuf>>>, } pub struct SnapshotResult<E: KvEngine> { snapshot: RegionSnapshot<E::Snapshot>, term: u64, } impl<E, Router> ImportSSTService<E, Router> where E: KvEngine, Router: 'static + RaftStoreRouter<E>, { pub fn new( cfg: Config, router: Router, engine: E, importer: Arc<SSTImporter>, ) -> ImportSSTService<E, Router> { let props = tikv_util::thread_group::current_properties(); let threads = ThreadPoolBuilder::new() .pool_size(cfg.num_threads) .name_prefix("sst-importer") .after_start(move |_| { tikv_util::thread_group::set_properties(props.clone()); tikv_alloc::add_thread_memory_accessor(); set_io_type(IOType::Import); }) .before_stop(move |_| tikv_alloc::remove_thread_memory_accessor()) .create() .unwrap(); importer.start_switch_mode_check(&threads, engine.clone()); ImportSSTService { cfg, engine, threads, router, importer, limiter: Limiter::new(f64::INFINITY), task_slots: Arc::new(Mutex::new(HashSet::default())), } } fn acquire_lock(task_slots: &Arc<Mutex<HashSet<PathBuf>>>, meta: &SstMeta) -> Result<bool> { let mut slots = task_slots.lock().unwrap(); let p = sst_meta_to_path(meta)?; Ok(slots.insert(p)) } fn release_lock(task_slots: &Arc<Mutex<HashSet<PathBuf>>>, meta: &SstMeta) -> Result<bool> { let mut slots = task_slots.lock().unwrap(); let p = sst_meta_to_path(meta)?; Ok(slots.remove(&p)) } async fn async_snapshot( router: Router, header: RaftRequestHeader, ) -> std::result::Result<SnapshotResult<E>, errorpb::Error> { let mut req = Request::default(); req.set_cmd_type(CmdType::Snap); let mut cmd = RaftCmdRequest::default(); cmd.set_header(header); cmd.set_requests(vec![req].into()); let (cb, future) = paired_future_callback(); if let Err(e) = router.send_command(cmd, Callback::Read(cb), RaftCmdExtraOpts::default()) { return Err(e.into()); } let mut res = future.await.map_err(|_| { let mut err = errorpb::Error::default(); let err_str = "too many sst files are ingesting"; let mut server_is_busy_err = errorpb::ServerIsBusy::default(); server_is_busy_err.set_reason(err_str.to_string()); err.set_message(err_str.to_string()); err.set_server_is_busy(server_is_busy_err); err })?; let mut header = res.response.take_header(); if header.has_error() { return Err(header.take_error()); } Ok(SnapshotResult { snapshot: res.snapshot.unwrap(), term: header.get_current_term(), }) } fn check_write_stall(&self) -> Option<errorpb::Error> { if self.importer.get_mode() == SwitchMode::Normal && self .engine .ingest_maybe_slowdown_writes(CF_WRITE) .expect("cf") { let mut errorpb = errorpb::Error::default(); let err = "too many sst files are ingesting"; let mut server_is_busy_err = errorpb::ServerIsBusy::default(); server_is_busy_err.set_reason(err.to_string()); errorpb.set_message(err.to_string()); errorpb.set_server_is_busy(server_is_busy_err); return Some(errorpb); } None } fn ingest_files( &self, context: Context, label: &'static str, ssts: Vec<SstMeta>, ) -> impl Future<Output = Result<IngestResponse>> { let header = make_request_header(context); let snapshot_res = Self::async_snapshot(self.router.clone(), header.clone()); let router = self.router.clone(); let importer = self.importer.clone(); async move { // check api version if !importer.as_ref().check_api_version(&ssts)? { return Err(Error::IncompatibleApiVersion); } let mut resp = IngestResponse::default(); let res = match snapshot_res.await { Ok(snap) => snap, Err(e) => { pb_error_inc(label, &e); resp.set_error(e); return Ok(resp); } }; fail_point!("import::sst_service::ingest"); // Make ingest command. let mut cmd = RaftCmdRequest::default(); cmd.set_header(header); cmd.mut_header().set_term(res.term); for sst in ssts.iter() { let mut ingest = Request::default(); ingest.set_cmd_type(CmdType::IngestSst); ingest.mut_ingest_sst().set_sst(sst.clone()); cmd.mut_requests().push(ingest); } // Here we shall check whether the file has been ingested before. This operation // must execute after geting a snapshot from raftstore to make sure that the // current leader has applied to current term. for sst in ssts.iter() { if !importer.exist(sst) { warn!( "sst [{:?}] not exist. we may retry an operation that has already succeeded", sst ); let mut errorpb = errorpb::Error::default(); let err = "The file which would be ingested doest not exist."; let stale_err = errorpb::StaleCommand::default(); errorpb.set_message(err.to_string()); errorpb.set_stale_command(stale_err); resp.set_error(errorpb); return Ok(resp); } } let (cb, future) = paired_future_callback(); if let Err(e) = router.send_command(cmd, Callback::write(cb), RaftCmdExtraOpts::default()) { resp.set_error(e.into()); return Ok(resp); } let mut res = future.await.map_err(Error::from)?; let mut header = res.response.take_header(); if header.has_error() { pb_error_inc(label, header.get_error()); resp.set_error(header.take_error()); } Ok(resp) } } } #[macro_export] macro_rules! impl_write { ($fn:ident, $req_ty:ident, $resp_ty:ident, $chunk_ty:ident, $writer_fn:ident) => { fn $fn( &mut self, _ctx: RpcContext<'_>, stream: RequestStream<$req_ty>, sink: ClientStreamingSink<$resp_ty>, ) { let import = self.importer.clone(); let engine = self.engine.clone(); let (rx, buf_driver) = create_stream_with_buffer(stream, self.cfg.stream_channel_window); let mut rx = rx.map_err(Error::from); let timer = Instant::now_coarse(); let label = stringify!($fn); let handle_task = async move { let res = async move { let first_req = rx.try_next().await?; let meta = match first_req { Some(r) => match r.chunk { Some($chunk_ty::Meta(m)) => m, _ => return Err(Error::InvalidChunk), }, _ => return Err(Error::InvalidChunk), }; let writer = match import.$writer_fn(&engine, meta) { Ok(w) => w, Err(e) => { error!("build writer failed {:?}", e); return Err(Error::InvalidChunk); } }; let writer = rx .try_fold(writer, |mut writer, req| async move { let batch = match req.chunk { Some($chunk_ty::Batch(b)) => b, _ => return Err(Error::InvalidChunk), }; writer.write(batch)?; Ok(writer) }) .await?; let metas = writer.finish()?; import.verify_checksum(&metas)?; let mut resp = $resp_ty::default(); resp.set_metas(metas.into()); Ok(resp) } .await; crate::send_rpc_response!(res, sink, label, timer); }; self.threads.spawn_ok(buf_driver); self.threads.spawn_ok(handle_task); } }; } impl<E, Router> ImportSst for ImportSSTService<E, Router> where E: KvEngine, Router: 'static + RaftStoreRouter<E>, { fn switch_mode( &mut self, ctx: RpcContext<'_>, req: SwitchModeRequest, sink: UnarySink<SwitchModeResponse>, ) { let label = "switch_mode"; let timer = Instant::now_coarse(); let res = { fn mf(cf: &str, name: &str, v: f64) { CONFIG_ROCKSDB_GAUGE.with_label_values(&[cf, name]).set(v); } match req.get_mode() { SwitchMode::Normal => self.importer.enter_normal_mode(self.engine.clone(), mf), SwitchMode::Import => self.importer.enter_import_mode(self.engine.clone(), mf), } }; match res { Ok(_) => info!("switch mode"; "mode" => ?req.get_mode()), Err(ref e) => error!(%*e; "switch mode failed"; "mode" => ?req.get_mode(),), } let task = async move { let res = Ok(SwitchModeResponse::default()); crate::send_rpc_response!(res, sink, label, timer); }; ctx.spawn(task); } /// Receive SST from client and save the file for later ingesting. fn upload( &mut self, _ctx: RpcContext<'_>, stream: RequestStream<UploadRequest>, sink: ClientStreamingSink<UploadResponse>, ) { let label = "upload"; let timer = Instant::now_coarse(); let import = self.importer.clone(); let (rx, buf_driver) = create_stream_with_buffer(stream, self.cfg.stream_channel_window); let mut map_rx = rx.map_err(Error::from); let handle_task = async move { // So stream will not be dropped until response is sent. let rx = &mut map_rx; let res = async move { let first_chunk = rx.try_next().await?; let meta = match first_chunk { Some(ref chunk) if chunk.has_meta() => chunk.get_meta(), _ => return Err(Error::InvalidChunk), }; let file = import.create(meta)?; let mut file = rx .try_fold(file, |mut file, chunk| async move { let start = Instant::now_coarse(); let data = chunk.get_data(); if data.is_empty() { return Err(Error::InvalidChunk); } file.append(data)?; IMPORT_UPLOAD_CHUNK_BYTES.observe(data.len() as f64); IMPORT_UPLOAD_CHUNK_DURATION.observe(start.saturating_elapsed_secs()); Ok(file) }) .await?; file.finish().map(|_| UploadResponse::default()) } .await; crate::send_rpc_response!(res, sink, label, timer); }; self.threads.spawn_ok(buf_driver); self.threads.spawn_ok(handle_task); } /// Downloads the file and performs key-rewrite for later ingesting. fn download( &mut self, _ctx: RpcContext<'_>, req: DownloadRequest, sink: UnarySink<DownloadResponse>, ) { let label = "download"; let timer = Instant::now_coarse(); let importer = Arc::clone(&self.importer); let limiter = self.limiter.clone(); let engine = self.engine.clone(); let start = Instant::now(); let handle_task = async move { // Records how long the download task waits to be scheduled. sst_importer::metrics::IMPORTER_DOWNLOAD_DURATION .with_label_values(&["queue"]) .observe(start.saturating_elapsed().as_secs_f64()); // FIXME: download() should be an async fn, to allow BR to cancel // a download task. // Unfortunately, this currently can't happen because the S3Storage // is not Send + Sync. See the documentation of S3Storage for reason. let cipher = req .cipher_info .to_owned() .into_option() .filter(|c| c.cipher_type != EncryptionMethod::Plaintext); let res = importer.download::<E>( req.get_sst(), req.get_storage_backend(), req.get_name(), req.get_rewrite_rule(), cipher, limiter, engine, ); let mut resp = DownloadResponse::default(); match res { Ok(range) => match range { Some(r) => resp.set_range(r), None => resp.set_is_empty(true), }, Err(e) => resp.set_error(e.into()), } let resp = Ok(resp); crate::send_rpc_response!(resp, sink, label, timer); }; self.threads.spawn_ok(handle_task); } /// Ingest the file by sending a raft command to raftstore. /// /// If the ingestion fails because the region is not found or the epoch does /// not match, the remaining files will eventually be cleaned up by /// CleanupSSTWorker. fn ingest( &mut self, ctx: RpcContext<'_>, mut req: IngestRequest, sink: UnarySink<IngestResponse>, ) { let label = "ingest"; let timer = Instant::now_coarse(); let mut resp = IngestResponse::default(); if let Some(errorpb) = self.check_write_stall() { resp.set_error(errorpb); ctx.spawn( sink.success(resp) .unwrap_or_else(|e| warn!("send rpc failed"; "err" => %e)), ); return; } let mut errorpb = errorpb::Error::default(); if !Self::acquire_lock(&self.task_slots, req.get_sst()).unwrap_or(false) { errorpb.set_message(Error::FileConflict.to_string()); resp.set_error(errorpb); ctx.spawn( sink.success(resp) .unwrap_or_else(|e| warn!("send rpc failed"; "err" => %e)), ); return; } let task_slots = self.task_slots.clone(); let meta = req.take_sst(); let f = self.ingest_files(req.take_context(), label, vec![meta.clone()]); let handle_task = async move { let res = f.await; Self::release_lock(&task_slots, &meta).unwrap(); crate::send_rpc_response!(res, sink, label, timer); }; self.threads.spawn_ok(handle_task); } /// Ingest multiple files by sending a raft command to raftstore. /// fn multi_ingest( &mut self, ctx: RpcContext<'_>, mut req: MultiIngestRequest, sink: UnarySink<IngestResponse>, ) { let label = "multi-ingest"; let timer = Instant::now_coarse(); let mut resp = IngestResponse::default(); if let Some(errorpb) = self.check_write_stall() { resp.set_error(errorpb); ctx.spawn( sink.success(resp) .unwrap_or_else(|e| warn!("send rpc failed"; "err" => %e)), ); return; } let mut errorpb = errorpb::Error::default(); let mut metas = vec![]; for sst in req.get_ssts() { if Self::acquire_lock(&self.task_slots, sst).unwrap_or(false) { metas.push(sst.clone()); } } if metas.len() < req.get_ssts().len() { for m in metas { Self::release_lock(&self.task_slots, &m).unwrap(); } errorpb.set_message(Error::FileConflict.to_string()); resp.set_error(errorpb); ctx.spawn( sink.success(resp) .unwrap_or_else(|e| warn!("send rpc failed"; "err" => %e)), ); return; } let task_slots = self.task_slots.clone(); let f = self.ingest_files(req.take_context(), label, req.take_ssts().into()); let handle_task = async move { let res = f.await; for m in metas { Self::release_lock(&task_slots, &m).unwrap(); } crate::send_rpc_response!(res, sink, label, timer); }; self.threads.spawn_ok(handle_task); } fn compact( &mut self, _ctx: RpcContext<'_>, req: CompactRequest, sink: UnarySink<CompactResponse>, ) { let label = "compact"; let timer = Instant::now_coarse(); let engine = self.engine.clone(); let handle_task = async move { let (start, end) = if !req.has_range() { (None, None) } else { ( Some(req.get_range().get_start()), Some(req.get_range().get_end()), ) }; let output_level = if req.get_output_level() == -1 { None } else { Some(req.get_output_level()) }; let res = engine.compact_files_in_range(start, end, output_level); match res { Ok(_) => info!( "compact files in range"; "start" => start.map(log_wrappers::Value::key), "end" => end.map(log_wrappers::Value::key), "output_level" => ?output_level, "takes" => ?timer.saturating_elapsed() ), Err(ref e) => error!(%*e; "compact files in range failed"; "start" => start.map(log_wrappers::Value::key), "end" => end.map(log_wrappers::Value::key), "output_level" => ?output_level, ), } let res = res .map_err(|e| Error::Engine(box_err!(e))) .map(|_| CompactResponse::default()); crate::send_rpc_response!(res, sink, label, timer); }; self.threads.spawn_ok(handle_task); } fn set_download_speed_limit( &mut self, ctx: RpcContext<'_>, req: SetDownloadSpeedLimitRequest, sink: UnarySink<SetDownloadSpeedLimitResponse>, ) { let label = "set_download_speed_limit"; let timer = Instant::now_coarse(); let speed_limit = req.get_speed_limit(); self.limiter.set_speed_limit(if speed_limit > 0 { speed_limit as f64 } else { f64::INFINITY }); let ctx_task = async move { let res = Ok(SetDownloadSpeedLimitResponse::default()); crate::send_rpc_response!(res, sink, label, timer); }; ctx.spawn(ctx_task); } fn duplicate_detect( &mut self, _ctx: RpcContext<'_>, mut request: DuplicateDetectRequest, mut sink: ServerStreamingSink<DuplicateDetectResponse>, ) { let label = "duplicate_detect"; let timer = Instant::now_coarse(); let context = request.take_context(); let router = self.router.clone(); let start_key = request.take_start_key(); let min_commit_ts = request.get_min_commit_ts(); let end_key = if request.get_end_key().is_empty() { None } else { Some(request.take_end_key()) }; let key_only = request.get_key_only(); let snap_res = Self::async_snapshot(router, make_request_header(context)); let handle_task = async move { let res = snap_res.await; let snapshot = match res { Ok(snap) => snap.snapshot, Err(e) => { let mut resp = DuplicateDetectResponse::default(); pb_error_inc(label, &e); resp.set_region_error(e); match sink .send((resp, WriteFlags::default().buffer_hint(true))) .await { Ok(_) => { IMPORT_RPC_DURATION .with_label_values(&[label, "ok"]) .observe(timer.saturating_elapsed_secs()); } Err(e) => { warn!( "connection send message fail"; "err" => %e ); } } let _ = sink.close().await; return; } }; let detector = DuplicateDetector::new(snapshot, start_key, end_key, min_commit_ts, key_only) .unwrap(); for resp in detector { if let Err(e) = sink .send((resp, WriteFlags::default().buffer_hint(true))) .await { warn!( "connection send message fail"; "err" => %e ); break; } } let _ = sink.close().await; }; self.threads.spawn_ok(handle_task); } impl_write!(write, WriteRequest, WriteResponse, Chunk, new_txn_writer); impl_write!( raw_write, RawWriteRequest, RawWriteResponse, RawChunk, new_raw_writer ); } // add error statistics from pb error response fn pb_error_inc(type_: &str, e: &errorpb::Error) { let label = if e.has_not_leader() { "not_leader" } else if e.has_store_not_match() { "store_not_match" } else if e.has_region_not_found() { "region_not_found" } else if e.has_key_not_in_region() { "key_not_in_range" } else if e.has_epoch_not_match() { "epoch_not_match" } else if e.has_server_is_busy() { "server_is_busy" } else if e.has_stale_command() { "stale_command" } else if e.has_raft_entry_too_large() { "raft_entry_too_large" } else { "unknown" }; IMPORTER_ERROR_VEC.with_label_values(&[type_, label]).inc(); } fn make_request_header(mut context: Context) -> RaftRequestHeader { let region_id = context.get_region_id(); let mut header = RaftRequestHeader::default(); header.set_peer(context.take_peer()); header.set_region_id(region_id); header.set_region_epoch(context.take_region_epoch()); header }
35.641457
101
0.523106
f4e672ed6f5b34bb379196de3f3303b6139e5933
16,389
use super::*; use egui::{color::*, *}; /// Showcase some ui code #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct MiscDemoWindow { num_columns: usize, widgets: Widgets, colors: ColorWidgets, tree: Tree, box_painting: BoxPainting, } impl Default for MiscDemoWindow { fn default() -> MiscDemoWindow { MiscDemoWindow { num_columns: 2, widgets: Default::default(), colors: Default::default(), tree: Tree::demo(), box_painting: Default::default(), } } } impl Demo for MiscDemoWindow { fn name(&self) -> &'static str { "✨ Misc Demos" } fn show(&mut self, ctx: &Context, open: &mut bool) { Window::new(self.name()) .open(open) .vscroll(true) .hscroll(true) .show(ctx, |ui| self.ui(ui)); } } impl View for MiscDemoWindow { fn ui(&mut self, ui: &mut Ui) { ui.set_min_width(250.0); CollapsingHeader::new("Widgets") .default_open(true) .show(ui, |ui| { self.widgets.ui(ui); }); CollapsingHeader::new("Text layout") .default_open(false) .show(ui, |ui| { text_layout_ui(ui); }); CollapsingHeader::new("Colors") .default_open(false) .show(ui, |ui| { self.colors.ui(ui); }); CollapsingHeader::new("Tree") .default_open(false) .show(ui, |ui| self.tree.ui(ui)); ui.collapsing("Columns", |ui| { ui.add(Slider::new(&mut self.num_columns, 1..=10).text("Columns")); ui.columns(self.num_columns, |cols| { for (i, col) in cols.iter_mut().enumerate() { col.label(format!("Column {} out of {}", i + 1, self.num_columns)); if i + 1 == self.num_columns && col.button("Delete this").clicked() { self.num_columns -= 1; } } }); }); CollapsingHeader::new("Test box rendering") .default_open(false) .show(ui, |ui| self.box_painting.ui(ui)); CollapsingHeader::new("Resize") .default_open(false) .show(ui, |ui| { Resize::default().default_height(100.0).show(ui, |ui| { ui.label("This ui can be resized!"); ui.label("Just pull the handle on the bottom right"); }); }); CollapsingHeader::new("Misc") .default_open(false) .show(ui, |ui| { ui.horizontal(|ui| { ui.label("You can pretty easily paint your own small icons:"); use std::f32::consts::TAU; let size = Vec2::splat(16.0); let (response, painter) = ui.allocate_painter(size, Sense::hover()); let rect = response.rect; let c = rect.center(); let r = rect.width() / 2.0 - 1.0; let color = Color32::from_gray(128); let stroke = Stroke::new(1.0, color); painter.circle_stroke(c, r, stroke); painter.line_segment([c - vec2(0.0, r), c + vec2(0.0, r)], stroke); painter.line_segment([c, c + r * Vec2::angled(TAU * 1.0 / 8.0)], stroke); painter.line_segment([c, c + r * Vec2::angled(TAU * 3.0 / 8.0)], stroke); }); }); } } // ---------------------------------------------------------------------------- #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct Widgets { angle: f32, password: String, } impl Default for Widgets { fn default() -> Self { Self { angle: std::f32::consts::TAU / 3.0, password: "hunter2".to_owned(), } } } impl Widgets { pub fn ui(&mut self, ui: &mut Ui) { let Self { angle, password } = self; ui.vertical_centered(|ui| { ui.add(crate::__egui_github_link_file_line!()); }); ui.horizontal_wrapped(|ui| { // Trick so we don't have to add spaces in the text below: let width = ui.fonts().glyph_width(&TextStyle::Body.resolve(ui.style()), ' '); ui.spacing_mut().item_spacing.x = width; ui.label(RichText::new("Text can have").color(Color32::from_rgb(110, 255, 110))); ui.colored_label(Color32::from_rgb(128, 140, 255), "color"); // Shortcut version ui.label("and tooltips.").on_hover_text( "This is a multiline tooltip that demonstrates that you can easily add tooltips to any element.\nThis is the second line.\nThis is the third.", ); ui.label("You can mix in other widgets into text, like"); let _ = ui.small_button("this button"); ui.label("."); ui.label("The default font supports all latin and cyrillic characters (ИÅđ…), common math symbols (∫√∞²⅓…), and many emojis (💓🌟🖩…).") .on_hover_text("There is currently no support for right-to-left languages."); ui.label("See the 🔤 Font Book for more!"); ui.monospace("There is also a monospace font."); }); let tooltip_ui = |ui: &mut Ui| { ui.heading("The name of the tooltip"); ui.horizontal(|ui| { ui.label("This tooltip was created with"); ui.monospace(".on_hover_ui(…)"); }); let _ = ui.button("A button you can never press"); }; ui.label("Tooltips can be more than just simple text.") .on_hover_ui(tooltip_ui); ui.separator(); ui.horizontal(|ui| { ui.label("An angle:"); ui.drag_angle(angle); ui.label(format!("≈ {:.3}τ", *angle / std::f32::consts::TAU)) .on_hover_text("Each τ represents one turn (τ = 2π)"); }) .response .on_hover_text("The angle is stored in radians, but presented in degrees"); ui.separator(); ui.horizontal(|ui| { ui.hyperlink_to("Password:", super::password::url_to_file_source_code()) .on_hover_text("See the example code for how to use egui to store UI state"); ui.add(super::password::password(password)); }); } } // ---------------------------------------------------------------------------- #[derive(PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] struct ColorWidgets { srgba_unmul: [u8; 4], srgba_premul: [u8; 4], rgba_unmul: [f32; 4], rgba_premul: [f32; 4], } impl Default for ColorWidgets { fn default() -> Self { // Approximately the same color. ColorWidgets { srgba_unmul: [0, 255, 183, 127], srgba_premul: [0, 187, 140, 127], rgba_unmul: [0.0, 1.0, 0.5, 0.5], rgba_premul: [0.0, 0.5, 0.25, 0.5], } } } impl ColorWidgets { fn ui(&mut self, ui: &mut Ui) { egui::reset_button(ui, self); ui.label("egui lets you edit colors stored as either sRGBA or linear RGBA and with or without premultiplied alpha"); let Self { srgba_unmul, srgba_premul, rgba_unmul, rgba_premul, } = self; ui.horizontal(|ui| { ui.color_edit_button_srgba_unmultiplied(srgba_unmul); ui.label(format!( "sRGBA: {} {} {} {}", srgba_unmul[0], srgba_unmul[1], srgba_unmul[2], srgba_unmul[3], )); }); ui.horizontal(|ui| { ui.color_edit_button_srgba_premultiplied(srgba_premul); ui.label(format!( "sRGBA with premultiplied alpha: {} {} {} {}", srgba_premul[0], srgba_premul[1], srgba_premul[2], srgba_premul[3], )); }); ui.horizontal(|ui| { ui.color_edit_button_rgba_unmultiplied(rgba_unmul); ui.label(format!( "Linear RGBA: {:.02} {:.02} {:.02} {:.02}", rgba_unmul[0], rgba_unmul[1], rgba_unmul[2], rgba_unmul[3], )); }); ui.horizontal(|ui| { ui.color_edit_button_rgba_premultiplied(rgba_premul); ui.label(format!( "Linear RGBA with premultiplied alpha: {:.02} {:.02} {:.02} {:.02}", rgba_premul[0], rgba_premul[1], rgba_premul[2], rgba_premul[3], )); }); } } // ---------------------------------------------------------------------------- #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] struct BoxPainting { size: Vec2, rounding: f32, stroke_width: f32, num_boxes: usize, } impl Default for BoxPainting { fn default() -> Self { Self { size: vec2(64.0, 32.0), rounding: 5.0, stroke_width: 2.0, num_boxes: 1, } } } impl BoxPainting { pub fn ui(&mut self, ui: &mut Ui) { ui.add(Slider::new(&mut self.size.x, 0.0..=500.0).text("width")); ui.add(Slider::new(&mut self.size.y, 0.0..=500.0).text("height")); ui.add(Slider::new(&mut self.rounding, 0.0..=50.0).text("rounding")); ui.add(Slider::new(&mut self.stroke_width, 0.0..=10.0).text("stroke_width")); ui.add(Slider::new(&mut self.num_boxes, 0..=8).text("num_boxes")); ui.horizontal_wrapped(|ui| { for _ in 0..self.num_boxes { let (rect, _response) = ui.allocate_at_least(self.size, Sense::hover()); ui.painter().rect( rect, self.rounding, Color32::from_gray(64), Stroke::new(self.stroke_width, Color32::WHITE), ); } }); } } // ---------------------------------------------------------------------------- #[derive(Clone, Copy, PartialEq)] enum Action { Keep, Delete, } #[derive(Clone, Default)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] struct Tree(String, SubTree); impl Tree { pub fn demo() -> Self { Self( String::from("root"), SubTree(vec![ SubTree(vec![SubTree::default(); 4]), SubTree(vec![SubTree(vec![SubTree::default(); 2]); 3]), ]), ) } pub fn ui(&mut self, ui: &mut Ui) -> Action { self.1.ui(ui, 0, "root", &mut self.0) } } #[derive(Clone, Default)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] struct SubTree(Vec<SubTree>); impl SubTree { pub fn ui( &mut self, ui: &mut Ui, depth: usize, name: &str, selected_name: &mut String, ) -> Action { let response = CollapsingHeader::new(name) .default_open(depth < 1) .selectable(true) .selected(selected_name.as_str() == name) .show(ui, |ui| self.children_ui(ui, name, depth, selected_name)); if response.header_response.clicked() { *selected_name = name.to_string(); } response.body_returned.unwrap_or(Action::Keep) } fn children_ui( &mut self, ui: &mut Ui, parent_name: &str, depth: usize, selected_name: &mut String, ) -> Action { if depth > 0 && ui .button(RichText::new("delete").color(Color32::RED)) .clicked() { return Action::Delete; } self.0 = std::mem::take(self) .0 .into_iter() .enumerate() .filter_map(|(i, mut tree)| { if tree.ui( ui, depth + 1, &format!("{}/{}", parent_name, i), selected_name, ) == Action::Keep { Some(tree) } else { None } }) .collect(); if ui.button("+").clicked() { self.0.push(SubTree::default()); } Action::Keep } } // ---------------------------------------------------------------------------- fn text_layout_ui(ui: &mut egui::Ui) { use egui::text::LayoutJob; let mut job = LayoutJob::default(); let first_row_indentation = 10.0; let (default_color, strong_color) = if ui.visuals().dark_mode { (Color32::LIGHT_GRAY, Color32::WHITE) } else { (Color32::DARK_GRAY, Color32::BLACK) }; job.append( "This is a demonstration of ", first_row_indentation, TextFormat { color: default_color, ..Default::default() }, ); job.append( "the egui text layout engine. ", 0.0, TextFormat { color: strong_color, ..Default::default() }, ); job.append( "It supports ", 0.0, TextFormat { color: default_color, ..Default::default() }, ); job.append( "different ", 0.0, TextFormat { color: Color32::from_rgb(110, 255, 110), ..Default::default() }, ); job.append( "colors, ", 0.0, TextFormat { color: Color32::from_rgb(128, 140, 255), ..Default::default() }, ); job.append( "backgrounds, ", 0.0, TextFormat { color: default_color, background: Color32::from_rgb(128, 32, 32), ..Default::default() }, ); job.append( "mixing ", 0.0, TextFormat { font_id: FontId::proportional(20.0), color: default_color, ..Default::default() }, ); job.append( "fonts, ", 0.0, TextFormat { font_id: FontId::monospace(14.0), color: default_color, ..Default::default() }, ); job.append( "raised text, ", 0.0, TextFormat { font_id: FontId::proportional(8.0), color: default_color, valign: Align::TOP, ..Default::default() }, ); job.append( "with ", 0.0, TextFormat { color: default_color, ..Default::default() }, ); job.append( "underlining", 0.0, TextFormat { color: default_color, underline: Stroke::new(1.0, Color32::LIGHT_BLUE), ..Default::default() }, ); job.append( " and ", 0.0, TextFormat { color: default_color, ..Default::default() }, ); job.append( "strikethrough", 0.0, TextFormat { color: default_color, strikethrough: Stroke::new(2.0, Color32::RED.linear_multiply(0.5)), ..Default::default() }, ); job.append( ". Of course, ", 0.0, TextFormat { color: default_color, ..Default::default() }, ); job.append( "you can", 0.0, TextFormat { color: default_color, strikethrough: Stroke::new(1.0, strong_color), ..Default::default() }, ); job.append( " mix these!", 0.0, TextFormat { font_id: FontId::proportional(8.0), color: Color32::LIGHT_BLUE, background: Color32::from_rgb(128, 0, 0), underline: Stroke::new(1.0, strong_color), ..Default::default() }, ); ui.label(job); ui.vertical_centered(|ui| { ui.add(crate::__egui_github_link_file_line!()); }); }
29.110124
159
0.483129
ab0db067cf78434b5c01f43b2f9541225274c455
160
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] pub type Battery = *mut ::core::ffi::c_void;
53.333333
114
0.8