hexsha
stringlengths
40
40
size
int64
2
1.05M
content
stringlengths
2
1.05M
avg_line_length
float64
1.33
100
max_line_length
int64
1
1k
alphanum_fraction
float64
0.25
1
3a26974e02ad85f34de54b296961d7f77cea94c4
7,167
//! Defines traits for blocking (synchronous) and non-blocking (asynchronous) //! communication with a Solana server as well a a trait that encompasses both. //! //! //! Synchronous implementations are expected to create transactions, sign them, and send //! them with multiple retries, updating blockhashes and resigning as-needed. //! //! Asynchronous implementations are expected to create transactions, sign them, and send //! them but without waiting to see if the server accepted it. #![cfg(feature = "full")] use crate::{ account::Account, clock::Slot, commitment_config::CommitmentConfig, epoch_info::EpochInfo, fee_calculator::{FeeCalculator, FeeRateGovernor}, hash::Hash, instruction::Instruction, message::Message, pubkey::Pubkey, signature::{Keypair, Signature}, signers::Signers, transaction, transport::Result, }; pub trait Client: SyncClient + AsyncClient { fn tpu_addr(&self) -> String; } pub trait SyncClient { /// Create a transaction from the given message, and send it to the /// server, retrying as-needed. fn send_and_confirm_message<T: Signers>( &self, keypairs: &T, message: Message, ) -> Result<Signature>; /// Create a transaction from a single instruction that only requires /// a single signer. Then send it to the server, retrying as-needed. fn send_and_confirm_instruction( &self, keypair: &Keypair, instruction: Instruction, ) -> Result<Signature>; /// Transfer lamports from `keypair` to `pubkey`, retrying until the /// transfer completes or produces and error. fn transfer_and_confirm( &self, lamports: u64, keypair: &Keypair, pubkey: &Pubkey, ) -> Result<Signature>; /// Get an account or None if not found. fn get_account_data(&self, pubkey: &Pubkey) -> Result<Option<Vec<u8>>>; /// Get an account or None if not found. fn get_account(&self, pubkey: &Pubkey) -> Result<Option<Account>>; /// Get an account or None if not found. Uses explicit commitment configuration. fn get_account_with_commitment( &self, pubkey: &Pubkey, commitment_config: CommitmentConfig, ) -> Result<Option<Account>>; /// Get account balance or 0 if not found. fn get_balance(&self, pubkey: &Pubkey) -> Result<u64>; /// Get account balance or 0 if not found. Uses explicit commitment configuration. fn get_balance_with_commitment( &self, pubkey: &Pubkey, commitment_config: CommitmentConfig, ) -> Result<u64>; fn get_minimum_balance_for_rent_exemption(&self, data_len: usize) -> Result<u64>; /// Get recent blockhash #[deprecated(since = "1.9.0", note = "Please use `get_latest_blockhash` instead")] fn get_recent_blockhash(&self) -> Result<(Hash, FeeCalculator)>; /// Get recent blockhash. Uses explicit commitment configuration. #[deprecated( since = "1.9.0", note = "Please use `get_latest_blockhash_with_commitment` and `get_latest_blockhash_with_commitment` instead" )] fn get_recent_blockhash_with_commitment( &self, commitment_config: CommitmentConfig, ) -> Result<(Hash, FeeCalculator, Slot)>; /// Get `Some(FeeCalculator)` associated with `blockhash` if it is still in /// the BlockhashQueue`, otherwise `None` #[deprecated( since = "1.9.0", note = "Please use `get_fee_for_message` or `is_blockhash_valid` instead" )] fn get_fee_calculator_for_blockhash(&self, blockhash: &Hash) -> Result<Option<FeeCalculator>>; /// Get recent fee rate governor #[deprecated( since = "1.9.0", note = "Please do not use, will no longer be available in the future" )] fn get_fee_rate_governor(&self) -> Result<FeeRateGovernor>; /// Get signature status. fn get_signature_status( &self, signature: &Signature, ) -> Result<Option<transaction::Result<()>>>; /// Get signature status. Uses explicit commitment configuration. fn get_signature_status_with_commitment( &self, signature: &Signature, commitment_config: CommitmentConfig, ) -> Result<Option<transaction::Result<()>>>; /// Get last known slot fn get_slot(&self) -> Result<Slot>; /// Get last known slot. Uses explicit commitment configuration. fn get_slot_with_commitment(&self, commitment_config: CommitmentConfig) -> Result<u64>; /// Get transaction count fn get_transaction_count(&self) -> Result<u64>; /// Get transaction count. Uses explicit commitment configuration. fn get_transaction_count_with_commitment( &self, commitment_config: CommitmentConfig, ) -> Result<u64>; fn get_epoch_info(&self) -> Result<EpochInfo>; /// Poll until the signature has been confirmed by at least `min_confirmed_blocks` fn poll_for_signature_confirmation( &self, signature: &Signature, min_confirmed_blocks: usize, ) -> Result<usize>; /// Poll to confirm a transaction. fn poll_for_signature(&self, signature: &Signature) -> Result<()>; #[deprecated( since = "1.9.0", note = "Please do not use, will no longer be available in the future" )] fn get_new_blockhash(&self, blockhash: &Hash) -> Result<(Hash, FeeCalculator)>; /// Get last known blockhash fn get_latest_blockhash(&self) -> Result<Hash>; /// Get latest blockhash with last valid block height. Uses explicit commitment configuration. fn get_latest_blockhash_with_commitment( &self, commitment_config: CommitmentConfig, ) -> Result<(Hash, u64)>; /// Check if the blockhash is valid fn is_blockhash_valid(&self, blockhash: &Hash, commitment: CommitmentConfig) -> Result<bool>; /// Calculate the fee for a `Message` fn get_fee_for_message(&self, message: &Message) -> Result<u64>; } pub trait AsyncClient { /// Send a signed transaction, but don't wait to see if the server accepted it. fn async_send_transaction(&self, transaction: transaction::Transaction) -> Result<Signature>; fn async_send_batch(&self, transactions: Vec<transaction::Transaction>) -> Result<()>; /// Create a transaction from the given message, and send it to the /// server, but don't wait for to see if the server accepted it. fn async_send_message<T: Signers>( &self, keypairs: &T, message: Message, recent_blockhash: Hash, ) -> Result<Signature>; /// Create a transaction from a single instruction that only requires /// a single signer. Then send it to the server, but don't wait for a reply. fn async_send_instruction( &self, keypair: &Keypair, instruction: Instruction, recent_blockhash: Hash, ) -> Result<Signature>; /// Attempt to transfer lamports from `keypair` to `pubkey`, but don't wait to confirm. fn async_transfer( &self, lamports: u64, keypair: &Keypair, pubkey: &Pubkey, recent_blockhash: Hash, ) -> Result<Signature>; }
34.623188
117
0.665829
16e7634bae7a06ef187a5889ee60e62268f4864c
11,079
use std::collections::HashMap; use actix_web::http::StatusCode; use actix_web::HttpResponse; use actix_web::ResponseError; use chrono::DateTime; use chrono::Utc; use failure::Fail; use failure::ResultExt; use opentracingrust::ExtractFormat; use opentracingrust::InjectFormat; use opentracingrust::Span; use opentracingrust::SpanContext; use opentracingrust::Tracer; use serde::de::DeserializeOwned; use serde_derive::Deserialize; use serde_derive::Serialize; use serde_json::json; use serde_json::Value as Json; use uuid::Uuid; use replicante_models_agent::actions::ActionModel; // Use the view versions of these models from here so they can easily change if needed. pub use replicante_models_agent::actions::ActionHistoryItem; pub use replicante_models_agent::actions::ActionListItem; pub use replicante_models_agent::actions::ActionRequester; pub use replicante_models_agent::actions::ActionState; use crate::store::Transaction; use crate::ErrorKind; use crate::Result; /// Abstraction of any action the agent can perform. /// /// # Action Kinds /// Action Kinds must be scoped to limit the chance of clashes. /// Scoping is done using the `<SCOPE>.<ACTION>` format. /// An action kind can have as many `.`s in it as desired, making Java-like reverse DNS /// scopes an option that greatly reduces the chances of clashes. /// /// The only constraint on Action Kindss is some scopes are reserved to replicante use itself. /// This allows the base agent frameworks to define some standard actions across all agents /// without clashing with custom or database specific actions. pub trait Action: Send + Sync + 'static { /// Action metadata and attributes. fn describe(&self) -> ActionDescriptor; /// Invoke the action to advance the given `ActionRecord`. fn invoke( &self, tx: &mut Transaction, record: &dyn ActionRecordView, span: Option<&mut Span>, ) -> Result<()>; /// Validate the arguments passed to an action request. fn validate_args(&self, args: &Json) -> ActionValidity; } /// Container for an action's metadata and other attributes. /// /// This data is the base of the actions system. /// Instead of hardcoded knowledge about what actions do, /// both system and users rely on metadata to call actions. #[derive(Clone, Eq, PartialEq, Hash, Debug, Serialize, Deserialize)] pub struct ActionDescriptor { pub kind: String, pub description: String, } /// Possible actions agent implementations can provide to the SDK. #[derive(Clone, Eq, PartialEq, Hash, Debug)] pub enum ActionHook { /// For the action implementing the graceful stop protocol for the store. /// /// Such action, if supported, MUST implement a datastore specific graceful shutdown. /// This action is not expected to operate on the process itself, although it will /// likely cause it to exit. /// /// For example, MongoDB `db.shutdownServer` is a good candidate for this action. StoreGracefulStop, } impl ActionHook { /// ActionDescriptor for a specific ActionHook. /// /// Any Action implementation attached to an ActionHook MUST return the /// ActionDescriptor returned by this method. /// If any agent returns an ActionHook with an ActionDescriptor that does not match /// the hook's descriptor the SDK will fail initiation with a panic. pub fn describe(&self) -> ActionDescriptor { match self { Self::StoreGracefulStop => ActionDescriptor { kind: "replicante.io/store.stop".into(), description: "Attempt graceful shutdown of the datastore node".into(), }, } } } /// Action state and metadata information. #[derive(Clone, PartialEq, Debug, Serialize, Deserialize)] pub struct ActionRecord { /// Version of the agent that last validated the action. pub agent_version: String, /// Time the action was first created (by the agent, by core, ...). pub created_ts: DateTime<Utc>, /// Time the action entered a finished state. pub finished_ts: Option<DateTime<Utc>>, /// Additional metadata headers attached to the action. pub headers: HashMap<String, String>, /// Unique ID of the action. pub id: Uuid, /// Type ID of the action to run. pub kind: String, /// Entity (system or user) requesting the execution of the action. pub requester: ActionRequester, /// Time the agent recorded the action in the DB. pub scheduled_ts: DateTime<Utc>, /// Arguments passed to the action when invoked. args: Json, /// State the action is currently in. state: ActionState, /// Optional payload attached to the current state. state_payload: Option<Json>, } impl ActionRecord { /// Construct an `ActionRecord` from raw attributes. #[allow(clippy::too_many_arguments)] pub(crate) fn inflate( agent_version: String, args: Json, created_ts: DateTime<Utc>, finished_ts: Option<DateTime<Utc>>, headers: HashMap<String, String>, id: Uuid, kind: String, requester: ActionRequester, scheduled_ts: DateTime<Utc>, state: ActionState, state_payload: Option<Json>, ) -> ActionRecord { ActionRecord { agent_version, args, created_ts, finished_ts, headers, id, kind, requester, scheduled_ts, state, state_payload, } } /// Initialise a new action to be executed. pub fn new<S>( kind: S, id: Option<Uuid>, created_ts: Option<DateTime<Utc>>, args: Json, requester: ActionRequester, ) -> ActionRecord where S: Into<String>, { let kind = kind.into(); let id = id.unwrap_or_else(Uuid::new_v4); let created_ts = created_ts.unwrap_or_else(Utc::now); ActionRecord { agent_version: env!("CARGO_PKG_VERSION").to_string(), args, created_ts, finished_ts: None, headers: HashMap::new(), id, kind, requester, scheduled_ts: Utc::now(), state: ActionState::New, state_payload: None, } } /// Extract the tracing context, if any is available. pub fn trace_get(&self, tracer: &Tracer) -> Result<Option<SpanContext>> { let format = ExtractFormat::TextMap(Box::new(&self.headers)); let context = tracer .extract(format) .map_err(failure::SyncFailure::new) .with_context(|_| ErrorKind::ActionDecode)?; Ok(context) } /// Set the tracing context on the action record for propagation. pub fn trace_set(&mut self, context: &SpanContext, tracer: &Tracer) -> Result<()> { let format = InjectFormat::TextMap(Box::new(&mut self.headers)); tracer .inject(context, format) .map_err(failure::SyncFailure::new) .with_context(|_| ErrorKind::ActionEncode)?; Ok(()) } /// Test helper to set an action state. #[cfg(any(test, feature = "with_test_support"))] pub fn set_state(&mut self, state: ActionState) { self.state = state; } /// Test helper to set an action payload. #[cfg(any(test, feature = "with_test_support"))] pub fn set_state_payload(&mut self, payload: Option<Json>) { self.state_payload = payload; } } impl From<ActionRecord> for ActionModel { fn from(record: ActionRecord) -> ActionModel { ActionModel { args: record.args, created_ts: record.created_ts, finished_ts: record.finished_ts, headers: record.headers, id: record.id, kind: record.kind, requester: record.requester, scheduled_ts: record.scheduled_ts, state: record.state, state_payload: record.state_payload, } } } /// A dynamic view on `ActionRecord`s. /// /// Allows actions to be composable by "presenting" the state a "nested action expects. /// Look at the `replicante.service.restart` action for an example. pub trait ActionRecordView { /// Access the action arguments. fn args(&self) -> &Json; /// Access the raw record, mainly to pass it to the store interface. fn inner(&self) -> &ActionRecord; /// Manipulte the next state and payload to transition to. fn map_transition( &self, transition_to: ActionState, payload: Option<Json>, ) -> Result<(ActionState, Option<Json>)>; /// Access the state the action is currently in. fn state(&self) -> &ActionState; /// Access the associated state payload, if any. fn state_payload(&self) -> &Option<Json>; } impl dyn ActionRecordView { /// Return the action headers. pub fn headers(view: &dyn ActionRecordView) -> &HashMap<String, String> { &view.inner().headers } /// Return the action ID. pub fn id(view: &dyn ActionRecordView) -> Uuid { view.inner().id } /// Access the state as stored in the ActionRecord. pub fn raw_state(record: &ActionRecord) -> &ActionState { &record.state } /// Extract a structured payload, if any was stored for the action. pub fn structured_state_payload<T>(view: &dyn ActionRecordView) -> Result<Option<T>> where T: DeserializeOwned, { let payload = view .state_payload() .clone() .map(serde_json::from_value) .transpose() .with_context(|_| ErrorKind::ActionDecode)?; Ok(payload) } } impl ActionRecordView for ActionRecord { fn args(&self) -> &Json { &self.args } fn inner(&self) -> &ActionRecord { self } fn map_transition( &self, transition_to: ActionState, payload: Option<Json>, ) -> Result<(ActionState, Option<Json>)> { Ok((transition_to, payload)) } fn state(&self) -> &ActionState { &self.state } fn state_payload(&self) -> &Option<Json> { &self.state_payload } } /// Result alias for methods that return an ActionValidityError. pub type ActionValidity<T = ()> = std::result::Result<T, ActionValidityError>; /// Result of action validation process. #[derive(Debug, Fail)] pub enum ActionValidityError { #[fail(display = "invalid action arguments: {}", _0)] InvalidArgs(String), } impl ActionValidityError { fn kind(&self) -> &str { match self { ActionValidityError::InvalidArgs(_) => "InvalidArgs", } } } impl ResponseError for ActionValidityError { fn status_code(&self) -> StatusCode { StatusCode::BAD_REQUEST } fn error_response(&self) -> HttpResponse { let status = self.status_code(); HttpResponse::build(status).json(json!({ "error": self.to_string(), "kind": self.kind(), })) } }
30.604972
94
0.636429
8ab042fe3e695da2bc1add40e3dadb9829399b42
66
pub mod list; pub mod routes; pub use list::*; pub use routes::*;
13.2
18
0.666667
212b9b7fdce4f8a327883986119223450eb17295
38,385
use std::sync::{Condvar, Mutex}; use std::sync::atomic::{AtomicBool, AtomicUsize}; #[cfg(target_pointer_width = "32")] use std::sync::atomic::AtomicI64; #[cfg(target_pointer_width = "64")] use std::sync::atomic::AtomicIsize; use std::sync::atomic::Ordering::SeqCst; #[cfg(feature = "failpoints")] use std::sync::atomic::Ordering::Relaxed; #[cfg(feature = "zstd")] use zstd::block::compress; use self::reader::LogReader; use super::*; type Header = u64; #[cfg(target_pointer_width = "64")] type AtomicLsn = AtomicIsize; #[cfg(target_pointer_width = "32")] type AtomicLsn = AtomicI64; macro_rules! io_fail { ($self:expr, $e:expr) => { #[cfg(feature = "failpoints")] fail_point!($e, |_| { $self._failpoint_crashing.store(true, SeqCst); // wake up any waiting threads so they don't stall forever $self.interval_updated.notify_all(); Err(Error::FailPoint) }); } } struct IoBuf { buf: UnsafeCell<Vec<u8>>, header: AtomicUsize, lid: AtomicUsize, lsn: AtomicUsize, capacity: AtomicUsize, maxed: AtomicBool, linearizer: Mutex<()>, } unsafe impl Sync for IoBuf {} pub(super) struct IoBufs { config: Config, bufs: Vec<IoBuf>, current_buf: AtomicUsize, written_bufs: AtomicUsize, // Pending intervals that have been written to stable storage, but may be // higher than the current value of `stable` due to interesting thread // interleavings. pub(super) intervals: Mutex<Vec<(Lsn, Lsn)>>, pub(super) interval_updated: Condvar, // The highest CONTIGUOUS log sequence number that has been written to // stable storage. This may be lower than the length of the underlying // file, and there may be buffers that have been written out-of-order // to stable storage due to interesting thread interleavings. stable_lsn: AtomicLsn, max_reserved_lsn: AtomicLsn, segment_accountant: Mutex<SegmentAccountant>, // used for signifying that we're simulating a crash #[cfg(feature = "failpoints")] _failpoint_crashing: AtomicBool, } /// `IoBufs` is a set of lock-free buffers for coordinating /// writes to underlying storage. impl IoBufs { pub fn start<R>( config: Config, mut snapshot: Snapshot<R>, ) -> CacheResult<IoBufs, ()> { // open file for writing let file = config.file()?; let io_buf_size = config.io_buf_size; let snapshot_max_lsn = snapshot.max_lsn; let snapshot_last_lid = snapshot.last_lid; let (next_lsn, next_lid) = if snapshot_max_lsn < SEG_HEADER_LEN as Lsn { snapshot.max_lsn = 0; snapshot.last_lid = 0; (0, 0) } else { match file.read_message( snapshot_last_lid, io_buf_size, config.use_compression, ) { Ok(LogRead::Flush(_lsn, _buf, len)) => ( snapshot_max_lsn + len as Lsn + MSG_HEADER_LEN as Lsn, snapshot_last_lid + len as LogID + MSG_HEADER_LEN as LogID, ), other => { // we can overwrite this non-flush debug!( "got non-flush tip while recovering at {}: {:?}", snapshot_last_lid, other ); (snapshot_max_lsn, snapshot_last_lid) } } }; let mut segment_accountant = SegmentAccountant::start(config.clone(), snapshot)?; let bufs = rep_no_copy![IoBuf::new(io_buf_size); config.io_bufs]; let current_buf = 0; trace!( "starting IoBufs with next_lsn: {} \ next_lid: {}", next_lsn, next_lid ); if next_lsn == 0 { // recovering at segment boundary assert_eq!(next_lid, next_lsn as LogID); let iobuf = &bufs[current_buf]; let lid = segment_accountant.next(next_lsn)?; iobuf.set_lid(lid); iobuf.set_capacity(io_buf_size - SEG_TRAILER_LEN); iobuf.store_segment_header(0, next_lsn); maybe_fail!("initial allocation"); file.pwrite_all(&*vec![0; config.io_buf_size], lid)?; file.sync_all()?; maybe_fail!("initial allocation post"); debug!( "starting log at clean offset {}, recovered lsn {}", next_lid, next_lsn ); } else { // the tip offset is not completely full yet, reuse it let iobuf = &bufs[current_buf]; let offset = next_lid % io_buf_size as LogID; iobuf.set_lid(next_lid); iobuf.set_capacity(io_buf_size - offset as usize - SEG_TRAILER_LEN); iobuf.set_lsn(next_lsn); debug!( "starting log at split offset {}, recovered lsn {}", next_lid, next_lsn ); } // we want stable to begin at -1, since the 0th byte // of our file has not yet been written. let stable = if next_lsn == 0 { -1 } else { next_lsn - 1 }; Ok(IoBufs { bufs: bufs, current_buf: AtomicUsize::new(current_buf), written_bufs: AtomicUsize::new(0), intervals: Mutex::new(vec![]), interval_updated: Condvar::new(), stable_lsn: AtomicLsn::new(stable), max_reserved_lsn: AtomicLsn::new(stable), config: config, segment_accountant: Mutex::new(segment_accountant), #[cfg(feature = "failpoints")] _failpoint_crashing: AtomicBool::new(false), }) } /// SegmentAccountant access for coordination with the `PageCache` pub(super) fn with_sa<B, F>(&self, f: F) -> B where F: FnOnce(&mut SegmentAccountant) -> B { let start = clock(); let mut sa = self.segment_accountant.lock().unwrap(); let locked_at = clock(); M.accountant_lock.measure(locked_at - start); let ret = f(&mut sa); M.accountant_hold.measure(clock() - locked_at); ret } fn idx(&self) -> usize { debug_delay(); let current_buf = self.current_buf.load(SeqCst); current_buf % self.config.io_bufs } /// Returns the last stable offset in storage. pub(super) fn stable(&self) -> Lsn { debug_delay(); self.stable_lsn.load(SeqCst) as Lsn } // Adds a header to the buffer, and optionally compresses // the buffer. // NB the caller is responsible for later setting the Lsn // bytes after a reservation has been acquired. fn encapsulate(&self, raw_buf: Vec<u8>) -> Vec<u8> { #[cfg(feature = "zstd")] let buf = if self.config.use_compression { let _measure = Measure::new(&M.compress); compress(&*raw_buf, self.config.get_zstd_compression_factor()) .unwrap() } else { raw_buf }; #[cfg(not(feature = "zstd"))] let buf = raw_buf; let crc16 = crc16_arr(&buf); let header = MessageHeader { kind: MessageKind::Success, lsn: 0, len: buf.len(), crc16: crc16, }; let header_bytes: [u8; MSG_HEADER_LEN] = header.into(); let mut out = vec![0; MSG_HEADER_LEN + buf.len()]; out[0..MSG_HEADER_LEN].copy_from_slice(&header_bytes); out[MSG_HEADER_LEN..].copy_from_slice(&*buf); out } /// Tries to claim a reservation for writing a buffer to a /// particular location in stable storge, which may either be /// completed or aborted later. Useful for maintaining /// linearizability across CAS operations that may need to /// persist part of their operation. /// /// # Panics /// /// Panics if the desired reservation is greater than the /// io buffer size minus the size of a segment header + /// a segment footer + a message header. pub(super) fn reserve( &self, raw_buf: Vec<u8>, ) -> CacheResult<Reservation, ()> { let _measure = Measure::new(&M.reserve); let io_bufs = self.config.io_bufs; // right shift 32 on 32-bit pointer systems panics #[cfg(target_pointer_width = "64")] assert_eq!((raw_buf.len() + MSG_HEADER_LEN) >> 32, 0); let buf = self.encapsulate(raw_buf); let max_overhead = if self.config.min_items_per_segment == 1 { SEG_HEADER_LEN + SEG_TRAILER_LEN } else { std::cmp::max(SEG_HEADER_LEN, SEG_TRAILER_LEN) }; let max_buf_size = (self.config.io_buf_size / self.config.min_items_per_segment) - max_overhead; if buf.len() > max_buf_size { return Err(Error::Unsupported(format!( "trying to write a buffer that is too large \ to be stored in the IO buffer. buf len: {} current max: {}. \ a future version of pagecache will implement automatic \ fragmentation of large values. feel free to open \ an issue if this is a pressing need of yours.", buf.len(), max_buf_size ))); } trace!("reserving buf of len {}", buf.len()); let mut printed = false; macro_rules! trace_once { ($($msg:expr),*) => { if !printed { trace!($($msg),*); printed = true; }}; } let mut spins = 0; loop { debug_delay(); let written_bufs = self.written_bufs.load(SeqCst); debug_delay(); let current_buf = self.current_buf.load(SeqCst); let idx = current_buf % io_bufs; spins += 1; if spins > 1_000_000 { debug!( "stalling in reserve, idx {}, buf len {}", idx, buf.len() ); spins = 0; } if written_bufs > current_buf { // This can happen because a reservation can finish up // before the sealing thread gets around to bumping // current_buf. trace_once!("written ahead of sealed, spinning"); M.log_looped(); #[cfg(feature = "failpoints")] { if self._failpoint_crashing.load(Relaxed) { return Err(Error::FailPoint); } } yield_now(); continue; } if current_buf - written_bufs >= io_bufs { // if written is too far behind, we need to // spin while it catches up to avoid overlap trace_once!("old io buffer not written yet, spinning"); M.log_looped(); #[cfg(feature = "failpoints")] { if self._failpoint_crashing.load(Relaxed) { return Err(Error::FailPoint); } } yield_now(); continue; } // load current header value let iobuf = &self.bufs[idx]; let header = iobuf.get_header(); // skip if already sealed if is_sealed(header) { // already sealed, start over and hope cur // has already been bumped by sealer. trace_once!("io buffer already sealed, spinning"); M.log_looped(); #[cfg(feature = "failpoints")] { if self._failpoint_crashing.load(Relaxed) { return Err(Error::FailPoint); } } yield_now(); continue; } // try to claim space let buf_offset = offset(header); let prospective_size = buf_offset as usize + buf.len(); let would_overflow = prospective_size > iobuf.get_capacity(); if would_overflow { // This buffer is too full to accept our write! // Try to seal the buffer, and maybe write it if // there are zero writers. trace_once!("io buffer too full, spinning"); self.maybe_seal_and_write_iobuf(idx, header, true)?; M.log_looped(); #[cfg(feature = "failpoints")] { if self._failpoint_crashing.load(Relaxed) { return Err(Error::FailPoint); } } yield_now(); continue; } // attempt to claim by incrementing an unsealed header let bumped_offset = bump_offset(header, buf.len() as Header); let claimed = incr_writers(bumped_offset); assert!(!is_sealed(claimed)); if iobuf.cas_header(header, claimed).is_err() { // CAS failed, start over trace_once!("CAS failed while claiming buffer slot, spinning"); M.log_looped(); #[cfg(feature = "failpoints")] { if self._failpoint_crashing.load(Relaxed) { return Err(Error::FailPoint); } } yield_now(); continue; } // if we're giving out a reservation, // the writer count should be positive assert_ne!(n_writers(claimed), 0); let lid = iobuf.get_lid(); assert_ne!( lid as usize, std::usize::MAX, "fucked up on idx {}\n{:?}", idx, self ); let out_buf = unsafe { (*iobuf.buf.get()).as_mut_slice() }; let res_start = buf_offset as usize; let res_end = res_start + buf.len(); let destination = &mut (out_buf)[res_start..res_end]; let reservation_offset = lid + u64::from(buf_offset); let reservation_lsn = iobuf.get_lsn() + u64::from(buf_offset) as Lsn; // we assign the LSN now that we know what it is assert_eq!(&buf[1..9], &[0u8; 8]); let lsn_bytes: [u8; 8] = unsafe { std::mem::transmute(reservation_lsn) }; let mut buf = buf; buf[1..9].copy_from_slice(&lsn_bytes); trace!( "reserved {} bytes at lsn {} lid {}", buf.len(), reservation_lsn, reservation_offset, ); self.bump_max_reserved_lsn(reservation_lsn); return Ok(Reservation { idx: idx, iobufs: self, data: buf, destination: destination, flushed: false, lsn: reservation_lsn, lid: reservation_offset, }); } } /// Called by Reservation on termination (completion or abort). /// Handles departure from shared state, and possibly writing /// the buffer to stable storage if necessary. pub(super) fn exit_reservation(&self, idx: usize) -> CacheResult<(), ()> { let iobuf = &self.bufs[idx]; let mut header = iobuf.get_header(); // Decrement writer count, retrying until successful. let mut spins = 0; loop { spins += 1; if spins > 10 { debug!("have spun >10x in decr"); spins = 0; } let new_hv = decr_writers(header); match iobuf.cas_header(header, new_hv) { Ok(new) => { header = new; break; } Err(new) => { // we failed to decr, retry header = new; } } } // Succeeded in decrementing writers, if we decremented writers // to 0 and it's sealed then we should write it to storage. if n_writers(header) == 0 && is_sealed(header) { trace!("exiting idx {} from res", idx); self.write_to_log(idx) } else { Ok(()) } } /// blocks until the specified log sequence number has /// been made stable on disk pub fn make_stable(&self, lsn: Lsn) -> CacheResult<(), ()> { let _measure = Measure::new(&M.make_stable); // NB before we write the 0th byte of the file, stable is -1 while self.stable() < lsn { let idx = self.idx(); let header = self.bufs[idx].get_header(); if offset(header) == 0 || is_sealed(header) { // nothing to write, don't bother sealing // current IO buffer. } else { self.maybe_seal_and_write_iobuf(idx, header, false)?; continue; } // block until another thread updates the stable lsn let waiter = self.intervals.lock().unwrap(); if self.stable() < lsn { #[cfg(feature = "failpoints")] { if self._failpoint_crashing.load(SeqCst) { return Err(Error::FailPoint); } } trace!("waiting on cond var for make_stable({})", lsn); let _waiter = self.interval_updated.wait(waiter).unwrap(); } else { trace!("make_stable({}) returning", lsn); break; } } Ok(()) } /// Called by users who wish to force the current buffer /// to flush some pending writes. pub(super) fn flush(&self) -> CacheResult<(), ()> { let max_reserved_lsn = self.max_reserved_lsn.load(SeqCst); self.make_stable(max_reserved_lsn) } // ensure self.max_reserved_lsn is set to this Lsn // or greater, for use in correct calls to flush. fn bump_max_reserved_lsn(&self, lsn: Lsn) { let mut current = self.max_reserved_lsn.load(SeqCst); loop { if current >= lsn { return; } let last = self.max_reserved_lsn.compare_and_swap(current, lsn, SeqCst); if last == current { // we succeeded. return; } current = last; } } // Attempt to seal the current IO buffer, possibly // writing it to disk if there are no other writers // operating on it. fn maybe_seal_and_write_iobuf( &self, idx: usize, header: Header, from_reserve: bool, ) -> CacheResult<(), ()> { let iobuf = &self.bufs[idx]; if is_sealed(header) { // this buffer is already sealed. nothing to do here. return Ok(()); } // NB need to do this before CAS because it can get // written and reset by another thread afterward let lid = iobuf.get_lid(); let lsn = iobuf.get_lsn(); let capacity = iobuf.get_capacity(); let io_buf_size = self.config.io_buf_size; if offset(header) as usize > capacity { // a race happened, nothing we can do return Ok(()); } let should_pad = from_reserve && capacity - offset(header) as usize >= MSG_HEADER_LEN; let sealed = if should_pad { mk_sealed(bump_offset(header, capacity as LogID - offset(header))) } else { mk_sealed(header) }; let res_len = offset(sealed) as usize; let maxed = res_len == capacity; let worked = iobuf.linearized(|| { if iobuf.cas_header(header, sealed).is_err() { // cas failed, don't try to continue return false; } trace!("{} sealed", idx); if from_reserve || maxed { // NB we linearize this together with sealing // the header here to guarantee that in write_to_log, // which may be executing as soon as the seal is set // by another thread, the thread that calls // iobuf.get_maxed() is linearized with this one! trace!("setting maxed to true for idx {}", idx); iobuf.set_maxed(true); } true }); if !worked { return Ok(()); } if should_pad { let offset = offset(header) as usize; let data = unsafe { (*iobuf.buf.get()).as_mut_slice() }; let len = capacity - offset - MSG_HEADER_LEN; // take the crc of the random bytes already after where we // would place our header. let padding_bytes = vec![EVIL_BYTE; len]; let crc16 = crc16_arr(&*padding_bytes); let header = MessageHeader { kind: MessageKind::Pad, lsn: lsn + offset as Lsn, len: len, crc16: crc16, }; let header_bytes: [u8; MSG_HEADER_LEN] = header.into(); data[offset..offset + MSG_HEADER_LEN].copy_from_slice( &header_bytes, ); data[offset + MSG_HEADER_LEN..capacity].copy_from_slice( &*padding_bytes, ); } assert!( capacity + SEG_HEADER_LEN >= res_len, "res_len of {} higher than buffer capacity {}", res_len, capacity ); let max = std::usize::MAX as LogID; assert_ne!( lid, max, "sealing something that should never have \ been claimed (idx {})\n{:?}", idx, self ); // open new slot let mut next_lsn = lsn; let next_offset = if from_reserve || maxed { // roll lsn to the next offset let lsn_idx = lsn / io_buf_size as Lsn; next_lsn = (lsn_idx + 1) * io_buf_size as Lsn; let segment_remainder = next_lsn - (lsn + res_len as Lsn); // mark unused as clear debug!( "rolling to new segment after clearing {}-{}", lid, lid + res_len as LogID, ); // we want to just mark the part that won't get marked in // write_to_log, which is basically just the wasted tip here. let low_lsn = lsn + res_len as Lsn; self.mark_interval(low_lsn, segment_remainder as usize); let ret = self.with_sa(|sa| sa.next(next_lsn)); #[cfg(feature = "failpoints")] { if let Err(Error::FailPoint) = ret { self._failpoint_crashing.store(true, SeqCst); // wake up any waiting threads so they don't stall forever self.interval_updated.notify_all(); } } ret? } else { debug!( "advancing offset within the current segment from {} to {}", lid, lid + res_len as LogID ); next_lsn += res_len as Lsn; let next_offset = lid + res_len as LogID; next_offset }; let next_idx = (idx + 1) % self.config.io_bufs; let next_iobuf = &self.bufs[next_idx]; // NB we spin on this CAS because the next iobuf may not actually // be written to disk yet! (we've lapped the writer in the iobuf // ring buffer) let mut spins = 0; while next_iobuf.cas_lid(max, next_offset).is_err() { spins += 1; if spins > 1_000_000 { debug!("have spun >1,000,000x in seal of buf {}", idx); spins = 0; } #[cfg(feature = "failpoints")] { if self._failpoint_crashing.load(Relaxed) { // panic!("propagating failpoint"); return Err(Error::FailPoint); } } yield_now(); } trace!("{} log set to {}", next_idx, next_offset); // NB as soon as the "sealed" bit is 0, this allows new threads // to start writing into this buffer, so do that after it's all // set up. expect this thread to block until the buffer completes // its entire lifecycle as soon as we do that. if from_reserve || maxed { next_iobuf.set_capacity(io_buf_size - SEG_TRAILER_LEN); next_iobuf.store_segment_header(sealed, next_lsn); } else { let new_cap = capacity - res_len; assert_ne!(new_cap, 0); next_iobuf.set_capacity(new_cap); next_iobuf.set_lsn(next_lsn); let last_salt = salt(sealed); let new_salt = bump_salt(last_salt); next_iobuf.set_header(new_salt); } trace!("{} zeroed header", next_idx); debug_delay(); let _current_buf = self.current_buf.fetch_add(1, SeqCst) + 1; trace!("{} current_buf", _current_buf % self.config.io_bufs); // if writers is 0, it's our responsibility to write the buffer. if n_writers(sealed) == 0 { self.write_to_log(idx) } else { Ok(()) } } // Write an IO buffer's data to stable storage and set up the // next IO buffer for writing. fn write_to_log(&self, idx: usize) -> CacheResult<(), ()> { let _measure = Measure::new(&M.write_to_log); let iobuf = &self.bufs[idx]; let header = iobuf.get_header(); let lid = iobuf.get_lid(); let base_lsn = iobuf.get_lsn(); let io_buf_size = self.config.io_buf_size; assert_eq!( (lid % io_buf_size as LogID) as Lsn, base_lsn % io_buf_size as Lsn ); assert_ne!( lid as usize, std::usize::MAX, "created reservation for uninitialized slot", ); let res_len = offset(header) as usize; let data = unsafe { (*iobuf.buf.get()).as_mut_slice() }; let f = self.config.file()?; io_fail!(self, "buffer write"); f.pwrite_all(&data[..res_len], lid)?; f.sync_all()?; io_fail!(self, "buffer write post"); if res_len > 0 { debug!( "wrote lsns {}-{} to disk at offsets {}-{}", base_lsn, base_lsn + res_len as Lsn - 1, lid, lid + res_len as LogID - 1 ); self.mark_interval(base_lsn, res_len); } // write a trailer if we're maxed let maxed = iobuf.linearized(|| iobuf.get_maxed()); if maxed { let segment_lsn = base_lsn / io_buf_size as Lsn * io_buf_size as Lsn; let segment_lid = lid / io_buf_size as LogID * io_buf_size as LogID; let trailer_overhang = io_buf_size as Lsn - SEG_TRAILER_LEN as Lsn; let trailer_lid = segment_lid + trailer_overhang as LogID; let trailer_lsn = segment_lsn + trailer_overhang; let trailer = SegmentTrailer { lsn: trailer_lsn, ok: true, }; let trailer_bytes: [u8; SEG_TRAILER_LEN] = trailer.into(); io_fail!(self, "trailer write"); f.pwrite_all(&trailer_bytes, trailer_lid)?; f.sync_all()?; io_fail!(self, "trailer write post"); iobuf.set_maxed(false); debug!( "wrote trailer at lid {} for lsn {}", trailer_lid, trailer_lsn ); // transition this segment into deplete-only mode now // that n_writers is 0, and all calls to mark_replace/link // happen before the reservation completes. trace!( "deactivating segment with lsn {} at idx {} with lid {}", segment_lsn, idx, lid ); self.with_sa(|sa| sa.deactivate_segment(segment_lsn, segment_lid)); } else { trace!( "not deactivating segment with lsn {}", base_lsn / io_buf_size as Lsn * io_buf_size as Lsn ); } M.written_bytes.measure(res_len as f64); // signal that this IO buffer is now uninitialized let max = std::usize::MAX as LogID; iobuf.set_lid(max); trace!("{} log <- MAX", idx); // communicate to other threads that we have written an IO buffer. debug_delay(); let _written_bufs = self.written_bufs.fetch_add(1, SeqCst); trace!("{} written", _written_bufs % self.config.io_bufs); Ok(()) } // It's possible that IO buffers are written out of order! // So we need to use this to keep track of them, and only // increment self.stable. If we didn't do this, then we would // accidentally decrement self.stable sometimes, or bump stable // above an offset that corresponds to a buffer that hasn't actually // been written yet! It's OK to use a mutex here because it is pretty // fast, compared to the other operations on shared state. fn mark_interval(&self, whence: Lsn, len: usize) { trace!("mark_interval({}, {})", whence, len); assert_ne!( len, 0, "mark_interval called with a zero-length range, starting from {}", whence ); let mut intervals = self.intervals.lock().unwrap(); let interval = (whence, whence + len as Lsn - 1); intervals.push(interval); debug_assert!( intervals.len() < 1000, "intervals is getting crazy... {:?}", *intervals ); // reverse sort intervals.sort_unstable_by(|a, b| b.cmp(a)); let mut updated = false; let len_before = intervals.len(); while let Some(&(low, high)) = intervals.last() { assert_ne!(low, high); let cur_stable = self.stable_lsn.load(SeqCst); // FIXME somehow, we marked offset 2233715 stable while interval 2231715-2231999 had // not yet been applied! assert!( low > cur_stable, "somehow, we marked offset {} stable while \ interval {}-{} had not yet been applied!", cur_stable, low, high ); if cur_stable + 1 == low { let old = self.stable_lsn.swap(high, SeqCst); assert_eq!( old, cur_stable, "concurrent stable offset modification detected" ); debug!("new highest interval: {} - {}", low, high); intervals.pop(); updated = true; } else { break; } } if len_before - intervals.len() > 100 { debug!("large merge of {} intervals", len_before - intervals.len()); } if updated { self.interval_updated.notify_all(); } } } impl Drop for IoBufs { fn drop(&mut self) { // don't do any more IO if we're simulating a crash #[cfg(feature = "failpoints")] { if self._failpoint_crashing.load(SeqCst) { return; } } if let Err(e) = self.flush() { error!("failed to flush from IoBufs::drop: {}", e); } if let Ok(f) = self.config.file() { f.sync_all().unwrap(); } debug!("IoBufs dropped"); } } impl periodic::Callback for std::sync::Arc<IoBufs> { fn call(&self) { if let Err(e) = self.flush() { #[cfg(feature = "failpoints")] { if let Error::FailPoint = e { self._failpoint_crashing.store(true, SeqCst); // wake up any waiting threads so they don't stall forever self.interval_updated.notify_all(); } } error!("failed to flush from periodic flush thread: {}", e); } } } impl Debug for IoBufs { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { debug_delay(); let current_buf = self.current_buf.load(SeqCst); debug_delay(); let written_bufs = self.written_bufs.load(SeqCst); formatter.write_fmt(format_args!( "IoBufs {{ sealed: {}, written: {}, bufs: {:?} }}", current_buf, written_bufs, self.bufs )) } } impl Debug for IoBuf { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { let header = self.get_header(); formatter.write_fmt(format_args!( "\n\tIoBuf {{ lid: {}, n_writers: {}, offset: \ {}, sealed: {} }}", self.get_lid(), n_writers(header), offset(header), is_sealed(header) )) } } impl IoBuf { fn new(buf_size: usize) -> IoBuf { IoBuf { buf: UnsafeCell::new(vec![0; buf_size]), header: AtomicUsize::new(0), lid: AtomicUsize::new(std::usize::MAX), lsn: AtomicUsize::new(0), capacity: AtomicUsize::new(0), maxed: AtomicBool::new(false), linearizer: Mutex::new(()), } } // use this for operations on an IoBuf that must be // linearized together, and can't fit in the header! fn linearized<F, B>(&self, f: F) -> B where F: FnOnce() -> B { let _l = self.linearizer.lock().unwrap(); f() } // This is called upon the initialization of a fresh segment. // We write a new segment header to the beginning of the buffer // for assistance during recovery. The caller is responsible // for ensuring that the IoBuf's capacity has been set properly. fn store_segment_header(&self, last: Header, lsn: Lsn) { debug!("storing lsn {} in beginning of buffer", lsn); assert!(self.get_capacity() >= SEG_HEADER_LEN + SEG_TRAILER_LEN); self.set_lsn(lsn); let header = SegmentHeader { lsn: lsn, ok: true, }; let header_bytes: [u8; SEG_HEADER_LEN] = header.into(); unsafe { (*self.buf.get())[0..SEG_HEADER_LEN].copy_from_slice(&header_bytes); } // ensure writes to the buffer land after our header. let last_salt = salt(last); let new_salt = bump_salt(last_salt); let bumped = bump_offset(new_salt, SEG_HEADER_LEN as Header); self.set_header(bumped); } fn set_capacity(&self, cap: usize) { debug_delay(); self.capacity.store(cap, SeqCst); } fn get_capacity(&self) -> usize { debug_delay(); self.capacity.load(SeqCst) } fn set_lsn(&self, lsn: Lsn) { debug_delay(); self.lsn.store(lsn as usize, SeqCst); } fn set_maxed(&self, maxed: bool) { debug_delay(); self.maxed.store(maxed, SeqCst); } fn get_maxed(&self) -> bool { debug_delay(); self.maxed.load(SeqCst) } fn get_lsn(&self) -> Lsn { debug_delay(); self.lsn.load(SeqCst) as Lsn } fn set_lid(&self, offset: LogID) { debug_delay(); self.lid.store(offset as usize, SeqCst); } fn get_lid(&self) -> LogID { debug_delay(); self.lid.load(SeqCst) as LogID } fn get_header(&self) -> Header { debug_delay(); self.header.load(SeqCst) as Header } fn set_header(&self, new: Header) { debug_delay(); self.header.store(new as usize, SeqCst); } fn cas_header(&self, old: Header, new: Header) -> Result<Header, Header> { debug_delay(); let res = self.header.compare_and_swap( old as usize, new as usize, SeqCst, ) as Header; if res == old { Ok(new) } else { Err(res) } } fn cas_lid(&self, old: LogID, new: LogID) -> Result<LogID, LogID> { debug_delay(); let res = self.lid.compare_and_swap( old as usize, new as usize, SeqCst, ) as LogID; if res == old { Ok(new) } else { Err(res) } } } #[inline(always)] fn is_sealed(v: Header) -> bool { v & 1 << 31 == 1 << 31 } #[inline(always)] fn mk_sealed(v: Header) -> Header { v | 1 << 31 } #[inline(always)] fn n_writers(v: Header) -> Header { v << 33 >> 57 } #[inline(always)] fn incr_writers(v: Header) -> Header { assert_ne!(n_writers(v), 127); v + (1 << 24) } #[inline(always)] fn decr_writers(v: Header) -> Header { assert_ne!(n_writers(v), 0); v - (1 << 24) } #[inline(always)] fn offset(v: Header) -> Header { v << 40 >> 40 } #[inline(always)] fn bump_offset(v: Header, by: Header) -> Header { assert_eq!(by >> 24, 0); v + by } #[inline(always)] fn bump_salt(v: Header) -> Header { (v + (1 << 32)) & 0xFFFFFFFF00000000 } #[inline(always)] fn salt(v: Header) -> Header { v >> 32 << 32 } #[inline(always)] fn yield_now() { #[cfg(nightly)] { std::sync::atomic::hint_core_should_pause(); } #[cfg(not(nightly))] { std::thread::yield_now(); } }
31.907731
96
0.516504
90bd78be76c51472bcc9fa3a76d395a751020984
782
use super::Identifier; use grin_core::ser; /// Map of named accounts to BIP32 paths #[derive(Clone, Debug, Serialize, Deserialize)] pub struct AcctPathMapping { /// label used by user pub label: String, /// Corresponding parent BIP32 derivation path pub path: Identifier, } impl ser::Writeable for AcctPathMapping { fn write<W: ser::Writer>(&self, writer: &mut W) -> Result<(), ser::Error> { writer.write_bytes(&serde_json::to_vec(self).map_err(|_| ser::Error::CorruptedData)?) } } impl ser::Readable for AcctPathMapping { fn read(reader: &mut dyn ser::Reader) -> Result<AcctPathMapping, ser::Error> { let data = reader.read_bytes_len_prefix()?; serde_json::from_slice(&data[..]).map_err(|_| ser::Error::CorruptedData) } }
31.28
93
0.675192
abb0ced4d64976bf92a1b6e4005cb908e99197b4
8,833
macro_rules! aead_module (($seal_name:ident, $open_name:ident, $seal_detached_name:ident, $open_detached_name:ident, $keybytes:expr, $noncebytes:expr, $tagbytes:expr) => ( #[cfg(not(feature = "std"))] use prelude::*; use libc::c_ulonglong; use randombytes::randombytes_into; /// Number of bytes in a `Key`. pub const KEYBYTES: usize = $keybytes as usize; /// Number of bytes in a `Nonce`. pub const NONCEBYTES: usize = $noncebytes as usize; /// Number of bytes in an authentication `Tag`. pub const TAGBYTES: usize = $tagbytes as usize; new_type! { /// `Key` for symmetric authenticated encryption with additional data. /// /// When a `Key` goes out of scope its contents will /// be zeroed out secret Key(KEYBYTES); } new_type! { /// `Nonce` for symmetric authenticated encryption with additional data. nonce Nonce(NONCEBYTES); } new_type! { /// Authentication `Tag` for symmetric authenticated encryption with additional data in /// detached mode. public Tag(TAGBYTES); } /// `gen_key()` randomly generates a secret key /// /// THREAD SAFETY: `gen_key()` is thread-safe provided that you have /// called `sodiumoxide::init()` once before using any other function /// from sodiumoxide. pub fn gen_key() -> Key { let mut k = Key([0u8; KEYBYTES]); randombytes_into(&mut k.0); k } /// `gen_nonce()` randomly generates a nonce /// /// THREAD SAFETY: `gen_key()` is thread-safe provided that you have /// called `sodiumoxide::init()` once before using any other function /// from sodiumoxide. pub fn gen_nonce() -> Nonce { let mut n = Nonce([0u8; NONCEBYTES]); randombytes_into(&mut n.0); n } /// `seal()` encrypts and authenticates a message `m` together with optional plaintext data `ad` /// using a secret key `k` and a nonce `n`. It returns a ciphertext `c`. pub fn seal(m: &[u8], ad: Option<&[u8]>, n: &Nonce, k: &Key) -> Vec<u8> { let (ad_p, ad_len) = ad.map(|ad| (ad.as_ptr(), ad.len() as c_ulonglong)).unwrap_or((0 as *const _, 0)); let mut c = Vec::with_capacity(m.len() + TAGBYTES); let mut clen = c.len() as c_ulonglong; unsafe { $seal_name( c.as_mut_ptr(), &mut clen, m.as_ptr(), m.len() as c_ulonglong, ad_p, ad_len, 0 as *mut _, n.0.as_ptr(), k.0.as_ptr() ); c.set_len(clen as usize); } c } /// `seal_detached()` encrypts and authenticates a message `m` together with optional plaintext data `ad` /// using a secret key `k` and a nonce `n`. /// `m` is encrypted in place, so after this function returns it will contain the ciphertext. /// The detached authentication tag is returned by value. pub fn seal_detached(m: &mut [u8], ad: Option<&[u8]>, n: &Nonce, k: &Key) -> Tag { let (ad_p, ad_len) = ad.map(|ad| (ad.as_ptr(), ad.len() as c_ulonglong)).unwrap_or((0 as *const _, 0)); let mut tag = Tag([0u8; TAGBYTES]); let mut maclen = TAGBYTES as c_ulonglong; unsafe { $seal_detached_name( m.as_mut_ptr(), tag.0.as_mut_ptr(), &mut maclen, m.as_ptr(), m.len() as c_ulonglong, ad_p, ad_len, 0 as *mut _, n.0.as_ptr(), k.0.as_ptr() ); } tag } /// `open()` verifies and decrypts a ciphertext `c` together with optional plaintext data `ad` /// using a secret key `k` and a nonce `n`. /// It returns a plaintext `Ok(m)`. /// If the ciphertext fails verification, `open()` returns `Err(())`. pub fn open(c: &[u8], ad: Option<&[u8]>, n: &Nonce, k: &Key) -> Result<Vec<u8>, ()> { if c.len() < TAGBYTES { return Err(()); } let (ad_p, ad_len) = ad.map(|ad| (ad.as_ptr(), ad.len() as c_ulonglong)).unwrap_or((0 as *const _, 0)); let mut m = Vec::with_capacity(c.len() - TAGBYTES); let mut mlen = m.len() as c_ulonglong; unsafe { let ret = $open_name( m.as_mut_ptr(), &mut mlen, 0 as *mut _, c.as_ptr(), c.len() as c_ulonglong, ad_p, ad_len, n.0.as_ptr(), k.0.as_ptr() ); if ret != 0 { return Err(()); } m.set_len(mlen as usize); } Ok(m) } /// `open_detached()` verifies and decrypts a ciphertext `c` toghether with optional plaintext data `ad` /// and and authentication tag `tag`, using a secret key `k` and a nonce `n`. /// `c` is decrypted in place, so if this function is successful it will contain the plaintext. /// If the ciphertext fails verification, `open_detached()` returns `Err(())`, /// and the ciphertext is not modified. pub fn open_detached(c: &mut [u8], ad: Option<&[u8]>, t: &Tag, n: &Nonce, k: &Key) -> Result<(), ()> { let (ad_p, ad_len) = ad.map(|ad| (ad.as_ptr(), ad.len() as c_ulonglong)).unwrap_or((0 as *const _, 0)); let ret = unsafe { $open_detached_name( c.as_mut_ptr(), 0 as *mut _, c.as_ptr(), c.len() as c_ulonglong, t.0.as_ptr(), ad_p, ad_len, n.0.as_ptr(), k.0.as_ptr() ) }; if ret == 0 { Ok(()) } else { Err(()) } } #[cfg(test)] mod test_m { use super::*; #[test] fn test_seal_open() { use randombytes::randombytes; for i in 0..256usize { let k = gen_key(); let n = gen_nonce(); let ad = randombytes(i); let m = randombytes(i); let c = seal(&m, Some(&ad), &n, &k); let m2 = open(&c, Some(&ad), &n, &k).unwrap(); assert_eq!(m, m2); } } #[test] fn test_seal_open_tamper() { use randombytes::randombytes; for i in 0..32usize { let k = gen_key(); let n = gen_nonce(); let mut ad = randombytes(i); let m = randombytes(i); let mut c = seal(&m, Some(&ad), &n, &k); for j in 0..c.len() { c[j] ^= 0x20; let m2 = open(&c, Some(&ad), &n, &k); c[j] ^= 0x20; assert!(m2.is_err()); } for j in 0..ad.len() { ad[j] ^= 0x20; let m2 = open(&c, Some(&ad), &n, &k); ad[j] ^= 0x20; assert!(m2.is_err()); } } } #[test] fn test_seal_open_detached() { use randombytes::randombytes; for i in 0..256usize { let k = gen_key(); let n = gen_nonce(); let ad = randombytes(i); let mut m = randombytes(i); let m2 = m.clone(); let t = seal_detached(&mut m, Some(&ad), &n, &k); open_detached(&mut m, Some(&ad), &t, &n, &k).unwrap(); assert_eq!(m, m2); } } #[test] fn test_seal_open_detached_tamper() { use randombytes::randombytes; for i in 0..32usize { let k = gen_key(); let n = gen_nonce(); let mut ad = randombytes(i); let mut m = randombytes(i); let mut t = seal_detached(&mut m, Some(&ad), &n, &k); for j in 0..m.len() { m[j] ^= 0x20; let r = open_detached(&mut m, Some(&ad), &t, &n, &k); m[j] ^= 0x20; assert!(r.is_err()); } for j in 0..ad.len() { ad[j] ^= 0x20; let r = open_detached(&mut m, Some(&ad), &t, &n, &k); ad[j] ^= 0x20; assert!(r.is_err()); } for j in 0..t.0.len() { t.0[j] ^= 0x20; let r = open_detached(&mut m, Some(&ad), &t, &n, &k); t.0[j] ^= 0x20; assert!(r.is_err()); } } } #[test] fn test_seal_open_detached_same() { use randombytes::randombytes; for i in 0..256usize { let k = gen_key(); let n = gen_nonce(); let ad = randombytes(i); let mut m = randombytes(i); let c = seal(&m, Some(&ad), &n, &k); let t = seal_detached(&mut m, Some(&ad), &n, &k); assert_eq!(&c[0..c.len()-TAGBYTES], &m[..]); assert_eq!(&c[c.len()-TAGBYTES..], &t.0[..]); let m2 = open(&c, Some(&ad), &n, &k).unwrap(); open_detached(&mut m, Some(&ad), &t, &n, &k).unwrap(); assert_eq!(m2, m); } } } ));
31.434164
107
0.497906
fe87438cce6bf015f10bec5443999b8958233d7e
3,370
/* Copyright 2021 JFrog Ltd 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 super::{get_config, RegistryError, RegistryErrorCode}; use crate::network::client::Client; use crate::node_manager::{handlers::*, model::cli::*}; use log::debug; use std::collections::HashMap; use warp::{http::StatusCode, Rejection, Reply}; pub async fn handle_get_peers(mut p2p_client: Client) -> Result<impl Reply, Rejection> { let peers = p2p_client.list_peers().await.map_err(RegistryError::from)?; debug!("Got received_peers: {:?}", peers); let str_peers: Vec<String> = peers.into_iter().map(|p| p.to_string()).collect(); let str_peers_as_json = serde_json::to_string(&str_peers).unwrap(); Ok(warp::http::response::Builder::new() .header("Content-Type", "application/octet-stream") .status(StatusCode::OK) .body(str_peers_as_json) .unwrap()) } pub async fn handle_get_status(mut p2p_client: Client) -> Result<impl Reply, Rejection> { let peers = p2p_client.list_peers().await.map_err(RegistryError::from)?; let art_count_result = get_arts_summary(); if art_count_result.is_err() { return Err(warp::reject::custom(RegistryError { code: RegistryErrorCode::Unknown(art_count_result.err().unwrap().to_string()), })); } let disk_space_result = disk_usage(); if disk_space_result.is_err() { return Err(warp::reject::custom(RegistryError { code: RegistryErrorCode::Unknown(disk_space_result.err().unwrap().to_string()), })); } let cli_config = get_config(); if cli_config.is_err() { return Err(warp::reject::custom(RegistryError { code: RegistryErrorCode::Unknown(cli_config.err().unwrap().to_string()), })); } let mut total_artifacts = 0; let mut art_summ_map: HashMap<String, usize> = HashMap::new(); for (k, v) in art_count_result.unwrap().iter() { if k == "SHA256" { total_artifacts += v; art_summ_map.insert("blobs".to_string(), *v); } else if k == "SHA512" { total_artifacts += v; art_summ_map.insert("manifests".to_string(), *v); } } let artifacts_summary = ArtifactsSummary { total: total_artifacts.to_string(), summary: art_summ_map, }; let status = Status { artifact_count: artifacts_summary, peers_count: peers.len(), peer_id: p2p_client.local_peer_id.to_string(), disk_allocated: cli_config.unwrap().disk_allocated, disk_usage: format!("{:.4}", disk_space_result.unwrap()), }; let status_as_json = serde_json::to_string(&status).unwrap(); Ok(warp::http::response::Builder::new() .header("Content-Type", "application/json") .status(StatusCode::OK) .body(status_as_json) .unwrap()) }
35.851064
91
0.657864
edddb7e6b314b0262e5e113edfe1ba759cf4f67c
105,576
use crate::binemit::Reloc; use crate::ir::immediates::{Ieee32, Ieee64}; use crate::ir::TrapCode; use crate::isa::x64::inst::args::*; use crate::isa::x64::inst::*; use crate::machinst::{inst_common, MachBuffer, MachInstEmit, MachLabel}; use core::convert::TryInto; use log::debug; use regalloc::{Reg, RegClass, Writable}; use std::convert::TryFrom; fn low8_will_sign_extend_to_64(x: u32) -> bool { let xs = (x as i32) as i64; xs == ((xs << 56) >> 56) } fn low8_will_sign_extend_to_32(x: u32) -> bool { let xs = x as i32; xs == ((xs << 24) >> 24) } //============================================================================= // Instructions and subcomponents: emission // For all of the routines that take both a memory-or-reg operand (sometimes // called "E" in the Intel documentation) and a reg-only operand ("G" in // Intelese), the order is always G first, then E. // // "enc" in the following means "hardware register encoding number". #[inline(always)] fn encode_modrm(m0d: u8, enc_reg_g: u8, rm_e: u8) -> u8 { debug_assert!(m0d < 4); debug_assert!(enc_reg_g < 8); debug_assert!(rm_e < 8); ((m0d & 3) << 6) | ((enc_reg_g & 7) << 3) | (rm_e & 7) } #[inline(always)] fn encode_sib(shift: u8, enc_index: u8, enc_base: u8) -> u8 { debug_assert!(shift < 4); debug_assert!(enc_index < 8); debug_assert!(enc_base < 8); ((shift & 3) << 6) | ((enc_index & 7) << 3) | (enc_base & 7) } /// Get the encoding number of a GPR. #[inline(always)] fn int_reg_enc(reg: Reg) -> u8 { debug_assert!(reg.is_real()); debug_assert_eq!(reg.get_class(), RegClass::I64); reg.get_hw_encoding() } /// Get the encoding number of any register. #[inline(always)] fn reg_enc(reg: Reg) -> u8 { debug_assert!(reg.is_real()); reg.get_hw_encoding() } /// A small bit field to record a REX prefix specification: /// - bit 0 set to 1 indicates REX.W must be 0 (cleared). /// - bit 1 set to 1 indicates the REX prefix must always be emitted. #[repr(transparent)] #[derive(Clone, Copy)] struct RexFlags(u8); impl RexFlags { /// By default, set the W field, and don't always emit. #[inline(always)] fn set_w() -> Self { Self(0) } /// Creates a new RexPrefix for which the REX.W bit will be cleared. #[inline(always)] fn clear_w() -> Self { Self(1) } #[inline(always)] fn always_emit(&mut self) -> &mut Self { self.0 = self.0 | 2; self } #[inline(always)] fn must_clear_w(&self) -> bool { (self.0 & 1) != 0 } #[inline(always)] fn must_always_emit(&self) -> bool { (self.0 & 2) != 0 } #[inline(always)] fn emit_two_op(&self, sink: &mut MachBuffer<Inst>, enc_g: u8, enc_e: u8) { let w = if self.must_clear_w() { 0 } else { 1 }; let r = (enc_g >> 3) & 1; let x = 0; let b = (enc_e >> 3) & 1; let rex = 0x40 | (w << 3) | (r << 2) | (x << 1) | b; if rex != 0x40 || self.must_always_emit() { sink.put1(rex); } } #[inline(always)] fn emit_three_op(&self, sink: &mut MachBuffer<Inst>, enc_g: u8, enc_index: u8, enc_base: u8) { let w = if self.must_clear_w() { 0 } else { 1 }; let r = (enc_g >> 3) & 1; let x = (enc_index >> 3) & 1; let b = (enc_base >> 3) & 1; let rex = 0x40 | (w << 3) | (r << 2) | (x << 1) | b; if rex != 0x40 || self.must_always_emit() { sink.put1(rex); } } } /// We may need to include one or more legacy prefix bytes before the REX prefix. This enum /// covers only the small set of possibilities that we actually need. enum LegacyPrefixes { /// No prefix bytes None, /// Operand Size Override -- here, denoting "16-bit operation" _66, /// The Lock prefix _F0, /// Operand size override and Lock _66F0, /// REPNE, but no specific meaning here -- is just an opcode extension _F2, /// REP/REPE, but no specific meaning here -- is just an opcode extension _F3, } impl LegacyPrefixes { #[inline(always)] fn emit(&self, sink: &mut MachBuffer<Inst>) { match self { LegacyPrefixes::_66 => sink.put1(0x66), LegacyPrefixes::_F0 => sink.put1(0xF0), LegacyPrefixes::_66F0 => { // I don't think the order matters, but in any case, this is the same order that // the GNU assembler uses. sink.put1(0x66); sink.put1(0xF0); } LegacyPrefixes::_F2 => sink.put1(0xF2), LegacyPrefixes::_F3 => sink.put1(0xF3), LegacyPrefixes::None => (), } } } /// This is the core 'emit' function for instructions that reference memory. /// /// For an instruction that has as operands a reg encoding `enc_g` and a memory address `mem_e`, /// create and emit: /// - first the legacy prefixes, if any /// - then the REX prefix, if needed /// - then caller-supplied opcode byte(s) (`opcodes` and `num_opcodes`), /// - then the MOD/RM byte, /// - then optionally, a SIB byte, /// - and finally optionally an immediate that will be derived from the `mem_e` operand. /// /// For most instructions up to and including SSE4.2, that will be the whole instruction: this is /// what we call "standard" instructions, and abbreviate "std" in the name here. VEX-prefixed /// instructions will require their own emitter functions. /// /// This will also work for 32-bits x86 instructions, assuming no REX prefix is provided. /// /// The opcodes are written bigendianly for the convenience of callers. For example, if the opcode /// bytes to be emitted are, in this order, F3 0F 27, then the caller should pass `opcodes` == /// 0xF3_0F_27 and `num_opcodes` == 3. /// /// The register operand is represented here not as a `Reg` but as its hardware encoding, `enc_g`. /// `rex` can specify special handling for the REX prefix. By default, the REX prefix will /// indicate a 64-bit operation and will be deleted if it is redundant (0x40). Note that for a /// 64-bit operation, the REX prefix will normally never be redundant, since REX.W must be 1 to /// indicate a 64-bit operation. fn emit_std_enc_mem( sink: &mut MachBuffer<Inst>, prefixes: LegacyPrefixes, opcodes: u32, mut num_opcodes: usize, enc_g: u8, mem_e: &Amode, rex: RexFlags, ) { // General comment for this function: the registers in `mem_e` must be // 64-bit integer registers, because they are part of an address // expression. But `enc_g` can be derived from a register of any class. prefixes.emit(sink); match mem_e { Amode::ImmReg { simm32, base } => { // First, the REX byte. let enc_e = int_reg_enc(*base); rex.emit_two_op(sink, enc_g, enc_e); // Now the opcode(s). These include any other prefixes the caller // hands to us. while num_opcodes > 0 { num_opcodes -= 1; sink.put1(((opcodes >> (num_opcodes << 3)) & 0xFF) as u8); } // Now the mod/rm and associated immediates. This is // significantly complicated due to the multiple special cases. if *simm32 == 0 && enc_e != regs::ENC_RSP && enc_e != regs::ENC_RBP && enc_e != regs::ENC_R12 && enc_e != regs::ENC_R13 { // FIXME JRS 2020Feb11: those four tests can surely be // replaced by a single mask-and-compare check. We should do // that because this routine is likely to be hot. sink.put1(encode_modrm(0, enc_g & 7, enc_e & 7)); } else if *simm32 == 0 && (enc_e == regs::ENC_RSP || enc_e == regs::ENC_R12) { sink.put1(encode_modrm(0, enc_g & 7, 4)); sink.put1(0x24); } else if low8_will_sign_extend_to_32(*simm32) && enc_e != regs::ENC_RSP && enc_e != regs::ENC_R12 { sink.put1(encode_modrm(1, enc_g & 7, enc_e & 7)); sink.put1((simm32 & 0xFF) as u8); } else if enc_e != regs::ENC_RSP && enc_e != regs::ENC_R12 { sink.put1(encode_modrm(2, enc_g & 7, enc_e & 7)); sink.put4(*simm32); } else if (enc_e == regs::ENC_RSP || enc_e == regs::ENC_R12) && low8_will_sign_extend_to_32(*simm32) { // REX.B distinguishes RSP from R12 sink.put1(encode_modrm(1, enc_g & 7, 4)); sink.put1(0x24); sink.put1((simm32 & 0xFF) as u8); } else if enc_e == regs::ENC_R12 || enc_e == regs::ENC_RSP { //.. wait for test case for RSP case // REX.B distinguishes RSP from R12 sink.put1(encode_modrm(2, enc_g & 7, 4)); sink.put1(0x24); sink.put4(*simm32); } else { unreachable!("ImmReg"); } } Amode::ImmRegRegShift { simm32, base: reg_base, index: reg_index, shift, } => { let enc_base = int_reg_enc(*reg_base); let enc_index = int_reg_enc(*reg_index); // The rex byte. rex.emit_three_op(sink, enc_g, enc_index, enc_base); // All other prefixes and opcodes. while num_opcodes > 0 { num_opcodes -= 1; sink.put1(((opcodes >> (num_opcodes << 3)) & 0xFF) as u8); } // modrm, SIB, immediates. if low8_will_sign_extend_to_32(*simm32) && enc_index != regs::ENC_RSP { sink.put1(encode_modrm(1, enc_g & 7, 4)); sink.put1(encode_sib(*shift, enc_index & 7, enc_base & 7)); sink.put1(*simm32 as u8); } else if enc_index != regs::ENC_RSP { sink.put1(encode_modrm(2, enc_g & 7, 4)); sink.put1(encode_sib(*shift, enc_index & 7, enc_base & 7)); sink.put4(*simm32); } else { panic!("ImmRegRegShift"); } } Amode::RipRelative { ref target } => { // First, the REX byte, with REX.B = 0. rex.emit_two_op(sink, enc_g, 0); // Now the opcode(s). These include any other prefixes the caller // hands to us. while num_opcodes > 0 { num_opcodes -= 1; sink.put1(((opcodes >> (num_opcodes << 3)) & 0xFF) as u8); } // RIP-relative is mod=00, rm=101. sink.put1(encode_modrm(0, enc_g & 7, 0b101)); match *target { BranchTarget::Label(label) => { let offset = sink.cur_offset(); sink.use_label_at_offset(offset, label, LabelUse::JmpRel32); sink.put4(0); } BranchTarget::ResolvedOffset(offset) => { let offset = u32::try_from(offset).expect("rip-relative can't hold >= U32_MAX values"); sink.put4(offset); } } } } } /// This is the core 'emit' function for instructions that do not reference memory. /// /// This is conceptually the same as emit_modrm_sib_enc_ge, except it is for the case where the E /// operand is a register rather than memory. Hence it is much simpler. fn emit_std_enc_enc( sink: &mut MachBuffer<Inst>, prefixes: LegacyPrefixes, opcodes: u32, mut num_opcodes: usize, enc_g: u8, enc_e: u8, rex: RexFlags, ) { // EncG and EncE can be derived from registers of any class, and they // don't even have to be from the same class. For example, for an // integer-to-FP conversion insn, one might be RegClass::I64 and the other // RegClass::V128. // The legacy prefixes. prefixes.emit(sink); // The rex byte. rex.emit_two_op(sink, enc_g, enc_e); // All other prefixes and opcodes. while num_opcodes > 0 { num_opcodes -= 1; sink.put1(((opcodes >> (num_opcodes << 3)) & 0xFF) as u8); } // Now the mod/rm byte. The instruction we're generating doesn't access // memory, so there is no SIB byte or immediate -- we're done. sink.put1(encode_modrm(3, enc_g & 7, enc_e & 7)); } // These are merely wrappers for the above two functions that facilitate passing // actual `Reg`s rather than their encodings. fn emit_std_reg_mem( sink: &mut MachBuffer<Inst>, prefixes: LegacyPrefixes, opcodes: u32, num_opcodes: usize, reg_g: Reg, mem_e: &Amode, rex: RexFlags, ) { let enc_g = reg_enc(reg_g); emit_std_enc_mem(sink, prefixes, opcodes, num_opcodes, enc_g, mem_e, rex); } fn emit_std_reg_reg( sink: &mut MachBuffer<Inst>, prefixes: LegacyPrefixes, opcodes: u32, num_opcodes: usize, reg_g: Reg, reg_e: Reg, rex: RexFlags, ) { let enc_g = reg_enc(reg_g); let enc_e = reg_enc(reg_e); emit_std_enc_enc(sink, prefixes, opcodes, num_opcodes, enc_g, enc_e, rex); } /// Write a suitable number of bits from an imm64 to the sink. fn emit_simm(sink: &mut MachBuffer<Inst>, size: u8, simm32: u32) { match size { 8 | 4 => sink.put4(simm32), 2 => sink.put2(simm32 as u16), 1 => sink.put1(simm32 as u8), _ => unreachable!(), } } /// A small helper to generate a signed conversion instruction. fn emit_signed_cvt( sink: &mut MachBuffer<Inst>, flags: &settings::Flags, state: &mut EmitState, src: Reg, dst: Writable<Reg>, to_f64: bool, ) { // Handle an unsigned int, which is the "easy" case: a signed conversion will do the // right thing. let op = if to_f64 { SseOpcode::Cvtsi2sd } else { SseOpcode::Cvtsi2ss }; let inst = Inst::gpr_to_xmm(op, RegMem::reg(src), OperandSize::Size64, dst); inst.emit(sink, flags, state); } /// Emits a one way conditional jump if CC is set (true). fn one_way_jmp(sink: &mut MachBuffer<Inst>, cc: CC, label: MachLabel) { let cond_start = sink.cur_offset(); let cond_disp_off = cond_start + 2; sink.use_label_at_offset(cond_disp_off, label, LabelUse::JmpRel32); sink.put1(0x0F); sink.put1(0x80 + cc.get_enc()); sink.put4(0x0); } /// The top-level emit function. /// /// Important! Do not add improved (shortened) encoding cases to existing /// instructions without also adding tests for those improved encodings. That /// is a dangerous game that leads to hard-to-track-down errors in the emitted /// code. /// /// For all instructions, make sure to have test coverage for all of the /// following situations. Do this by creating the cross product resulting from /// applying the following rules to each operand: /// /// (1) for any insn that mentions a register: one test using a register from /// the group [rax, rcx, rdx, rbx, rsp, rbp, rsi, rdi] and a second one /// using a register from the group [r8, r9, r10, r11, r12, r13, r14, r15]. /// This helps detect incorrect REX prefix construction. /// /// (2) for any insn that mentions a byte register: one test for each of the /// four encoding groups [al, cl, dl, bl], [spl, bpl, sil, dil], /// [r8b .. r11b] and [r12b .. r15b]. This checks that /// apparently-redundant REX prefixes are retained when required. /// /// (3) for any insn that contains an immediate field, check the following /// cases: field is zero, field is in simm8 range (-128 .. 127), field is /// in simm32 range (-0x8000_0000 .. 0x7FFF_FFFF). This is because some /// instructions that require a 32-bit immediate have a short-form encoding /// when the imm is in simm8 range. /// /// Rules (1), (2) and (3) don't apply for registers within address expressions /// (`Addr`s). Those are already pretty well tested, and the registers in them /// don't have any effect on the containing instruction (apart from possibly /// require REX prefix bits). /// /// When choosing registers for a test, avoid using registers with the same /// offset within a given group. For example, don't use rax and r8, since they /// both have the lowest 3 bits as 000, and so the test won't detect errors /// where those 3-bit register sub-fields are confused by the emitter. Instead /// use (eg) rax (lo3 = 000) and r9 (lo3 = 001). Similarly, don't use (eg) cl /// and bpl since they have the same offset in their group; use instead (eg) cl /// and sil. /// /// For all instructions, also add a test that uses only low-half registers /// (rax .. rdi, xmm0 .. xmm7) etc, so as to check that any redundant REX /// prefixes are correctly omitted. This low-half restriction must apply to /// _all_ registers in the insn, even those in address expressions. /// /// Following these rules creates large numbers of test cases, but it's the /// only way to make the emitter reliable. /// /// Known possible improvements: /// /// * there's a shorter encoding for shl/shr/sar by a 1-bit immediate. (Do we /// care?) pub(crate) fn emit( inst: &Inst, sink: &mut MachBuffer<Inst>, flags: &settings::Flags, state: &mut EmitState, ) { match inst { Inst::AluRmiR { is_64, op, src, dst: reg_g, } => { let rex = if *is_64 { RexFlags::set_w() } else { RexFlags::clear_w() }; if *op == AluRmiROpcode::Mul { // We kinda freeloaded Mul into RMI_R_Op, but it doesn't fit the usual pattern, so // we have to special-case it. match src { RegMemImm::Reg { reg: reg_e } => { emit_std_reg_reg( sink, LegacyPrefixes::None, 0x0FAF, 2, reg_g.to_reg(), *reg_e, rex, ); } RegMemImm::Mem { addr } => { emit_std_reg_mem( sink, LegacyPrefixes::None, 0x0FAF, 2, reg_g.to_reg(), &addr.finalize(state), rex, ); } RegMemImm::Imm { simm32 } => { let use_imm8 = low8_will_sign_extend_to_32(*simm32); let opcode = if use_imm8 { 0x6B } else { 0x69 }; // Yes, really, reg_g twice. emit_std_reg_reg( sink, LegacyPrefixes::None, opcode, 1, reg_g.to_reg(), reg_g.to_reg(), rex, ); emit_simm(sink, if use_imm8 { 1 } else { 4 }, *simm32); } } } else { let (opcode_r, opcode_m, subopcode_i) = match op { AluRmiROpcode::Add => (0x01, 0x03, 0), AluRmiROpcode::Sub => (0x29, 0x2B, 5), AluRmiROpcode::And => (0x21, 0x23, 4), AluRmiROpcode::Or => (0x09, 0x0B, 1), AluRmiROpcode::Xor => (0x31, 0x33, 6), AluRmiROpcode::Mul => panic!("unreachable"), }; match src { RegMemImm::Reg { reg: reg_e } => { // GCC/llvm use the swapped operand encoding (viz., the R/RM vs RM/R // duality). Do this too, so as to be able to compare generated machine // code easily. emit_std_reg_reg( sink, LegacyPrefixes::None, opcode_r, 1, *reg_e, reg_g.to_reg(), rex, ); // NB: if this is ever extended to handle byte size ops, be sure to retain // redundant REX prefixes. } RegMemImm::Mem { addr } => { // Here we revert to the "normal" G-E ordering. emit_std_reg_mem( sink, LegacyPrefixes::None, opcode_m, 1, reg_g.to_reg(), &addr.finalize(state), rex, ); } RegMemImm::Imm { simm32 } => { let use_imm8 = low8_will_sign_extend_to_32(*simm32); let opcode = if use_imm8 { 0x83 } else { 0x81 }; // And also here we use the "normal" G-E ordering. let enc_g = int_reg_enc(reg_g.to_reg()); emit_std_enc_enc( sink, LegacyPrefixes::None, opcode, 1, subopcode_i, enc_g, rex, ); emit_simm(sink, if use_imm8 { 1 } else { 4 }, *simm32); } } } } Inst::UnaryRmR { size, op, src, dst } => { let (prefix, rex_flags) = match size { 2 => (LegacyPrefixes::_66, RexFlags::clear_w()), 4 => (LegacyPrefixes::None, RexFlags::clear_w()), 8 => (LegacyPrefixes::None, RexFlags::set_w()), _ => unreachable!(), }; let (opcode, num_opcodes) = match op { UnaryRmROpcode::Bsr => (0x0fbd, 2), UnaryRmROpcode::Bsf => (0x0fbc, 2), }; match src { RegMem::Reg { reg: src } => emit_std_reg_reg( sink, prefix, opcode, num_opcodes, dst.to_reg(), *src, rex_flags, ), RegMem::Mem { addr: src } => emit_std_reg_mem( sink, prefix, opcode, num_opcodes, dst.to_reg(), &src.finalize(state), rex_flags, ), } } Inst::Not { size, src } => { let (opcode, prefix, rex_flags) = match size { 1 => (0xF6, LegacyPrefixes::None, RexFlags::clear_w()), 2 => (0xF7, LegacyPrefixes::_66, RexFlags::clear_w()), 4 => (0xF7, LegacyPrefixes::None, RexFlags::clear_w()), 8 => (0xF7, LegacyPrefixes::None, RexFlags::set_w()), _ => unreachable!("{}", size), }; let subopcode = 2; let src = int_reg_enc(src.to_reg()); emit_std_enc_enc(sink, prefix, opcode, 1, subopcode, src, rex_flags) } Inst::Neg { size, src } => { let (opcode, prefix, rex_flags) = match size { 1 => (0xF6, LegacyPrefixes::None, RexFlags::clear_w()), 2 => (0xF7, LegacyPrefixes::_66, RexFlags::clear_w()), 4 => (0xF7, LegacyPrefixes::None, RexFlags::clear_w()), 8 => (0xF7, LegacyPrefixes::None, RexFlags::set_w()), _ => unreachable!("{}", size), }; let subopcode = 3; let src = int_reg_enc(src.to_reg()); emit_std_enc_enc(sink, prefix, opcode, 1, subopcode, src, rex_flags) } Inst::Div { size, signed, divisor, loc, } => { let (opcode, prefix, rex_flags) = match size { 1 => (0xF6, LegacyPrefixes::None, RexFlags::clear_w()), 2 => (0xF7, LegacyPrefixes::_66, RexFlags::clear_w()), 4 => (0xF7, LegacyPrefixes::None, RexFlags::clear_w()), 8 => (0xF7, LegacyPrefixes::None, RexFlags::set_w()), _ => unreachable!("{}", size), }; sink.add_trap(*loc, TrapCode::IntegerDivisionByZero); let subopcode = if *signed { 7 } else { 6 }; match divisor { RegMem::Reg { reg } => { let src = int_reg_enc(*reg); emit_std_enc_enc(sink, prefix, opcode, 1, subopcode, src, rex_flags) } RegMem::Mem { addr: src } => emit_std_enc_mem( sink, prefix, opcode, 1, subopcode, &src.finalize(state), rex_flags, ), } } Inst::MulHi { size, signed, rhs } => { let (prefix, rex_flags) = match size { 2 => (LegacyPrefixes::_66, RexFlags::clear_w()), 4 => (LegacyPrefixes::None, RexFlags::clear_w()), 8 => (LegacyPrefixes::None, RexFlags::set_w()), _ => unreachable!(), }; let subopcode = if *signed { 5 } else { 4 }; match rhs { RegMem::Reg { reg } => { let src = int_reg_enc(*reg); emit_std_enc_enc(sink, prefix, 0xF7, 1, subopcode, src, rex_flags) } RegMem::Mem { addr: src } => emit_std_enc_mem( sink, prefix, 0xF7, 1, subopcode, &src.finalize(state), rex_flags, ), } } Inst::SignExtendData { size } => match size { 1 => { sink.put1(0x66); sink.put1(0x98); } 2 => { sink.put1(0x66); sink.put1(0x99); } 4 => sink.put1(0x99), 8 => { sink.put1(0x48); sink.put1(0x99); } _ => unreachable!(), }, Inst::CheckedDivOrRemSeq { kind, size, divisor, loc, tmp, } => { // Generates the following code sequence: // // ;; check divide by zero: // cmp 0 %divisor // jnz $after_trap // ud2 // $after_trap: // // ;; for signed modulo/div: // cmp -1 %divisor // jnz $do_op // ;; for signed modulo, result is 0 // mov #0, %rdx // j $done // ;; for signed div, check for integer overflow against INT_MIN of the right size // cmp INT_MIN, %rax // jnz $do_op // ud2 // // $do_op: // ;; if signed // cdq ;; sign-extend from rax into rdx // ;; else // mov #0, %rdx // idiv %divisor // // $done: debug_assert!(flags.avoid_div_traps()); // Check if the divisor is zero, first. let inst = Inst::cmp_rmi_r(*size, RegMemImm::imm(0), divisor.to_reg()); inst.emit(sink, flags, state); let inst = Inst::trap_if(CC::Z, TrapCode::IntegerDivisionByZero, *loc); inst.emit(sink, flags, state); let (do_op, done_label) = if kind.is_signed() { // Now check if the divisor is -1. let inst = Inst::cmp_rmi_r(*size, RegMemImm::imm(0xffffffff), divisor.to_reg()); inst.emit(sink, flags, state); let do_op = sink.get_label(); // If not equal, jump to do-op. one_way_jmp(sink, CC::NZ, do_op); // Here, divisor == -1. if !kind.is_div() { // x % -1 = 0; put the result into the destination, $rdx. let done_label = sink.get_label(); let inst = Inst::imm( OperandSize::from_bytes(*size as u32), 0, Writable::from_reg(regs::rdx()), ); inst.emit(sink, flags, state); let inst = Inst::jmp_known(BranchTarget::Label(done_label)); inst.emit(sink, flags, state); (Some(do_op), Some(done_label)) } else { // Check for integer overflow. if *size == 8 { let tmp = tmp.expect("temporary for i64 sdiv"); let inst = Inst::imm(OperandSize::Size64, 0x8000000000000000, tmp); inst.emit(sink, flags, state); let inst = Inst::cmp_rmi_r(8, RegMemImm::reg(tmp.to_reg()), regs::rax()); inst.emit(sink, flags, state); } else { let inst = Inst::cmp_rmi_r(*size, RegMemImm::imm(0x80000000), regs::rax()); inst.emit(sink, flags, state); } // If not equal, jump over the trap. let inst = Inst::trap_if(CC::Z, TrapCode::IntegerOverflow, *loc); inst.emit(sink, flags, state); (Some(do_op), None) } } else { (None, None) }; if let Some(do_op) = do_op { sink.bind_label(do_op); } assert!( *size > 1, "CheckedDivOrRemSeq for i8 is not yet implemented" ); // Fill in the high parts: if kind.is_signed() { // sign-extend the sign-bit of rax into rdx, for signed opcodes. let inst = Inst::sign_extend_data(*size); inst.emit(sink, flags, state); } else { // zero for unsigned opcodes. let inst = Inst::imm(OperandSize::Size64, 0, Writable::from_reg(regs::rdx())); inst.emit(sink, flags, state); } let inst = Inst::div(*size, kind.is_signed(), RegMem::reg(divisor.to_reg()), *loc); inst.emit(sink, flags, state); // Lowering takes care of moving the result back into the right register, see comment // there. if let Some(done) = done_label { sink.bind_label(done); } } Inst::Imm { dst_is_64, simm64, dst, } => { let enc_dst = int_reg_enc(dst.to_reg()); if *dst_is_64 { if low32_will_sign_extend_to_64(*simm64) { // Sign-extended move imm32. emit_std_enc_enc( sink, LegacyPrefixes::None, 0xC7, 1, /* subopcode */ 0, enc_dst, RexFlags::set_w(), ); sink.put4(*simm64 as u32); } else { sink.put1(0x48 | ((enc_dst >> 3) & 1)); sink.put1(0xB8 | (enc_dst & 7)); sink.put8(*simm64); } } else { if ((enc_dst >> 3) & 1) == 1 { sink.put1(0x41); } sink.put1(0xB8 | (enc_dst & 7)); sink.put4(*simm64 as u32); } } Inst::MovRR { is_64, src, dst } => { let rex = if *is_64 { RexFlags::set_w() } else { RexFlags::clear_w() }; emit_std_reg_reg(sink, LegacyPrefixes::None, 0x89, 1, *src, dst.to_reg(), rex); } Inst::MovzxRmR { ext_mode, src, dst, srcloc, } => { let (opcodes, num_opcodes, mut rex_flags) = match ext_mode { ExtMode::BL => { // MOVZBL is (REX.W==0) 0F B6 /r (0x0FB6, 2, RexFlags::clear_w()) } ExtMode::BQ => { // MOVZBQ is (REX.W==1) 0F B6 /r // I'm not sure why the Intel manual offers different // encodings for MOVZBQ than for MOVZBL. AIUI they should // achieve the same, since MOVZBL is just going to zero out // the upper half of the destination anyway. (0x0FB6, 2, RexFlags::set_w()) } ExtMode::WL => { // MOVZWL is (REX.W==0) 0F B7 /r (0x0FB7, 2, RexFlags::clear_w()) } ExtMode::WQ => { // MOVZWQ is (REX.W==1) 0F B7 /r (0x0FB7, 2, RexFlags::set_w()) } ExtMode::LQ => { // This is just a standard 32 bit load, and we rely on the // default zero-extension rule to perform the extension. // Note that in reg/reg mode, gcc seems to use the swapped form R/RM, which we // don't do here, since it's the same encoding size. // MOV r/m32, r32 is (REX.W==0) 8B /r (0x8B, 1, RexFlags::clear_w()) } }; match src { RegMem::Reg { reg: src } => { match ext_mode { ExtMode::BL | ExtMode::BQ => { // A redundant REX prefix must be emitted for certain register inputs. let enc_src = int_reg_enc(*src); if enc_src >= 4 && enc_src <= 7 { rex_flags.always_emit(); }; } _ => {} } emit_std_reg_reg( sink, LegacyPrefixes::None, opcodes, num_opcodes, dst.to_reg(), *src, rex_flags, ) } RegMem::Mem { addr: src } => { let src = &src.finalize(state); if let Some(srcloc) = *srcloc { // Register the offset at which the actual load instruction starts. sink.add_trap(srcloc, TrapCode::HeapOutOfBounds); } emit_std_reg_mem( sink, LegacyPrefixes::None, opcodes, num_opcodes, dst.to_reg(), src, rex_flags, ) } } } Inst::Mov64MR { src, dst, srcloc } => { let src = &src.finalize(state); if let Some(srcloc) = *srcloc { // Register the offset at which the actual load instruction starts. sink.add_trap(srcloc, TrapCode::HeapOutOfBounds); } emit_std_reg_mem( sink, LegacyPrefixes::None, 0x8B, 1, dst.to_reg(), src, RexFlags::set_w(), ) } Inst::LoadEffectiveAddress { addr, dst } => emit_std_reg_mem( sink, LegacyPrefixes::None, 0x8D, 1, dst.to_reg(), &addr.finalize(state), RexFlags::set_w(), ), Inst::MovsxRmR { ext_mode, src, dst, srcloc, } => { let (opcodes, num_opcodes, mut rex_flags) = match ext_mode { ExtMode::BL => { // MOVSBL is (REX.W==0) 0F BE /r (0x0FBE, 2, RexFlags::clear_w()) } ExtMode::BQ => { // MOVSBQ is (REX.W==1) 0F BE /r (0x0FBE, 2, RexFlags::set_w()) } ExtMode::WL => { // MOVSWL is (REX.W==0) 0F BF /r (0x0FBF, 2, RexFlags::clear_w()) } ExtMode::WQ => { // MOVSWQ is (REX.W==1) 0F BF /r (0x0FBF, 2, RexFlags::set_w()) } ExtMode::LQ => { // MOVSLQ is (REX.W==1) 63 /r (0x63, 1, RexFlags::set_w()) } }; match src { RegMem::Reg { reg: src } => { match ext_mode { ExtMode::BL | ExtMode::BQ => { // A redundant REX prefix must be emitted for certain register inputs. let enc_src = int_reg_enc(*src); if enc_src >= 4 && enc_src <= 7 { rex_flags.always_emit(); }; } _ => {} } emit_std_reg_reg( sink, LegacyPrefixes::None, opcodes, num_opcodes, dst.to_reg(), *src, rex_flags, ) } RegMem::Mem { addr: src } => { let src = &src.finalize(state); if let Some(srcloc) = *srcloc { // Register the offset at which the actual load instruction starts. sink.add_trap(srcloc, TrapCode::HeapOutOfBounds); } emit_std_reg_mem( sink, LegacyPrefixes::None, opcodes, num_opcodes, dst.to_reg(), src, rex_flags, ) } } } Inst::MovRM { size, src, dst, srcloc, } => { let dst = &dst.finalize(state); if let Some(srcloc) = *srcloc { // Register the offset at which the actual load instruction starts. sink.add_trap(srcloc, TrapCode::HeapOutOfBounds); } match size { 1 => { // This is one of the few places where the presence of a // redundant REX prefix changes the meaning of the // instruction. let mut rex = RexFlags::clear_w(); let enc_src = int_reg_enc(*src); if enc_src >= 4 && enc_src <= 7 { rex.always_emit(); }; // MOV r8, r/m8 is (REX.W==0) 88 /r emit_std_reg_mem(sink, LegacyPrefixes::None, 0x88, 1, *src, dst, rex) } 2 => { // MOV r16, r/m16 is 66 (REX.W==0) 89 /r emit_std_reg_mem( sink, LegacyPrefixes::_66, 0x89, 1, *src, dst, RexFlags::clear_w(), ) } 4 => { // MOV r32, r/m32 is (REX.W==0) 89 /r emit_std_reg_mem( sink, LegacyPrefixes::None, 0x89, 1, *src, dst, RexFlags::clear_w(), ) } 8 => { // MOV r64, r/m64 is (REX.W==1) 89 /r emit_std_reg_mem( sink, LegacyPrefixes::None, 0x89, 1, *src, dst, RexFlags::set_w(), ) } _ => panic!("x64::Inst::Mov_R_M::emit: unreachable"), } } Inst::ShiftR { size, kind, num_bits, dst, } => { let enc_dst = int_reg_enc(dst.to_reg()); let subopcode = match kind { ShiftKind::RotateLeft => 0, ShiftKind::RotateRight => 1, ShiftKind::ShiftLeft => 4, ShiftKind::ShiftRightLogical => 5, ShiftKind::ShiftRightArithmetic => 7, }; match num_bits { None => { let (opcode, prefix, rex_flags) = match size { 1 => (0xD2, LegacyPrefixes::None, RexFlags::clear_w()), 2 => (0xD3, LegacyPrefixes::_66, RexFlags::clear_w()), 4 => (0xD3, LegacyPrefixes::None, RexFlags::clear_w()), 8 => (0xD3, LegacyPrefixes::None, RexFlags::set_w()), _ => unreachable!("{}", size), }; // SHL/SHR/SAR %cl, reg8 is (REX.W==0) D2 /subopcode // SHL/SHR/SAR %cl, reg16 is 66 (REX.W==0) D3 /subopcode // SHL/SHR/SAR %cl, reg32 is (REX.W==0) D3 /subopcode // SHL/SHR/SAR %cl, reg64 is (REX.W==1) D3 /subopcode emit_std_enc_enc(sink, prefix, opcode, 1, subopcode, enc_dst, rex_flags); } Some(num_bits) => { let (opcode, prefix, rex_flags) = match size { 1 => (0xC0, LegacyPrefixes::None, RexFlags::clear_w()), 2 => (0xC1, LegacyPrefixes::_66, RexFlags::clear_w()), 4 => (0xC1, LegacyPrefixes::None, RexFlags::clear_w()), 8 => (0xC1, LegacyPrefixes::None, RexFlags::set_w()), _ => unreachable!("{}", size), }; // SHL/SHR/SAR $ib, reg8 is (REX.W==0) C0 /subopcode // SHL/SHR/SAR $ib, reg16 is 66 (REX.W==0) C1 /subopcode // SHL/SHR/SAR $ib, reg32 is (REX.W==0) C1 /subopcode ib // SHL/SHR/SAR $ib, reg64 is (REX.W==1) C1 /subopcode ib // When the shift amount is 1, there's an even shorter encoding, but we don't // bother with that nicety here. emit_std_enc_enc(sink, prefix, opcode, 1, subopcode, enc_dst, rex_flags); sink.put1(*num_bits); } } } Inst::XmmRmiReg { opcode, src, dst } => { let rex = RexFlags::clear_w(); let prefix = LegacyPrefixes::_66; if let RegMemImm::Imm { simm32 } = src { let (opcode_bytes, reg_digit) = match opcode { SseOpcode::Psllw => (0x0F71, 6), SseOpcode::Pslld => (0x0F72, 6), SseOpcode::Psllq => (0x0F73, 6), SseOpcode::Psraw => (0x0F71, 4), SseOpcode::Psrad => (0x0F72, 4), SseOpcode::Psrlw => (0x0F71, 2), SseOpcode::Psrld => (0x0F72, 2), SseOpcode::Psrlq => (0x0F73, 2), _ => panic!("invalid opcode: {}", opcode), }; let dst_enc = reg_enc(dst.to_reg()); emit_std_enc_enc(sink, prefix, opcode_bytes, 2, reg_digit, dst_enc, rex); let imm = (*simm32) .try_into() .expect("the immediate must be convertible to a u8"); sink.put1(imm); } else { let opcode_bytes = match opcode { SseOpcode::Psllw => 0x0FF1, SseOpcode::Pslld => 0x0FF2, SseOpcode::Psllq => 0x0FF3, SseOpcode::Psraw => 0x0FE1, SseOpcode::Psrad => 0x0FE2, SseOpcode::Psrlw => 0x0FD1, SseOpcode::Psrld => 0x0FD2, SseOpcode::Psrlq => 0x0FD3, _ => panic!("invalid opcode: {}", opcode), }; match src { RegMemImm::Reg { reg } => { emit_std_reg_reg(sink, prefix, opcode_bytes, 2, dst.to_reg(), *reg, rex); } RegMemImm::Mem { addr } => { let addr = &addr.finalize(state); emit_std_reg_mem(sink, prefix, opcode_bytes, 2, dst.to_reg(), addr, rex); } RegMemImm::Imm { .. } => unreachable!(), } }; } Inst::CmpRmiR { size, src: src_e, dst: reg_g, } => { let mut prefix = LegacyPrefixes::None; if *size == 2 { prefix = LegacyPrefixes::_66; } let mut rex = match size { 8 => RexFlags::set_w(), 4 | 2 => RexFlags::clear_w(), 1 => { let mut rex = RexFlags::clear_w(); // Here, a redundant REX prefix changes the meaning of the instruction. let enc_g = int_reg_enc(*reg_g); if enc_g >= 4 && enc_g <= 7 { rex.always_emit(); } rex } _ => panic!("x64::Inst::Cmp_RMI_R::emit: unreachable"), }; match src_e { RegMemImm::Reg { reg: reg_e } => { if *size == 1 { // Check whether the E register forces the use of a redundant REX. let enc_e = int_reg_enc(*reg_e); if enc_e >= 4 && enc_e <= 7 { rex.always_emit(); } } // Use the swapped operands encoding, to stay consistent with the output of // gcc/llvm. let opcode = if *size == 1 { 0x38 } else { 0x39 }; emit_std_reg_reg(sink, prefix, opcode, 1, *reg_e, *reg_g, rex); } RegMemImm::Mem { addr } => { let addr = &addr.finalize(state); // Whereas here we revert to the "normal" G-E ordering. let opcode = if *size == 1 { 0x3A } else { 0x3B }; emit_std_reg_mem(sink, prefix, opcode, 1, *reg_g, addr, rex); } RegMemImm::Imm { simm32 } => { // FIXME JRS 2020Feb11: there are shorter encodings for // cmp $imm, rax/eax/ax/al. let use_imm8 = low8_will_sign_extend_to_32(*simm32); // And also here we use the "normal" G-E ordering. let opcode = if *size == 1 { 0x80 } else if use_imm8 { 0x83 } else { 0x81 }; let enc_g = int_reg_enc(*reg_g); emit_std_enc_enc(sink, prefix, opcode, 1, 7 /*subopcode*/, enc_g, rex); emit_simm(sink, if use_imm8 { 1 } else { *size }, *simm32); } } } Inst::Setcc { cc, dst } => { let opcode = 0x0f90 + cc.get_enc() as u32; let mut rex_flags = RexFlags::clear_w(); rex_flags.always_emit(); emit_std_enc_enc( sink, LegacyPrefixes::None, opcode, 2, 0, reg_enc(dst.to_reg()), rex_flags, ); } Inst::Cmove { size, cc, src, dst: reg_g, } => { let (prefix, rex_flags) = match size { 2 => (LegacyPrefixes::_66, RexFlags::clear_w()), 4 => (LegacyPrefixes::None, RexFlags::clear_w()), 8 => (LegacyPrefixes::None, RexFlags::set_w()), _ => unreachable!("invalid size spec for cmove"), }; let opcode = 0x0F40 + cc.get_enc() as u32; match src { RegMem::Reg { reg: reg_e } => { emit_std_reg_reg(sink, prefix, opcode, 2, reg_g.to_reg(), *reg_e, rex_flags); } RegMem::Mem { addr } => { let addr = &addr.finalize(state); emit_std_reg_mem(sink, prefix, opcode, 2, reg_g.to_reg(), addr, rex_flags); } } } Inst::XmmCmove { is_64, cc, src, dst, } => { // Lowering of the Select IR opcode when the input is an fcmp relies on the fact that // this doesn't clobber flags. Make sure to not do so here. let next = sink.get_label(); // Jump if cc is *not* set. one_way_jmp(sink, cc.invert(), next); let op = if *is_64 { SseOpcode::Movsd } else { SseOpcode::Movss }; let inst = Inst::xmm_unary_rm_r(op, src.clone(), *dst); inst.emit(sink, flags, state); sink.bind_label(next); } Inst::Push64 { src } => { match src { RegMemImm::Reg { reg } => { let enc_reg = int_reg_enc(*reg); let rex = 0x40 | ((enc_reg >> 3) & 1); if rex != 0x40 { sink.put1(rex); } sink.put1(0x50 | (enc_reg & 7)); } RegMemImm::Mem { addr } => { let addr = &addr.finalize(state); emit_std_enc_mem( sink, LegacyPrefixes::None, 0xFF, 1, 6, /*subopcode*/ addr, RexFlags::clear_w(), ); } RegMemImm::Imm { simm32 } => { if low8_will_sign_extend_to_64(*simm32) { sink.put1(0x6A); sink.put1(*simm32 as u8); } else { sink.put1(0x68); sink.put4(*simm32); } } } } Inst::Pop64 { dst } => { let enc_dst = int_reg_enc(dst.to_reg()); if enc_dst >= 8 { // 0x41 == REX.{W=0, B=1}. It seems that REX.W is irrelevant here. sink.put1(0x41); } sink.put1(0x58 + (enc_dst & 7)); } Inst::CallKnown { dest, loc, opcode, .. } => { if let Some(s) = state.take_stack_map() { sink.add_stack_map(StackMapExtent::UpcomingBytes(5), s); } sink.put1(0xE8); // The addend adjusts for the difference between the end of the instruction and the // beginning of the immediate field. sink.add_reloc(*loc, Reloc::X86CallPCRel4, &dest, -4); sink.put4(0); if opcode.is_call() { sink.add_call_site(*loc, *opcode); } } Inst::CallUnknown { dest, opcode, loc, .. } => { let start_offset = sink.cur_offset(); match dest { RegMem::Reg { reg } => { let reg_enc = int_reg_enc(*reg); emit_std_enc_enc( sink, LegacyPrefixes::None, 0xFF, 1, 2, /*subopcode*/ reg_enc, RexFlags::clear_w(), ); } RegMem::Mem { addr } => { let addr = &addr.finalize(state); emit_std_enc_mem( sink, LegacyPrefixes::None, 0xFF, 1, 2, /*subopcode*/ addr, RexFlags::clear_w(), ); } } if let Some(s) = state.take_stack_map() { sink.add_stack_map(StackMapExtent::StartedAtOffset(start_offset), s); } if opcode.is_call() { sink.add_call_site(*loc, *opcode); } } Inst::Ret {} => sink.put1(0xC3), Inst::JmpKnown { dst } => { let br_start = sink.cur_offset(); let br_disp_off = br_start + 1; let br_end = br_start + 5; if let Some(l) = dst.as_label() { sink.use_label_at_offset(br_disp_off, l, LabelUse::JmpRel32); sink.add_uncond_branch(br_start, br_end, l); } let disp = dst.as_offset32_or_zero(); let disp = disp as u32; sink.put1(0xE9); sink.put4(disp); } Inst::JmpIf { cc, taken } => { let cond_start = sink.cur_offset(); let cond_disp_off = cond_start + 2; if let Some(l) = taken.as_label() { sink.use_label_at_offset(cond_disp_off, l, LabelUse::JmpRel32); // Since this is not a terminator, don't enroll in the branch inversion mechanism. } let taken_disp = taken.as_offset32_or_zero(); let taken_disp = taken_disp as u32; sink.put1(0x0F); sink.put1(0x80 + cc.get_enc()); sink.put4(taken_disp); } Inst::JmpCond { cc, taken, not_taken, } => { // If taken. let cond_start = sink.cur_offset(); let cond_disp_off = cond_start + 2; let cond_end = cond_start + 6; if let Some(l) = taken.as_label() { sink.use_label_at_offset(cond_disp_off, l, LabelUse::JmpRel32); let inverted: [u8; 6] = [0x0F, 0x80 + (cc.invert().get_enc()), 0x00, 0x00, 0x00, 0x00]; sink.add_cond_branch(cond_start, cond_end, l, &inverted[..]); } let taken_disp = taken.as_offset32_or_zero(); let taken_disp = taken_disp as u32; sink.put1(0x0F); sink.put1(0x80 + cc.get_enc()); sink.put4(taken_disp); // If not taken. let uncond_start = sink.cur_offset(); let uncond_disp_off = uncond_start + 1; let uncond_end = uncond_start + 5; if let Some(l) = not_taken.as_label() { sink.use_label_at_offset(uncond_disp_off, l, LabelUse::JmpRel32); sink.add_uncond_branch(uncond_start, uncond_end, l); } let nt_disp = not_taken.as_offset32_or_zero(); let nt_disp = nt_disp as u32; sink.put1(0xE9); sink.put4(nt_disp); } Inst::JmpUnknown { target } => { match target { RegMem::Reg { reg } => { let reg_enc = int_reg_enc(*reg); emit_std_enc_enc( sink, LegacyPrefixes::None, 0xFF, 1, 4, /*subopcode*/ reg_enc, RexFlags::clear_w(), ); } RegMem::Mem { addr } => { let addr = &addr.finalize(state); emit_std_enc_mem( sink, LegacyPrefixes::None, 0xFF, 1, 4, /*subopcode*/ addr, RexFlags::clear_w(), ); } } } Inst::JmpTableSeq { idx, tmp1, tmp2, ref targets, default_target, .. } => { // This sequence is *one* instruction in the vcode, and is expanded only here at // emission time, because we cannot allow the regalloc to insert spills/reloads in // the middle; we depend on hardcoded PC-rel addressing below. // // We don't have to worry about emitting islands, because the only label-use type has a // maximum range of 2 GB. If we later consider using shorter-range label references, // this will need to be revisited. // Save index in a tmp (the live range of ridx only goes to start of this // sequence; rtmp1 or rtmp2 may overwrite it). // We generate the following sequence: // ;; generated by lowering: cmp #jmp_table_size, %idx // jnb $default_target // movl %idx, %tmp2 // lea start_of_jump_table_offset(%rip), %tmp1 // movslq [%tmp1, %tmp2, 4], %tmp2 ;; shift of 2, viz. multiply index by 4 // addq %tmp2, %tmp1 // j *%tmp1 // $start_of_jump_table: // -- jump table entries let default_label = match default_target { BranchTarget::Label(label) => label, _ => unreachable!(), }; one_way_jmp(sink, CC::NB, *default_label); // idx unsigned >= jmp table size // Copy the index (and make sure to clear the high 32-bits lane of tmp2). let inst = Inst::movzx_rm_r(ExtMode::LQ, RegMem::reg(*idx), *tmp2, None); inst.emit(sink, flags, state); // Load base address of jump table. let start_of_jumptable = sink.get_label(); let inst = Inst::lea( Amode::rip_relative(BranchTarget::Label(start_of_jumptable)), *tmp1, ); inst.emit(sink, flags, state); // Load value out of the jump table. It's a relative offset to the target block, so it // might be negative; use a sign-extension. let inst = Inst::movsx_rm_r( ExtMode::LQ, RegMem::mem(Amode::imm_reg_reg_shift(0, tmp1.to_reg(), tmp2.to_reg(), 2)), *tmp2, None, ); inst.emit(sink, flags, state); // Add base of jump table to jump-table-sourced block offset. let inst = Inst::alu_rmi_r( true, /* is_64 */ AluRmiROpcode::Add, RegMemImm::reg(tmp2.to_reg()), *tmp1, ); inst.emit(sink, flags, state); // Branch to computed address. let inst = Inst::jmp_unknown(RegMem::reg(tmp1.to_reg())); inst.emit(sink, flags, state); // Emit jump table (table of 32-bit offsets). sink.bind_label(start_of_jumptable); let jt_off = sink.cur_offset(); for &target in targets.iter() { let word_off = sink.cur_offset(); // off_into_table is an addend here embedded in the label to be later patched at // the end of codegen. The offset is initially relative to this jump table entry; // with the extra addend, it'll be relative to the jump table's start, after // patching. let off_into_table = word_off - jt_off; sink.use_label_at_offset(word_off, target.as_label().unwrap(), LabelUse::PCRel32); sink.put4(off_into_table); } } Inst::TrapIf { cc, trap_code, srcloc, } => { let else_label = sink.get_label(); // Jump over if the invert of CC is set (i.e. CC is not set). one_way_jmp(sink, cc.invert(), else_label); // Trap! let inst = Inst::trap(*srcloc, *trap_code); inst.emit(sink, flags, state); sink.bind_label(else_label); } Inst::XmmUnaryRmR { op, src: src_e, dst: reg_g, srcloc, } => { let rex = RexFlags::clear_w(); let (prefix, opcode, num_opcodes) = match op { SseOpcode::Cvtss2sd => (LegacyPrefixes::_F3, 0x0F5A, 2), SseOpcode::Cvtsd2ss => (LegacyPrefixes::_F2, 0x0F5A, 2), SseOpcode::Movaps => (LegacyPrefixes::None, 0x0F28, 2), SseOpcode::Movapd => (LegacyPrefixes::_66, 0x0F28, 2), SseOpcode::Movdqa => (LegacyPrefixes::_66, 0x0F6F, 2), SseOpcode::Movdqu => (LegacyPrefixes::_F3, 0x0F6F, 2), SseOpcode::Movsd => (LegacyPrefixes::_F2, 0x0F10, 2), SseOpcode::Movss => (LegacyPrefixes::_F3, 0x0F10, 2), SseOpcode::Movups => (LegacyPrefixes::None, 0x0F10, 2), SseOpcode::Movupd => (LegacyPrefixes::_66, 0x0F10, 2), SseOpcode::Pabsb => (LegacyPrefixes::_66, 0x0F381C, 3), SseOpcode::Pabsw => (LegacyPrefixes::_66, 0x0F381D, 3), SseOpcode::Pabsd => (LegacyPrefixes::_66, 0x0F381E, 3), SseOpcode::Sqrtps => (LegacyPrefixes::None, 0x0F51, 2), SseOpcode::Sqrtpd => (LegacyPrefixes::_66, 0x0F51, 2), SseOpcode::Sqrtss => (LegacyPrefixes::_F3, 0x0F51, 2), SseOpcode::Sqrtsd => (LegacyPrefixes::_F2, 0x0F51, 2), _ => unimplemented!("Opcode {:?} not implemented", op), }; match src_e { RegMem::Reg { reg: reg_e } => { emit_std_reg_reg( sink, prefix, opcode, num_opcodes, reg_g.to_reg(), *reg_e, rex, ); } RegMem::Mem { addr } => { let addr = &addr.finalize(state); if let Some(srcloc) = *srcloc { // Register the offset at which the actual load instruction starts. sink.add_trap(srcloc, TrapCode::HeapOutOfBounds); } emit_std_reg_mem(sink, prefix, opcode, num_opcodes, reg_g.to_reg(), addr, rex); } }; } Inst::XmmRmR { op, src: src_e, dst: reg_g, } => { let rex = RexFlags::clear_w(); let (prefix, opcode, length) = match op { SseOpcode::Addps => (LegacyPrefixes::None, 0x0F58, 2), SseOpcode::Addpd => (LegacyPrefixes::_66, 0x0F58, 2), SseOpcode::Addss => (LegacyPrefixes::_F3, 0x0F58, 2), SseOpcode::Addsd => (LegacyPrefixes::_F2, 0x0F58, 2), SseOpcode::Andpd => (LegacyPrefixes::_66, 0x0F54, 2), SseOpcode::Andps => (LegacyPrefixes::None, 0x0F54, 2), SseOpcode::Andnps => (LegacyPrefixes::None, 0x0F55, 2), SseOpcode::Andnpd => (LegacyPrefixes::_66, 0x0F55, 2), SseOpcode::Divps => (LegacyPrefixes::None, 0x0F5E, 2), SseOpcode::Divpd => (LegacyPrefixes::_66, 0x0F5E, 2), SseOpcode::Divss => (LegacyPrefixes::_F3, 0x0F5E, 2), SseOpcode::Divsd => (LegacyPrefixes::_F2, 0x0F5E, 2), SseOpcode::Maxps => (LegacyPrefixes::None, 0x0F5F, 2), SseOpcode::Maxpd => (LegacyPrefixes::_66, 0x0F5F, 2), SseOpcode::Maxss => (LegacyPrefixes::_F3, 0x0F5F, 2), SseOpcode::Maxsd => (LegacyPrefixes::_F2, 0x0F5F, 2), SseOpcode::Minps => (LegacyPrefixes::None, 0x0F5D, 2), SseOpcode::Minpd => (LegacyPrefixes::_66, 0x0F5D, 2), SseOpcode::Minss => (LegacyPrefixes::_F3, 0x0F5D, 2), SseOpcode::Minsd => (LegacyPrefixes::_F2, 0x0F5D, 2), SseOpcode::Movlhps => (LegacyPrefixes::None, 0x0F16, 2), SseOpcode::Movsd => (LegacyPrefixes::_F2, 0x0F10, 2), SseOpcode::Mulps => (LegacyPrefixes::None, 0x0F59, 2), SseOpcode::Mulpd => (LegacyPrefixes::_66, 0x0F59, 2), SseOpcode::Mulss => (LegacyPrefixes::_F3, 0x0F59, 2), SseOpcode::Mulsd => (LegacyPrefixes::_F2, 0x0F59, 2), SseOpcode::Orpd => (LegacyPrefixes::_66, 0x0F56, 2), SseOpcode::Orps => (LegacyPrefixes::None, 0x0F56, 2), SseOpcode::Paddb => (LegacyPrefixes::_66, 0x0FFC, 2), SseOpcode::Paddd => (LegacyPrefixes::_66, 0x0FFE, 2), SseOpcode::Paddq => (LegacyPrefixes::_66, 0x0FD4, 2), SseOpcode::Paddw => (LegacyPrefixes::_66, 0x0FFD, 2), SseOpcode::Paddsb => (LegacyPrefixes::_66, 0x0FEC, 2), SseOpcode::Paddsw => (LegacyPrefixes::_66, 0x0FED, 2), SseOpcode::Paddusb => (LegacyPrefixes::_66, 0x0FDC, 2), SseOpcode::Paddusw => (LegacyPrefixes::_66, 0x0FDD, 2), SseOpcode::Pavgb => (LegacyPrefixes::_66, 0x0FE0, 2), SseOpcode::Pavgw => (LegacyPrefixes::_66, 0x0FE3, 2), SseOpcode::Pcmpeqb => (LegacyPrefixes::_66, 0x0F74, 2), SseOpcode::Pcmpeqw => (LegacyPrefixes::_66, 0x0F75, 2), SseOpcode::Pcmpeqd => (LegacyPrefixes::_66, 0x0F76, 2), SseOpcode::Pcmpeqq => (LegacyPrefixes::_66, 0x0F3829, 3), SseOpcode::Pcmpgtb => (LegacyPrefixes::_66, 0x0F64, 2), SseOpcode::Pcmpgtw => (LegacyPrefixes::_66, 0x0F65, 2), SseOpcode::Pcmpgtd => (LegacyPrefixes::_66, 0x0F66, 2), SseOpcode::Pcmpgtq => (LegacyPrefixes::_66, 0x0F3837, 3), SseOpcode::Pmaxsb => (LegacyPrefixes::_66, 0x0F383C, 3), SseOpcode::Pmaxsw => (LegacyPrefixes::_66, 0x0FEE, 2), SseOpcode::Pmaxsd => (LegacyPrefixes::_66, 0x0F383D, 3), SseOpcode::Pmaxub => (LegacyPrefixes::_66, 0x0FDE, 2), SseOpcode::Pmaxuw => (LegacyPrefixes::_66, 0x0F383E, 3), SseOpcode::Pmaxud => (LegacyPrefixes::_66, 0x0F383F, 3), SseOpcode::Pminsb => (LegacyPrefixes::_66, 0x0F3838, 3), SseOpcode::Pminsw => (LegacyPrefixes::_66, 0x0FEA, 2), SseOpcode::Pminsd => (LegacyPrefixes::_66, 0x0F3839, 3), SseOpcode::Pminub => (LegacyPrefixes::_66, 0x0FDA, 2), SseOpcode::Pminuw => (LegacyPrefixes::_66, 0x0F383A, 3), SseOpcode::Pminud => (LegacyPrefixes::_66, 0x0F383B, 3), SseOpcode::Pmulld => (LegacyPrefixes::_66, 0x0F3840, 3), SseOpcode::Pmullw => (LegacyPrefixes::_66, 0x0FD5, 2), SseOpcode::Pmuludq => (LegacyPrefixes::_66, 0x0FF4, 2), SseOpcode::Por => (LegacyPrefixes::_66, 0x0FEB, 2), SseOpcode::Pshufb => (LegacyPrefixes::_66, 0x0F3800, 3), SseOpcode::Psubb => (LegacyPrefixes::_66, 0x0FF8, 2), SseOpcode::Psubd => (LegacyPrefixes::_66, 0x0FFA, 2), SseOpcode::Psubq => (LegacyPrefixes::_66, 0x0FFB, 2), SseOpcode::Psubw => (LegacyPrefixes::_66, 0x0FF9, 2), SseOpcode::Pxor => (LegacyPrefixes::_66, 0x0FEF, 2), SseOpcode::Subps => (LegacyPrefixes::None, 0x0F5C, 2), SseOpcode::Subpd => (LegacyPrefixes::_66, 0x0F5C, 2), SseOpcode::Subss => (LegacyPrefixes::_F3, 0x0F5C, 2), SseOpcode::Subsd => (LegacyPrefixes::_F2, 0x0F5C, 2), SseOpcode::Xorps => (LegacyPrefixes::None, 0x0F57, 2), SseOpcode::Xorpd => (LegacyPrefixes::_66, 0x0F57, 2), _ => unimplemented!("Opcode {:?} not implemented", op), }; match src_e { RegMem::Reg { reg: reg_e } => { emit_std_reg_reg(sink, prefix, opcode, length, reg_g.to_reg(), *reg_e, rex); } RegMem::Mem { addr } => { let addr = &addr.finalize(state); emit_std_reg_mem(sink, prefix, opcode, length, reg_g.to_reg(), addr, rex); } } } Inst::XmmMinMaxSeq { size, is_min, lhs, rhs_dst, } => { // Generates the following sequence: // cmpss/cmpsd %lhs, %rhs_dst // jnz do_min_max // jp propagate_nan // // ;; ordered and equal: propagate the sign bit (for -0 vs 0): // {and,or}{ss,sd} %lhs, %rhs_dst // j done // // ;; to get the desired NaN behavior (signalling NaN transformed into a quiet NaN, the // ;; NaN value is returned), we add both inputs. // propagate_nan: // add{ss,sd} %lhs, %rhs_dst // j done // // do_min_max: // {min,max}{ss,sd} %lhs, %rhs_dst // // done: let done = sink.get_label(); let propagate_nan = sink.get_label(); let do_min_max = sink.get_label(); let (add_op, cmp_op, and_op, or_op, min_max_op) = match size { OperandSize::Size32 => ( SseOpcode::Addss, SseOpcode::Ucomiss, SseOpcode::Andps, SseOpcode::Orps, if *is_min { SseOpcode::Minss } else { SseOpcode::Maxss }, ), OperandSize::Size64 => ( SseOpcode::Addsd, SseOpcode::Ucomisd, SseOpcode::Andpd, SseOpcode::Orpd, if *is_min { SseOpcode::Minsd } else { SseOpcode::Maxsd }, ), }; let inst = Inst::xmm_cmp_rm_r(cmp_op, RegMem::reg(*lhs), rhs_dst.to_reg()); inst.emit(sink, flags, state); one_way_jmp(sink, CC::NZ, do_min_max); one_way_jmp(sink, CC::P, propagate_nan); // Ordered and equal. The operands are bit-identical unless they are zero // and negative zero. These instructions merge the sign bits in that // case, and are no-ops otherwise. let op = if *is_min { or_op } else { and_op }; let inst = Inst::xmm_rm_r(op, RegMem::reg(*lhs), *rhs_dst); inst.emit(sink, flags, state); let inst = Inst::jmp_known(BranchTarget::Label(done)); inst.emit(sink, flags, state); // x86's min/max are not symmetric; if either operand is a NaN, they return the // read-only operand: perform an addition between the two operands, which has the // desired NaN propagation effects. sink.bind_label(propagate_nan); let inst = Inst::xmm_rm_r(add_op, RegMem::reg(*lhs), *rhs_dst); inst.emit(sink, flags, state); one_way_jmp(sink, CC::P, done); sink.bind_label(do_min_max); let inst = Inst::xmm_rm_r(min_max_op, RegMem::reg(*lhs), *rhs_dst); inst.emit(sink, flags, state); sink.bind_label(done); } Inst::XmmRmRImm { op, src, dst, imm, is64: w, } => { let (prefix, opcode, len) = match op { SseOpcode::Cmpps => (LegacyPrefixes::None, 0x0FC2, 2), SseOpcode::Cmppd => (LegacyPrefixes::_66, 0x0FC2, 2), SseOpcode::Cmpss => (LegacyPrefixes::_F3, 0x0FC2, 2), SseOpcode::Cmpsd => (LegacyPrefixes::_F2, 0x0FC2, 2), SseOpcode::Insertps => (LegacyPrefixes::_66, 0x0F3A21, 3), SseOpcode::Pinsrb => (LegacyPrefixes::_66, 0x0F3A20, 3), SseOpcode::Pinsrw => (LegacyPrefixes::_66, 0x0FC4, 2), SseOpcode::Pinsrd => (LegacyPrefixes::_66, 0x0F3A22, 3), SseOpcode::Pextrb => (LegacyPrefixes::_66, 0x0F3A14, 3), SseOpcode::Pextrw => (LegacyPrefixes::_66, 0x0FC5, 2), SseOpcode::Pextrd => (LegacyPrefixes::_66, 0x0F3A16, 3), SseOpcode::Pshufd => (LegacyPrefixes::_66, 0x0F70, 2), _ => unimplemented!("Opcode {:?} not implemented", op), }; let rex = if *w { RexFlags::set_w() } else { RexFlags::clear_w() }; let regs_swapped = match *op { // These opcodes (and not the SSE2 version of PEXTRW) flip the operand // encoding: `dst` in ModRM's r/m, `src` in ModRM's reg field. SseOpcode::Pextrb | SseOpcode::Pextrd => true, // The rest of the opcodes have the customary encoding: `dst` in ModRM's reg, // `src` in ModRM's r/m field. _ => false, }; match src { RegMem::Reg { reg } => { if regs_swapped { emit_std_reg_reg(sink, prefix, opcode, len, *reg, dst.to_reg(), rex); } else { emit_std_reg_reg(sink, prefix, opcode, len, dst.to_reg(), *reg, rex); } } RegMem::Mem { addr } => { let addr = &addr.finalize(state); assert!( !regs_swapped, "No existing way to encode a mem argument in the ModRM r/m field." ); emit_std_reg_mem(sink, prefix, opcode, len, dst.to_reg(), addr, rex); } } sink.put1(*imm) } Inst::XmmLoadConstSeq { val, dst, ty } => { // This sequence is *one* instruction in the vcode, and is expanded only here at // emission time, because we cannot allow the regalloc to insert spills/reloads in // the middle; we depend on hardcoded PC-rel addressing below. TODO Eventually this // "constant inline" code should be replaced by constant pool integration. // Load the inline constant. let constant_start_label = sink.get_label(); let load_offset = Amode::rip_relative(BranchTarget::Label(constant_start_label)); let load = Inst::load(*ty, load_offset, *dst, ExtKind::None, None); load.emit(sink, flags, state); // Jump over the constant. let constant_end_label = sink.get_label(); let continue_at_offset = BranchTarget::Label(constant_end_label); let jump = Inst::jmp_known(continue_at_offset); jump.emit(sink, flags, state); // Emit the constant. sink.bind_label(constant_start_label); for i in val.iter() { sink.put1(*i); } sink.bind_label(constant_end_label); } Inst::XmmUninitializedValue { .. } => { // This instruction format only exists to declare a register as a `def`; no code is // emitted. } Inst::XmmMovRM { op, src, dst, srcloc, } => { let (prefix, opcode) = match op { SseOpcode::Movaps => (LegacyPrefixes::None, 0x0F29), SseOpcode::Movapd => (LegacyPrefixes::_66, 0x0F29), SseOpcode::Movdqa => (LegacyPrefixes::_66, 0x0F7F), SseOpcode::Movdqu => (LegacyPrefixes::_F3, 0x0F7F), SseOpcode::Movss => (LegacyPrefixes::_F3, 0x0F11), SseOpcode::Movsd => (LegacyPrefixes::_F2, 0x0F11), SseOpcode::Movups => (LegacyPrefixes::None, 0x0F11), SseOpcode::Movupd => (LegacyPrefixes::_66, 0x0F11), _ => unimplemented!("Opcode {:?} not implemented", op), }; let dst = &dst.finalize(state); if let Some(srcloc) = *srcloc { // Register the offset at which the actual load instruction starts. sink.add_trap(srcloc, TrapCode::HeapOutOfBounds); } emit_std_reg_mem(sink, prefix, opcode, 2, *src, dst, RexFlags::clear_w()); } Inst::XmmToGpr { op, src, dst, dst_size, } => { let (prefix, opcode, dst_first) = match op { // Movd and movq use the same opcode; the presence of the REX prefix (set below) // actually determines which is used. SseOpcode::Movd | SseOpcode::Movq => (LegacyPrefixes::_66, 0x0F7E, false), SseOpcode::Cvttss2si => (LegacyPrefixes::_F3, 0x0F2C, true), SseOpcode::Cvttsd2si => (LegacyPrefixes::_F2, 0x0F2C, true), _ => panic!("unexpected opcode {:?}", op), }; let rex = match dst_size { OperandSize::Size32 => RexFlags::clear_w(), OperandSize::Size64 => RexFlags::set_w(), }; let (src, dst) = if dst_first { (dst.to_reg(), *src) } else { (*src, dst.to_reg()) }; emit_std_reg_reg(sink, prefix, opcode, 2, src, dst, rex); } Inst::GprToXmm { op, src: src_e, dst: reg_g, src_size, } => { let (prefix, opcode) = match op { // Movd and movq use the same opcode; the presence of the REX prefix (set below) // actually determines which is used. SseOpcode::Movd | SseOpcode::Movq => (LegacyPrefixes::_66, 0x0F6E), SseOpcode::Cvtsi2ss => (LegacyPrefixes::_F3, 0x0F2A), SseOpcode::Cvtsi2sd => (LegacyPrefixes::_F2, 0x0F2A), _ => panic!("unexpected opcode {:?}", op), }; let rex = match *src_size { OperandSize::Size32 => RexFlags::clear_w(), OperandSize::Size64 => RexFlags::set_w(), }; match src_e { RegMem::Reg { reg: reg_e } => { emit_std_reg_reg(sink, prefix, opcode, 2, reg_g.to_reg(), *reg_e, rex); } RegMem::Mem { addr } => { let addr = &addr.finalize(state); emit_std_reg_mem(sink, prefix, opcode, 2, reg_g.to_reg(), addr, rex); } } } Inst::XmmCmpRmR { op, src, dst } => { let rex = RexFlags::clear_w(); let (prefix, opcode, len) = match op { SseOpcode::Ptest => (LegacyPrefixes::_66, 0x0F3817, 3), SseOpcode::Ucomisd => (LegacyPrefixes::_66, 0x0F2E, 2), SseOpcode::Ucomiss => (LegacyPrefixes::None, 0x0F2E, 2), _ => unimplemented!("Emit xmm cmp rm r"), }; match src { RegMem::Reg { reg } => { emit_std_reg_reg(sink, prefix, opcode, len, *dst, *reg, rex); } RegMem::Mem { addr } => { let addr = &addr.finalize(state); emit_std_reg_mem(sink, prefix, opcode, len, *dst, addr, rex); } } } Inst::CvtUint64ToFloatSeq { to_f64, src, dst, tmp_gpr1, tmp_gpr2, } => { // Note: this sequence is specific to 64-bit mode; a 32-bit mode would require a // different sequence. // // Emit the following sequence: // // cmp 0, %src // jl handle_negative // // ;; handle positive, which can't overflow // cvtsi2sd/cvtsi2ss %src, %dst // j done // // ;; handle negative: see below for an explanation of what it's doing. // handle_negative: // mov %src, %tmp_gpr1 // shr $1, %tmp_gpr1 // mov %src, %tmp_gpr2 // and $1, %tmp_gpr2 // or %tmp_gpr1, %tmp_gpr2 // cvtsi2sd/cvtsi2ss %tmp_gpr2, %dst // addsd/addss %dst, %dst // // done: assert_ne!(src, tmp_gpr1); assert_ne!(src, tmp_gpr2); assert_ne!(tmp_gpr1, tmp_gpr2); let handle_negative = sink.get_label(); let done = sink.get_label(); // If x seen as a signed int64 is not negative, a signed-conversion will do the right // thing. // TODO use tst src, src here. let inst = Inst::cmp_rmi_r(8, RegMemImm::imm(0), src.to_reg()); inst.emit(sink, flags, state); one_way_jmp(sink, CC::L, handle_negative); // Handle a positive int64, which is the "easy" case: a signed conversion will do the // right thing. emit_signed_cvt(sink, flags, state, src.to_reg(), *dst, *to_f64); let inst = Inst::jmp_known(BranchTarget::Label(done)); inst.emit(sink, flags, state); sink.bind_label(handle_negative); // Divide x by two to get it in range for the signed conversion, keep the LSB, and // scale it back up on the FP side. let inst = Inst::gen_move(*tmp_gpr1, src.to_reg(), types::I64); inst.emit(sink, flags, state); // tmp_gpr1 := src >> 1 let inst = Inst::shift_r(8, ShiftKind::ShiftRightLogical, Some(1), *tmp_gpr1); inst.emit(sink, flags, state); let inst = Inst::gen_move(*tmp_gpr2, src.to_reg(), types::I64); inst.emit(sink, flags, state); let inst = Inst::alu_rmi_r( true, /* 64bits */ AluRmiROpcode::And, RegMemImm::imm(1), *tmp_gpr2, ); inst.emit(sink, flags, state); let inst = Inst::alu_rmi_r( true, /* 64bits */ AluRmiROpcode::Or, RegMemImm::reg(tmp_gpr1.to_reg()), *tmp_gpr2, ); inst.emit(sink, flags, state); emit_signed_cvt(sink, flags, state, tmp_gpr2.to_reg(), *dst, *to_f64); let add_op = if *to_f64 { SseOpcode::Addsd } else { SseOpcode::Addss }; let inst = Inst::xmm_rm_r(add_op, RegMem::reg(dst.to_reg()), *dst); inst.emit(sink, flags, state); sink.bind_label(done); } Inst::CvtFloatToSintSeq { src_size, dst_size, is_saturating, src, dst, tmp_gpr, tmp_xmm, srcloc, } => { // Emits the following common sequence: // // cvttss2si/cvttsd2si %src, %dst // cmp %dst, 1 // jno done // // Then, for saturating conversions: // // ;; check for NaN // cmpss/cmpsd %src, %src // jnp not_nan // xor %dst, %dst // // ;; positive inputs get saturated to INT_MAX; negative ones to INT_MIN, which is // ;; already in %dst. // xorpd %tmp_xmm, %tmp_xmm // cmpss/cmpsd %src, %tmp_xmm // jnb done // mov/movaps $INT_MAX, %dst // // done: // // Then, for non-saturating conversions: // // ;; check for NaN // cmpss/cmpsd %src, %src // jnp not_nan // ud2 trap BadConversionToInteger // // ;; check if INT_MIN was the correct result, against a magic constant: // not_nan: // movaps/mov $magic, %tmp_gpr // movq/movd %tmp_gpr, %tmp_xmm // cmpss/cmpsd %tmp_xmm, %src // jnb/jnbe $check_positive // ud2 trap IntegerOverflow // // ;; if positive, it was a real overflow // check_positive: // xorpd %tmp_xmm, %tmp_xmm // cmpss/cmpsd %src, %tmp_xmm // jnb done // ud2 trap IntegerOverflow // // done: let src = src.to_reg(); let (cast_op, cmp_op, trunc_op) = match src_size { OperandSize::Size64 => (SseOpcode::Movq, SseOpcode::Ucomisd, SseOpcode::Cvttsd2si), OperandSize::Size32 => (SseOpcode::Movd, SseOpcode::Ucomiss, SseOpcode::Cvttss2si), }; let done = sink.get_label(); let not_nan = sink.get_label(); // The truncation. let inst = Inst::xmm_to_gpr(trunc_op, src, *dst, *dst_size); inst.emit(sink, flags, state); // Compare against 1, in case of overflow the dst operand was INT_MIN. let inst = Inst::cmp_rmi_r(dst_size.to_bytes(), RegMemImm::imm(1), dst.to_reg()); inst.emit(sink, flags, state); one_way_jmp(sink, CC::NO, done); // no overflow => done // Check for NaN. let inst = Inst::xmm_cmp_rm_r(cmp_op, RegMem::reg(src), src); inst.emit(sink, flags, state); one_way_jmp(sink, CC::NP, not_nan); // go to not_nan if not a NaN if *is_saturating { // For NaN, emit 0. let inst = Inst::alu_rmi_r( *dst_size == OperandSize::Size64, AluRmiROpcode::Xor, RegMemImm::reg(dst.to_reg()), *dst, ); inst.emit(sink, flags, state); let inst = Inst::jmp_known(BranchTarget::Label(done)); inst.emit(sink, flags, state); sink.bind_label(not_nan); // If the input was positive, saturate to INT_MAX. // Zero out tmp_xmm. let inst = Inst::xmm_rm_r(SseOpcode::Xorpd, RegMem::reg(tmp_xmm.to_reg()), *tmp_xmm); inst.emit(sink, flags, state); let inst = Inst::xmm_cmp_rm_r(cmp_op, RegMem::reg(src), tmp_xmm.to_reg()); inst.emit(sink, flags, state); // Jump if >= to done. one_way_jmp(sink, CC::NB, done); // Otherwise, put INT_MAX. if *dst_size == OperandSize::Size64 { let inst = Inst::imm(OperandSize::Size64, 0x7fffffffffffffff, *dst); inst.emit(sink, flags, state); } else { let inst = Inst::imm(OperandSize::Size32, 0x7fffffff, *dst); inst.emit(sink, flags, state); } } else { let check_positive = sink.get_label(); let inst = Inst::trap(*srcloc, TrapCode::BadConversionToInteger); inst.emit(sink, flags, state); // Check if INT_MIN was the correct result: determine the smallest floating point // number that would convert to INT_MIN, put it in a temporary register, and compare // against the src register. // If the src register is less (or in some cases, less-or-equal) than the threshold, // trap! sink.bind_label(not_nan); let mut no_overflow_cc = CC::NB; // >= let output_bits = dst_size.to_bits(); match *src_size { OperandSize::Size32 => { let cst = Ieee32::pow2(output_bits - 1).neg().bits(); let inst = Inst::imm(OperandSize::Size32, cst as u64, *tmp_gpr); inst.emit(sink, flags, state); } OperandSize::Size64 => { // An f64 can represent `i32::min_value() - 1` exactly with precision to spare, // so there are values less than -2^(N-1) that convert correctly to INT_MIN. let cst = if output_bits < 64 { no_overflow_cc = CC::NBE; // > Ieee64::fcvt_to_sint_negative_overflow(output_bits) } else { Ieee64::pow2(output_bits - 1).neg() }; let inst = Inst::imm(OperandSize::Size64, cst.bits(), *tmp_gpr); inst.emit(sink, flags, state); } } let inst = Inst::gpr_to_xmm(cast_op, RegMem::reg(tmp_gpr.to_reg()), *src_size, *tmp_xmm); inst.emit(sink, flags, state); let inst = Inst::xmm_cmp_rm_r(cmp_op, RegMem::reg(tmp_xmm.to_reg()), src); inst.emit(sink, flags, state); // jump over trap if src >= or > threshold one_way_jmp(sink, no_overflow_cc, check_positive); let inst = Inst::trap(*srcloc, TrapCode::IntegerOverflow); inst.emit(sink, flags, state); // If positive, it was a real overflow. sink.bind_label(check_positive); // Zero out the tmp_xmm register. let inst = Inst::xmm_rm_r(SseOpcode::Xorpd, RegMem::reg(tmp_xmm.to_reg()), *tmp_xmm); inst.emit(sink, flags, state); let inst = Inst::xmm_cmp_rm_r(cmp_op, RegMem::reg(src), tmp_xmm.to_reg()); inst.emit(sink, flags, state); one_way_jmp(sink, CC::NB, done); // jump over trap if 0 >= src let inst = Inst::trap(*srcloc, TrapCode::IntegerOverflow); inst.emit(sink, flags, state); } sink.bind_label(done); } Inst::CvtFloatToUintSeq { src_size, dst_size, is_saturating, src, dst, tmp_gpr, tmp_xmm, srcloc, } => { // The only difference in behavior between saturating and non-saturating is how we // handle errors. Emits the following sequence: // // movaps/mov 2**(int_width - 1), %tmp_gpr // movq/movd %tmp_gpr, %tmp_xmm // cmpss/cmpsd %tmp_xmm, %src // jnb is_large // // ;; check for NaN inputs // jnp not_nan // -- non-saturating: ud2 trap BadConversionToInteger // -- saturating: xor %dst, %dst; j done // // not_nan: // cvttss2si/cvttsd2si %src, %dst // cmp 0, %dst // jnl done // -- non-saturating: ud2 trap IntegerOverflow // -- saturating: xor %dst, %dst; j done // // is_large: // subss/subsd %tmp_xmm, %src ; <-- we clobber %src here // cvttss2si/cvttss2sd %tmp_x, %dst // cmp 0, %dst // jnl next_is_large // -- non-saturating: ud2 trap IntegerOverflow // -- saturating: movaps $UINT_MAX, %dst; j done // // next_is_large: // add 2**(int_width -1), %dst ;; 2 instructions for 64-bits integers // // done: assert_ne!(tmp_xmm, src, "tmp_xmm clobbers src!"); let (sub_op, cast_op, cmp_op, trunc_op) = if *src_size == OperandSize::Size64 { ( SseOpcode::Subsd, SseOpcode::Movq, SseOpcode::Ucomisd, SseOpcode::Cvttsd2si, ) } else { ( SseOpcode::Subss, SseOpcode::Movd, SseOpcode::Ucomiss, SseOpcode::Cvttss2si, ) }; let done = sink.get_label(); let cst = if *src_size == OperandSize::Size64 { Ieee64::pow2(dst_size.to_bits() - 1).bits() } else { Ieee32::pow2(dst_size.to_bits() - 1).bits() as u64 }; let inst = Inst::imm(*src_size, cst, *tmp_gpr); inst.emit(sink, flags, state); let inst = Inst::gpr_to_xmm(cast_op, RegMem::reg(tmp_gpr.to_reg()), *src_size, *tmp_xmm); inst.emit(sink, flags, state); let inst = Inst::xmm_cmp_rm_r(cmp_op, RegMem::reg(tmp_xmm.to_reg()), src.to_reg()); inst.emit(sink, flags, state); let handle_large = sink.get_label(); one_way_jmp(sink, CC::NB, handle_large); // jump to handle_large if src >= large_threshold let not_nan = sink.get_label(); one_way_jmp(sink, CC::NP, not_nan); // jump over trap if not NaN if *is_saturating { // Emit 0. let inst = Inst::alu_rmi_r( *dst_size == OperandSize::Size64, AluRmiROpcode::Xor, RegMemImm::reg(dst.to_reg()), *dst, ); inst.emit(sink, flags, state); let inst = Inst::jmp_known(BranchTarget::Label(done)); inst.emit(sink, flags, state); } else { // Trap. let inst = Inst::trap(*srcloc, TrapCode::BadConversionToInteger); inst.emit(sink, flags, state); } sink.bind_label(not_nan); // Actual truncation for small inputs: if the result is not positive, then we had an // overflow. let inst = Inst::xmm_to_gpr(trunc_op, src.to_reg(), *dst, *dst_size); inst.emit(sink, flags, state); let inst = Inst::cmp_rmi_r(dst_size.to_bytes(), RegMemImm::imm(0), dst.to_reg()); inst.emit(sink, flags, state); one_way_jmp(sink, CC::NL, done); // if dst >= 0, jump to done if *is_saturating { // The input was "small" (< 2**(width -1)), so the only way to get an integer // overflow is because the input was too small: saturate to the min value, i.e. 0. let inst = Inst::alu_rmi_r( *dst_size == OperandSize::Size64, AluRmiROpcode::Xor, RegMemImm::reg(dst.to_reg()), *dst, ); inst.emit(sink, flags, state); let inst = Inst::jmp_known(BranchTarget::Label(done)); inst.emit(sink, flags, state); } else { // Trap. let inst = Inst::trap(*srcloc, TrapCode::IntegerOverflow); inst.emit(sink, flags, state); } // Now handle large inputs. sink.bind_label(handle_large); let inst = Inst::xmm_rm_r(sub_op, RegMem::reg(tmp_xmm.to_reg()), *src); inst.emit(sink, flags, state); let inst = Inst::xmm_to_gpr(trunc_op, src.to_reg(), *dst, *dst_size); inst.emit(sink, flags, state); let inst = Inst::cmp_rmi_r(dst_size.to_bytes(), RegMemImm::imm(0), dst.to_reg()); inst.emit(sink, flags, state); let next_is_large = sink.get_label(); one_way_jmp(sink, CC::NL, next_is_large); // if dst >= 0, jump to next_is_large if *is_saturating { // The input was "large" (>= 2**(width -1)), so the only way to get an integer // overflow is because the input was too large: saturate to the max value. let inst = Inst::imm( OperandSize::Size64, if *dst_size == OperandSize::Size64 { u64::max_value() } else { u32::max_value() as u64 }, *dst, ); inst.emit(sink, flags, state); let inst = Inst::jmp_known(BranchTarget::Label(done)); inst.emit(sink, flags, state); } else { let inst = Inst::trap(*srcloc, TrapCode::IntegerOverflow); inst.emit(sink, flags, state); } sink.bind_label(next_is_large); if *dst_size == OperandSize::Size64 { let inst = Inst::imm(OperandSize::Size64, 1 << 63, *tmp_gpr); inst.emit(sink, flags, state); let inst = Inst::alu_rmi_r( true, AluRmiROpcode::Add, RegMemImm::reg(tmp_gpr.to_reg()), *dst, ); inst.emit(sink, flags, state); } else { let inst = Inst::alu_rmi_r(false, AluRmiROpcode::Add, RegMemImm::imm(1 << 31), *dst); inst.emit(sink, flags, state); } sink.bind_label(done); } Inst::LoadExtName { dst, name, offset, srcloc, } => { // The full address can be encoded in the register, with a relocation. // Generates: movabsq $name, %dst let enc_dst = int_reg_enc(dst.to_reg()); sink.put1(0x48 | ((enc_dst >> 3) & 1)); sink.put1(0xB8 | (enc_dst & 7)); sink.add_reloc(*srcloc, Reloc::Abs8, name, *offset); if flags.emit_all_ones_funcaddrs() { sink.put8(u64::max_value()); } else { sink.put8(0); } } Inst::LockCmpxchg { ty, src, dst, srcloc, } => { if let Some(srcloc) = srcloc { sink.add_trap(*srcloc, TrapCode::HeapOutOfBounds); } // lock cmpxchg{b,w,l,q} %src, (dst) // Note that 0xF0 is the Lock prefix. let (prefix, rex, opcodes) = match *ty { types::I8 => { let mut rex_flags = RexFlags::clear_w(); let enc_src = int_reg_enc(*src); if enc_src >= 4 && enc_src <= 7 { rex_flags.always_emit(); }; (LegacyPrefixes::_F0, rex_flags, 0x0FB0) } types::I16 => (LegacyPrefixes::_66F0, RexFlags::clear_w(), 0x0FB1), types::I32 => (LegacyPrefixes::_F0, RexFlags::clear_w(), 0x0FB1), types::I64 => (LegacyPrefixes::_F0, RexFlags::set_w(), 0x0FB1), _ => unreachable!(), }; emit_std_reg_mem(sink, prefix, opcodes, 2, *src, &dst.finalize(state), rex); } Inst::AtomicRmwSeq { ty, op, srcloc } => { // Emit this: // // mov{zbq,zwq,zlq,q} (%r9), %rax // rax = old value // again: // movq %rax, %r11 // rax = old value, r11 = old value // `op`q %r10, %r11 // rax = old value, r11 = new value // lock cmpxchg{b,w,l,q} %r11, (%r9) // try to store new value // jnz again // If this is taken, rax will have a "revised" old value // // Operand conventions: // IN: %r9 (addr), %r10 (2nd arg for `op`) // OUT: %rax (old value), %r11 (trashed), %rflags (trashed) // // In the case where the operation is 'xchg', the "`op`q" instruction is instead // movq %r10, %r11 // so that we simply write in the destination, the "2nd arg for `op`". let rax = regs::rax(); let r9 = regs::r9(); let r10 = regs::r10(); let r11 = regs::r11(); let rax_w = Writable::from_reg(rax); let r11_w = Writable::from_reg(r11); let amode = Amode::imm_reg(0, r9); let again_label = sink.get_label(); // mov{zbq,zwq,zlq,q} (%r9), %rax // No need to call `add_trap` here, since the `i1` emit will do that. let i1 = Inst::load(*ty, amode.clone(), rax_w, ExtKind::ZeroExtend, *srcloc); i1.emit(sink, flags, state); // again: sink.bind_label(again_label); // movq %rax, %r11 let i2 = Inst::mov_r_r(true, rax, r11_w); i2.emit(sink, flags, state); // opq %r10, %r11 let r10_rmi = RegMemImm::reg(r10); let i3 = if *op == inst_common::AtomicRmwOp::Xchg { Inst::mov_r_r(true, r10, r11_w) } else { let alu_op = match op { inst_common::AtomicRmwOp::Add => AluRmiROpcode::Add, inst_common::AtomicRmwOp::Sub => AluRmiROpcode::Sub, inst_common::AtomicRmwOp::And => AluRmiROpcode::And, inst_common::AtomicRmwOp::Or => AluRmiROpcode::Or, inst_common::AtomicRmwOp::Xor => AluRmiROpcode::Xor, inst_common::AtomicRmwOp::Xchg => unreachable!(), }; Inst::alu_rmi_r(true, alu_op, r10_rmi, r11_w) }; i3.emit(sink, flags, state); // lock cmpxchg{b,w,l,q} %r11, (%r9) // No need to call `add_trap` here, since the `i4` emit will do that. let i4 = Inst::LockCmpxchg { ty: *ty, src: r11, dst: amode.into(), srcloc: *srcloc, }; i4.emit(sink, flags, state); // jnz again one_way_jmp(sink, CC::NZ, again_label); } Inst::Fence { kind } => { sink.put1(0x0F); sink.put1(0xAE); match kind { FenceKind::MFence => sink.put1(0xF0), // mfence = 0F AE F0 FenceKind::LFence => sink.put1(0xE8), // lfence = 0F AE E8 FenceKind::SFence => sink.put1(0xF8), // sfence = 0F AE F8 } } Inst::Hlt => { sink.put1(0xcc); } Inst::Ud2 { trap_info } => { sink.add_trap(trap_info.0, trap_info.1); if let Some(s) = state.take_stack_map() { sink.add_stack_map(StackMapExtent::UpcomingBytes(2), s); } sink.put1(0x0f); sink.put1(0x0b); } Inst::VirtualSPOffsetAdj { offset } => { debug!( "virtual sp offset adjusted by {} -> {}", offset, state.virtual_sp_offset + offset ); state.virtual_sp_offset += offset; } Inst::Nop { .. } | Inst::EpiloguePlaceholder => { // Generate no code. } } state.clear_post_insn(); }
38.447196
103
0.463173
91467e3339b9ce41eb67b792968797a713a6b991
13,148
use engine_core::{engine_state, execution}; use engine_test_support::{ internal::{ DeployItemBuilder, ExecuteRequestBuilder, InMemoryWasmTestBuilder, DEFAULT_GENESIS_CONFIG, DEFAULT_PAYMENT, STANDARD_PAYMENT_CONTRACT, }, DEFAULT_ACCOUNT_ADDR, }; use types::account::{PublicKey, Weight}; const CONTRACT_ADD_UPDATE_ASSOCIATED_KEY: &str = "add_update_associated_key.wasm"; const CONTRACT_AUTHORIZED_KEYS: &str = "authorized_keys.wasm"; #[ignore] #[test] fn should_deploy_with_authorized_identity_key() { let exec_request = ExecuteRequestBuilder::standard( DEFAULT_ACCOUNT_ADDR, CONTRACT_AUTHORIZED_KEYS, (Weight::new(1), Weight::new(1)), ) .build(); // Basic deploy with single key InMemoryWasmTestBuilder::default() .run_genesis(&DEFAULT_GENESIS_CONFIG) .exec(exec_request) .commit() .expect_success(); } #[ignore] #[test] fn should_raise_auth_failure_with_invalid_key() { // tests that authorized keys that does not belong to account raises // Error::Authorization let key_1 = PublicKey::ed25519_from([254; 32]); assert_ne!(DEFAULT_ACCOUNT_ADDR, key_1); let exec_request = { let deploy = DeployItemBuilder::new() .with_address(DEFAULT_ACCOUNT_ADDR) .with_payment_code(STANDARD_PAYMENT_CONTRACT, (*DEFAULT_PAYMENT,)) .with_session_code(CONTRACT_AUTHORIZED_KEYS, (Weight::new(1), Weight::new(1))) .with_deploy_hash([1u8; 32]) .with_authorization_keys(&[key_1]) .build(); ExecuteRequestBuilder::from_deploy_item(deploy).build() }; // Basic deploy with single key let result = InMemoryWasmTestBuilder::default() .run_genesis(&DEFAULT_GENESIS_CONFIG) .exec(exec_request) .commit() .finish(); let deploy_result = result .builder() .get_exec_response(0) .expect("should have exec response") .get(0) .expect("should have at least one deploy result"); assert!( deploy_result.has_precondition_failure(), "{:?}", deploy_result ); let message = format!("{}", deploy_result.error().unwrap()); assert_eq!(message, format!("{}", engine_state::Error::Authorization)) } #[ignore] #[test] fn should_raise_auth_failure_with_invalid_keys() { // tests that authorized keys that does not belong to account raises // Error::Authorization let key_1 = PublicKey::ed25519_from([254; 32]); let key_2 = PublicKey::ed25519_from([253; 32]); let key_3 = PublicKey::ed25519_from([252; 32]); assert_ne!(DEFAULT_ACCOUNT_ADDR, key_1); assert_ne!(DEFAULT_ACCOUNT_ADDR, key_2); assert_ne!(DEFAULT_ACCOUNT_ADDR, key_3); let exec_request = { let deploy = DeployItemBuilder::new() .with_address(DEFAULT_ACCOUNT_ADDR) .with_payment_code(STANDARD_PAYMENT_CONTRACT, (*DEFAULT_PAYMENT,)) .with_session_code("authorized_keys.wasm", (Weight::new(1), Weight::new(1))) .with_deploy_hash([1u8; 32]) .with_authorization_keys(&[key_2, key_1, key_3]) .build(); ExecuteRequestBuilder::from_deploy_item(deploy).build() }; // Basic deploy with single key let result = InMemoryWasmTestBuilder::default() .run_genesis(&DEFAULT_GENESIS_CONFIG) .exec(exec_request) .commit() .finish(); let deploy_result = result .builder() .get_exec_response(0) .expect("should have exec response") .get(0) .expect("should have at least one deploy result"); assert!(deploy_result.has_precondition_failure()); let message = format!("{}", deploy_result.error().unwrap()); assert_eq!(message, format!("{}", engine_state::Error::Authorization)) } #[ignore] #[test] fn should_raise_deploy_authorization_failure() { // tests that authorized keys needs sufficient cumulative weight let key_1 = PublicKey::ed25519_from([254; 32]); let key_2 = PublicKey::ed25519_from([253; 32]); let key_3 = PublicKey::ed25519_from([252; 32]); assert_ne!(DEFAULT_ACCOUNT_ADDR, key_1); assert_ne!(DEFAULT_ACCOUNT_ADDR, key_2); assert_ne!(DEFAULT_ACCOUNT_ADDR, key_3); let exec_request_1 = ExecuteRequestBuilder::standard( DEFAULT_ACCOUNT_ADDR, CONTRACT_ADD_UPDATE_ASSOCIATED_KEY, (key_1,), ) .build(); let exec_request_2 = ExecuteRequestBuilder::standard( DEFAULT_ACCOUNT_ADDR, CONTRACT_ADD_UPDATE_ASSOCIATED_KEY, (key_2,), ) .build(); let exec_request_3 = ExecuteRequestBuilder::standard( DEFAULT_ACCOUNT_ADDR, CONTRACT_ADD_UPDATE_ASSOCIATED_KEY, (key_3,), ) .build(); // Deploy threshold is equal to 3, keymgmnt is still 1. // Even after verifying weights and thresholds to not // lock out the account, those values should work as // account now has 1. identity key with weight=1 and // a key with weight=2. let exec_request_4 = ExecuteRequestBuilder::standard( DEFAULT_ACCOUNT_ADDR, CONTRACT_AUTHORIZED_KEYS, (Weight::new(4), Weight::new(3)), ) .build(); // Basic deploy with single key let result1 = InMemoryWasmTestBuilder::default() .run_genesis(&DEFAULT_GENESIS_CONFIG) // Reusing a test contract that would add new key .exec(exec_request_1) .expect_success() .commit() .exec(exec_request_2) .expect_success() .commit() .exec(exec_request_3) .expect_success() .commit() // This should execute successfuly - change deploy and key management // thresholds. .exec(exec_request_4) .expect_success() .commit() .finish(); let exec_request_5 = ExecuteRequestBuilder::standard( DEFAULT_ACCOUNT_ADDR, CONTRACT_AUTHORIZED_KEYS, (Weight::new(5), Weight::new(4)), //args ) .build(); // With deploy threshold == 3 using single secondary key // with weight == 2 should raise deploy authorization failure. let result2 = InMemoryWasmTestBuilder::from_result(result1) .exec(exec_request_5) .commit() .finish(); { let deploy_result = result2 .builder() .get_exec_response(0) .expect("should have exec response") .get(0) .expect("should have at least one deploy result"); assert!(deploy_result.has_precondition_failure()); let message = format!("{}", deploy_result.error().unwrap()); assert!(message.contains(&format!( "{}", execution::Error::DeploymentAuthorizationFailure ))) } let exec_request_6 = { let deploy = DeployItemBuilder::new() .with_address(DEFAULT_ACCOUNT_ADDR) .with_payment_code(STANDARD_PAYMENT_CONTRACT, (*DEFAULT_PAYMENT,)) // change deployment threshold to 4 .with_session_code("authorized_keys.wasm", (Weight::new(6), Weight::new(5))) .with_deploy_hash([6u8; 32]) .with_authorization_keys(&[DEFAULT_ACCOUNT_ADDR, key_1, key_2, key_3]) .build(); ExecuteRequestBuilder::from_deploy_item(deploy).build() }; // identity key (w: 1) and key_1 (w: 2) passes threshold of 3 let result3 = InMemoryWasmTestBuilder::from_result(result2) .exec(exec_request_6) .expect_success() .commit() .finish(); let exec_request_7 = ExecuteRequestBuilder::standard( DEFAULT_ACCOUNT_ADDR, CONTRACT_AUTHORIZED_KEYS, (Weight::new(0), Weight::new(0)), //args ) .build(); // deployment threshold is now 4 // failure: key_2 weight + key_1 weight < deployment threshold let result4 = InMemoryWasmTestBuilder::from_result(result3) .exec(exec_request_7) .commit() .finish(); { let deploy_result = result4 .builder() .get_exec_response(0) .expect("should have exec response") .get(0) .expect("should have at least one deploy result"); assert!(deploy_result.has_precondition_failure()); let message = format!("{}", deploy_result.error().unwrap()); assert!(message.contains(&format!( "{}", execution::Error::DeploymentAuthorizationFailure ))) } let exec_request_8 = { let deploy = DeployItemBuilder::new() .with_address(DEFAULT_ACCOUNT_ADDR) .with_payment_code(STANDARD_PAYMENT_CONTRACT, (*DEFAULT_PAYMENT,)) // change deployment threshold to 4 .with_session_code( "authorized_keys.wasm", (Weight::new(0), Weight::new(0)), //args ) .with_deploy_hash([8u8; 32]) .with_authorization_keys(&[DEFAULT_ACCOUNT_ADDR, key_1, key_2, key_3]) .build(); ExecuteRequestBuilder::from_deploy_item(deploy).build() }; // success: identity key weight + key_1 weight + key_2 weight >= deployment // threshold InMemoryWasmTestBuilder::from_result(result4) .exec(exec_request_8) .commit() .expect_success() .finish(); } #[ignore] #[test] fn should_authorize_deploy_with_multiple_keys() { // tests that authorized keys needs sufficient cumulative weight // and each of the associated keys is greater than threshold let key_1 = PublicKey::ed25519_from([254; 32]); let key_2 = PublicKey::ed25519_from([253; 32]); assert_ne!(DEFAULT_ACCOUNT_ADDR, key_1); assert_ne!(DEFAULT_ACCOUNT_ADDR, key_2); let exec_request_1 = ExecuteRequestBuilder::standard( DEFAULT_ACCOUNT_ADDR, CONTRACT_ADD_UPDATE_ASSOCIATED_KEY, (key_1,), ) .build(); let exec_request_2 = ExecuteRequestBuilder::standard( DEFAULT_ACCOUNT_ADDR, CONTRACT_ADD_UPDATE_ASSOCIATED_KEY, (key_2,), ) .build(); // Basic deploy with single key let result1 = InMemoryWasmTestBuilder::default() .run_genesis(&DEFAULT_GENESIS_CONFIG) // Reusing a test contract that would add new key .exec(exec_request_1) .expect_success() .commit() .exec(exec_request_2) .expect_success() .commit() .finish(); // key_1 (w: 2) key_2 (w: 2) each passes default threshold of 1 let exec_request_3 = ExecuteRequestBuilder::standard( DEFAULT_ACCOUNT_ADDR, CONTRACT_AUTHORIZED_KEYS, (Weight::new(0), Weight::new(0)), ) .build(); InMemoryWasmTestBuilder::from_result(result1) .exec(exec_request_3) .expect_success() .commit(); } #[ignore] #[test] fn should_not_authorize_deploy_with_duplicated_keys() { // tests that authorized keys needs sufficient cumulative weight // and each of the associated keys is greater than threshold let key_1 = PublicKey::ed25519_from([254; 32]); assert_ne!(DEFAULT_ACCOUNT_ADDR, key_1); let exec_request_1 = ExecuteRequestBuilder::standard( DEFAULT_ACCOUNT_ADDR, CONTRACT_ADD_UPDATE_ASSOCIATED_KEY, (key_1,), ) .build(); let exec_request_2 = ExecuteRequestBuilder::standard( DEFAULT_ACCOUNT_ADDR, CONTRACT_AUTHORIZED_KEYS, (Weight::new(4), Weight::new(3)), ) .build(); // Basic deploy with single key let result1 = InMemoryWasmTestBuilder::default() .run_genesis(&DEFAULT_GENESIS_CONFIG) // Reusing a test contract that would add new key .exec(exec_request_1) .expect_success() .commit() .exec(exec_request_2) .expect_success() .commit() .finish(); let exec_request_3 = { let deploy = DeployItemBuilder::new() .with_address(DEFAULT_ACCOUNT_ADDR) .with_payment_code(STANDARD_PAYMENT_CONTRACT, (*DEFAULT_PAYMENT,)) .with_session_code("authorized_keys.wasm", (Weight::new(0), Weight::new(0))) .with_deploy_hash([3u8; 32]) .with_authorization_keys(&[ key_1, key_1, key_1, key_1, key_1, key_1, key_1, key_1, key_1, key_1, ]) .build(); ExecuteRequestBuilder::from_deploy_item(deploy).build() }; // success: identity key weight + key_1 weight + key_2 weight >= deployment // threshold let final_result = InMemoryWasmTestBuilder::from_result(result1) .exec(exec_request_3) .commit() .finish(); let deploy_result = final_result .builder() .get_exec_response(0) .expect("should have exec response") .get(0) .expect("should have at least one deploy result"); assert!( deploy_result.has_precondition_failure(), "{:?}", deploy_result ); let message = format!("{}", deploy_result.error().unwrap()); assert!(message.contains(&format!( "{}", execution::Error::DeploymentAuthorizationFailure ))) }
33.20202
98
0.635002
fc25d5ca8322845023f8f4fdf6c86c65b18d8956
2,090
use crate::printer::Printer; use anyhow::{Context, Result}; use log::info; use reinfer_client::{Client, DatasetIdentifier, SourceId, SourceIdentifier, UpdateDataset}; use structopt::StructOpt; /// Update a dataset. #[derive(Debug, StructOpt)] pub struct UpdateDatasetArgs { #[structopt(name = "dataset")] /// Name or id of the dataset to delete dataset: DatasetIdentifier, #[structopt(long = "title")] /// Set the title of the dataset title: Option<String>, #[structopt(long = "description")] /// Set the description of the dataset description: Option<String>, #[structopt(short = "s", long = "source")] /// Names or ids of the sources in the dataset sources: Option<Vec<SourceIdentifier>>, } pub fn update(client: &Client, args: &UpdateDatasetArgs, printer: &Printer) -> Result<()> { let UpdateDatasetArgs { dataset, title, description, sources, } = args; let source_ids = sources .as_ref() .map::<Result<Vec<SourceId>>, _>(|sources| { sources .iter() .map(|source| Ok(client.get_source(source.clone())?.id)) .collect() }) .transpose() .context("Operation to get sources failed")?; let dataset_full_name = match dataset { DatasetIdentifier::FullName(name) => name.to_owned(), dataset @ DatasetIdentifier::Id(_) => client .get_dataset(dataset.to_owned()) .context("Fetching dataset id.")? .full_name(), }; let dataset = client .update_dataset( &dataset_full_name, UpdateDataset { source_ids: source_ids.as_deref(), title: title.as_deref(), description: description.as_deref(), }, ) .context("Operation to update a dataset has failed.")?; info!( "Dataset `{}` [id: {}] updated successfully", dataset.full_name().0, dataset.id.0, ); printer.print_resources(&[dataset])?; Ok(()) }
29.027778
91
0.580861
11affb9dfd576bc55921b8ee5b82a4048a2fdbc7
77,910
// 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. //! Collections implemented with bit vectors. //! //! # Example //! //! This is a simple example of the [Sieve of Eratosthenes][sieve] //! which calculates prime numbers up to a given limit. //! //! [sieve]: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes //! //! ``` //! use std::collections::{BitvSet, Bitv}; //! use std::iter; //! //! let max_prime = 10000; //! //! // Store the primes as a BitvSet //! let primes = { //! // Assume all numbers are prime to begin, and then we //! // cross off non-primes progressively //! let mut bv = Bitv::with_capacity(max_prime, true); //! //! // Neither 0 nor 1 are prime //! bv.set(0, false); //! bv.set(1, false); //! //! for i in range(2, max_prime) { //! // if i is a prime //! if bv[i] { //! // Mark all multiples of i as non-prime (any multiples below i * i //! // will have been marked as non-prime previously) //! for j in iter::range_step(i * i, max_prime, i) { bv.set(j, false) } //! } //! } //! BitvSet::from_bitv(bv) //! }; //! //! // Simple primality tests below our max bound //! let print_primes = 20; //! print!("The primes below {} are: ", print_primes); //! for x in range(0, print_primes) { //! if primes.contains(&x) { //! print!("{} ", x); //! } //! } //! println!(""); //! //! // We can manipulate the internal Bitv //! let num_primes = primes.get_ref().iter().filter(|x| *x).count(); //! println!("There are {} primes below {}", num_primes, max_prime); //! ``` #![allow(missing_doc)] use core::prelude::*; use core::cmp; use core::default::Default; use core::fmt; use core::iter::{Chain, Enumerate, Repeat, Skip, Take}; use core::iter; use core::slice; use core::uint; use std::hash; use {Mutable, Set, MutableSet, MutableSeq}; use vec::Vec; type MatchWords<'a> = Chain<MaskWords<'a>, Skip<Take<Enumerate<Repeat<uint>>>>>; // Take two BitV's, and return iterators of their words, where the shorter one // has been padded with 0's fn match_words <'a,'b>(a: &'a Bitv, b: &'b Bitv) -> (MatchWords<'a>, MatchWords<'b>) { let a_len = a.storage.len(); let b_len = b.storage.len(); // have to uselessly pretend to pad the longer one for type matching if a_len < b_len { (a.mask_words(0).chain(Repeat::new(0u).enumerate().take(b_len).skip(a_len)), b.mask_words(0).chain(Repeat::new(0u).enumerate().take(0).skip(0))) } else { (a.mask_words(0).chain(Repeat::new(0u).enumerate().take(0).skip(0)), b.mask_words(0).chain(Repeat::new(0u).enumerate().take(a_len).skip(b_len))) } } static TRUE: bool = true; static FALSE: bool = false; /// The bitvector type. /// /// # Example /// /// ```rust /// use collections::Bitv; /// /// let mut bv = Bitv::with_capacity(10, false); /// /// // insert all primes less than 10 /// bv.set(2, true); /// bv.set(3, true); /// bv.set(5, true); /// bv.set(7, true); /// println!("{}", bv.to_string()); /// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count()); /// /// // flip all values in bitvector, producing non-primes less than 10 /// bv.negate(); /// println!("{}", bv.to_string()); /// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count()); /// /// // reset bitvector to empty /// bv.clear(); /// println!("{}", bv.to_string()); /// println!("total bits set to true: {}", bv.iter().filter(|x| *x).count()); /// ``` pub struct Bitv { /// Internal representation of the bit vector storage: Vec<uint>, /// The number of valid bits in the internal representation nbits: uint } impl Index<uint,bool> for Bitv { #[inline] fn index<'a>(&'a self, i: &uint) -> &'a bool { if self.get(*i) { &TRUE } else { &FALSE } } } struct MaskWords<'a> { iter: slice::Items<'a, uint>, next_word: Option<&'a uint>, last_word_mask: uint, offset: uint } impl<'a> Iterator<(uint, uint)> for MaskWords<'a> { /// Returns (offset, word) #[inline] fn next<'a>(&'a mut self) -> Option<(uint, uint)> { let ret = self.next_word; match ret { Some(&w) => { self.next_word = self.iter.next(); self.offset += 1; // The last word may need to be masked if self.next_word.is_none() { Some((self.offset - 1, w & self.last_word_mask)) } else { Some((self.offset - 1, w)) } }, None => None } } } impl Bitv { #[inline] fn process(&mut self, other: &Bitv, op: |uint, uint| -> uint) -> bool { let len = other.storage.len(); assert_eq!(self.storage.len(), len); let mut changed = false; // Notice: `a` is *not* masked here, which is fine as long as // `op` is a bitwise operation, since any bits that should've // been masked were fine to change anyway. `b` is masked to // make sure its unmasked bits do not cause damage. for (a, (_, b)) in self.storage.iter_mut() .zip(other.mask_words(0)) { let w = op(*a, b); if *a != w { changed = true; *a = w; } } changed } #[inline] fn mask_words<'a>(&'a self, mut start: uint) -> MaskWords<'a> { if start > self.storage.len() { start = self.storage.len(); } let mut iter = self.storage.slice_from(start).iter(); MaskWords { next_word: iter.next(), iter: iter, last_word_mask: { let rem = self.nbits % uint::BITS; if rem > 0 { (1 << rem) - 1 } else { !0 } }, offset: start } } /// Creates an empty `Bitv`. /// /// # Example /// /// ``` /// use std::collections::Bitv; /// let mut bv = Bitv::new(); /// ``` pub fn new() -> Bitv { Bitv { storage: Vec::new(), nbits: 0 } } /// Creates a `Bitv` that holds `nbits` elements, setting each element /// to `init`. /// /// # Example /// /// ``` /// use std::collections::Bitv; /// /// let mut bv = Bitv::with_capacity(10u, false); /// assert_eq!(bv.len(), 10u); /// for x in bv.iter() { /// assert_eq!(x, false); /// } /// ``` pub fn with_capacity(nbits: uint, init: bool) -> Bitv { Bitv { storage: Vec::from_elem((nbits + uint::BITS - 1) / uint::BITS, if init { !0u } else { 0u }), nbits: nbits } } /// Retrieves the value at index `i`. /// /// # Failure /// /// Fails if `i` is out of bounds. /// /// # Example /// /// ``` /// use std::collections::bitv; /// /// let bv = bitv::from_bytes([0b01100000]); /// assert_eq!(bv.get(0), false); /// assert_eq!(bv.get(1), true); /// /// // Can also use array indexing /// assert_eq!(bv[1], true); /// ``` #[inline] pub fn get(&self, i: uint) -> bool { assert!(i < self.nbits); let w = i / uint::BITS; let b = i % uint::BITS; let x = self.storage[w] & (1 << b); x != 0 } /// Sets the value of a bit at a index `i`. /// /// # Failure /// /// Fails if `i` is out of bounds. /// /// # Example /// /// ``` /// use std::collections::Bitv; /// /// let mut bv = Bitv::with_capacity(5, false); /// bv.set(3, true); /// assert_eq!(bv[3], true); /// ``` #[inline] pub fn set(&mut self, i: uint, x: bool) { assert!(i < self.nbits); let w = i / uint::BITS; let b = i % uint::BITS; let flag = 1 << b; *self.storage.get_mut(w) = if x { self.storage[w] | flag } else { self.storage[w] & !flag }; } /// Sets all bits to 1. /// /// # Example /// /// ``` /// use std::collections::bitv; /// /// let before = 0b01100000; /// let after = 0b11111111; /// /// let mut bv = bitv::from_bytes([before]); /// bv.set_all(); /// assert_eq!(bv, bitv::from_bytes([after])); /// ``` #[inline] pub fn set_all(&mut self) { for w in self.storage.iter_mut() { *w = !0u; } } /// Flips all bits. /// /// # Example /// /// ``` /// use std::collections::bitv; /// /// let before = 0b01100000; /// let after = 0b10011111; /// /// let mut bv = bitv::from_bytes([before]); /// bv.negate(); /// assert_eq!(bv, bitv::from_bytes([after])); /// ``` #[inline] pub fn negate(&mut self) { for w in self.storage.iter_mut() { *w = !*w; } } /// Calculates the union of two bitvectors. This acts like the bitwise `or` /// function. /// /// Sets `self` to the union of `self` and `other`. Both bitvectors must be /// the same length. Returns `true` if `self` changed. /// /// # Failure /// /// Fails if the bitvectors are of different lengths. /// /// # Example /// /// ``` /// use std::collections::bitv; /// /// let a = 0b01100100; /// let b = 0b01011010; /// let res = 0b01111110; /// /// let mut a = bitv::from_bytes([a]); /// let b = bitv::from_bytes([b]); /// /// assert!(a.union(&b)); /// assert_eq!(a, bitv::from_bytes([res])); /// ``` #[inline] pub fn union(&mut self, other: &Bitv) -> bool { self.process(other, |w1, w2| w1 | w2) } /// Calculates the intersection of two bitvectors. This acts like the /// bitwise `and` function. /// /// Sets `self` to the intersection of `self` and `other`. Both bitvectors /// must be the same length. Returns `true` if `self` changed. /// /// # Failure /// /// Fails if the bitvectors are of different lengths. /// /// # Example /// /// ``` /// use std::collections::bitv; /// /// let a = 0b01100100; /// let b = 0b01011010; /// let res = 0b01000000; /// /// let mut a = bitv::from_bytes([a]); /// let b = bitv::from_bytes([b]); /// /// assert!(a.intersect(&b)); /// assert_eq!(a, bitv::from_bytes([res])); /// ``` #[inline] pub fn intersect(&mut self, other: &Bitv) -> bool { self.process(other, |w1, w2| w1 & w2) } /// Calculates the difference between two bitvectors. /// /// Sets each element of `self` to the value of that element minus the /// element of `other` at the same index. Both bitvectors must be the same /// length. Returns `true` if `self` changed. /// /// # Failure /// /// Fails if the bitvectors are of different length. /// /// # Example /// /// ``` /// use std::collections::bitv; /// /// let a = 0b01100100; /// let b = 0b01011010; /// let a_b = 0b00100100; // a - b /// let b_a = 0b00011010; // b - a /// /// let mut bva = bitv::from_bytes([a]); /// let bvb = bitv::from_bytes([b]); /// /// assert!(bva.difference(&bvb)); /// assert_eq!(bva, bitv::from_bytes([a_b])); /// /// let bva = bitv::from_bytes([a]); /// let mut bvb = bitv::from_bytes([b]); /// /// assert!(bvb.difference(&bva)); /// assert_eq!(bvb, bitv::from_bytes([b_a])); /// ``` #[inline] pub fn difference(&mut self, other: &Bitv) -> bool { self.process(other, |w1, w2| w1 & !w2) } /// Returns `true` if all bits are 1. /// /// # Example /// /// ``` /// use std::collections::Bitv; /// /// let mut bv = Bitv::with_capacity(5, true); /// assert_eq!(bv.all(), true); /// /// bv.set(1, false); /// assert_eq!(bv.all(), false); /// ``` #[inline] pub fn all(&self) -> bool { let mut last_word = !0u; // Check that every word but the last is all-ones... self.mask_words(0).all(|(_, elem)| { let tmp = last_word; last_word = elem; tmp == !0u }) && // ...and that the last word is ones as far as it needs to be (last_word == ((1 << self.nbits % uint::BITS) - 1) || last_word == !0u) } /// Returns an iterator over the elements of the vector in order. /// /// # Example /// /// ``` /// use std::collections::bitv; /// /// let bv = bitv::from_bytes([0b01110100, 0b10010010]); /// assert_eq!(bv.iter().filter(|x| *x).count(), 7); /// ``` #[inline] pub fn iter<'a>(&'a self) -> Bits<'a> { Bits {bitv: self, next_idx: 0, end_idx: self.nbits} } /// Returns `true` if all bits are 0. /// /// # Example /// /// ``` /// use std::collections::Bitv; /// /// let mut bv = Bitv::with_capacity(10, false); /// assert_eq!(bv.none(), true); /// /// bv.set(3, true); /// assert_eq!(bv.none(), false); /// ``` pub fn none(&self) -> bool { self.mask_words(0).all(|(_, w)| w == 0) } /// Returns `true` if any bit is 1. /// /// # Example /// /// ``` /// use std::collections::Bitv; /// /// let mut bv = Bitv::with_capacity(10, false); /// assert_eq!(bv.any(), false); /// /// bv.set(3, true); /// assert_eq!(bv.any(), true); /// ``` #[inline] pub fn any(&self) -> bool { !self.none() } /// Organises the bits into bytes, such that the first bit in the /// `Bitv` becomes the high-order bit of the first byte. If the /// size of the `Bitv` is not a multiple of eight then trailing bits /// will be filled-in with `false`. /// /// # Example /// /// ``` /// use std::collections::Bitv; /// /// let mut bv = Bitv::with_capacity(3, true); /// bv.set(1, false); /// /// assert_eq!(bv.to_bytes(), vec!(0b10100000)); /// /// let mut bv = Bitv::with_capacity(9, false); /// bv.set(2, true); /// bv.set(8, true); /// /// assert_eq!(bv.to_bytes(), vec!(0b00100000, 0b10000000)); /// ``` pub fn to_bytes(&self) -> Vec<u8> { fn bit (bitv: &Bitv, byte: uint, bit: uint) -> u8 { let offset = byte * 8 + bit; if offset >= bitv.nbits { 0 } else { bitv.get(offset) as u8 << (7 - bit) } } let len = self.nbits/8 + if self.nbits % 8 == 0 { 0 } else { 1 }; Vec::from_fn(len, |i| bit(self, i, 0) | bit(self, i, 1) | bit(self, i, 2) | bit(self, i, 3) | bit(self, i, 4) | bit(self, i, 5) | bit(self, i, 6) | bit(self, i, 7) ) } /// Transforms `self` into a `Vec<bool>` by turning each bit into a `bool`. /// /// # Example /// /// ``` /// use std::collections::bitv; /// /// let bv = bitv::from_bytes([0b10100000]); /// assert_eq!(bv.to_bools(), vec!(true, false, true, false, /// false, false, false, false)); /// ``` pub fn to_bools(&self) -> Vec<bool> { Vec::from_fn(self.nbits, |i| self.get(i)) } /// Compares a `Bitv` to a slice of `bool`s. /// Both the `Bitv` and slice must have the same length. /// /// # Failure /// /// Fails if the the `Bitv` and slice are of different length. /// /// # Example /// /// ``` /// use std::collections::bitv; /// /// let bv = bitv::from_bytes([0b10100000]); /// /// assert!(bv.eq_vec([true, false, true, false, /// false, false, false, false])); /// ``` pub fn eq_vec(&self, v: &[bool]) -> bool { assert_eq!(self.nbits, v.len()); let mut i = 0; while i < self.nbits { if self.get(i) != v[i] { return false; } i = i + 1; } true } /// Shortens a `Bitv`, dropping excess elements. /// /// If `len` is greater than the vector's current length, this has no /// effect. /// /// # Example /// /// ``` /// use std::collections::bitv; /// /// let mut bv = bitv::from_bytes([0b01001011]); /// bv.truncate(2); /// assert!(bv.eq_vec([false, true])); /// ``` pub fn truncate(&mut self, len: uint) { if len < self.len() { self.nbits = len; let word_len = (len + uint::BITS - 1) / uint::BITS; self.storage.truncate(word_len); if len % uint::BITS > 0 { let mask = (1 << len % uint::BITS) - 1; *self.storage.get_mut(word_len - 1) &= mask; } } } /// Grows the vector to be able to store `size` bits without resizing. /// /// # Example /// /// ``` /// use std::collections::Bitv; /// /// let mut bv = Bitv::with_capacity(3, false); /// bv.reserve(10); /// assert_eq!(bv.len(), 3); /// assert!(bv.capacity() >= 10); /// ``` pub fn reserve(&mut self, size: uint) { let old_size = self.storage.len(); let size = (size + uint::BITS - 1) / uint::BITS; if old_size < size { self.storage.grow(size - old_size, &0); } } /// Returns the capacity in bits for this bit vector. Inserting any /// element less than this amount will not trigger a resizing. /// /// # Example /// /// ``` /// use std::collections::Bitv; /// /// let mut bv = Bitv::new(); /// bv.reserve(10); /// assert!(bv.capacity() >= 10); /// ``` #[inline] pub fn capacity(&self) -> uint { self.storage.len() * uint::BITS } /// Grows the `Bitv` in-place, adding `n` copies of `value` to the `Bitv`. /// /// # Example /// /// ``` /// use std::collections::bitv; /// /// let mut bv = bitv::from_bytes([0b01001011]); /// bv.grow(2, true); /// assert_eq!(bv.len(), 10); /// assert_eq!(bv.to_bytes(), vec!(0b01001011, 0b11000000)); /// ``` pub fn grow(&mut self, n: uint, value: bool) { let new_nbits = self.nbits + n; let new_nwords = (new_nbits + uint::BITS - 1) / uint::BITS; let full_value = if value { !0 } else { 0 }; // Correct the old tail word let old_last_word = (self.nbits + uint::BITS - 1) / uint::BITS - 1; if self.nbits % uint::BITS > 0 { let overhang = self.nbits % uint::BITS; // # of already-used bits let mask = !((1 << overhang) - 1); // e.g. 5 unused bits => 111110....0 if value { *self.storage.get_mut(old_last_word) |= mask; } else { *self.storage.get_mut(old_last_word) &= !mask; } } // Fill in words after the old tail word let stop_idx = cmp::min(self.storage.len(), new_nwords); for idx in range(old_last_word + 1, stop_idx) { *self.storage.get_mut(idx) = full_value; } // Allocate new words, if needed if new_nwords > self.storage.len() { let to_add = new_nwords - self.storage.len(); self.storage.grow(to_add, &full_value); } // Adjust internal bit count self.nbits = new_nbits; } /// Shortens by one element and returns the removed element. /// /// # Failure /// /// Assert if empty. /// /// # Example /// /// ``` /// use std::collections::bitv; /// /// let mut bv = bitv::from_bytes([0b01001001]); /// assert_eq!(bv.pop(), true); /// assert_eq!(bv.pop(), false); /// assert_eq!(bv.len(), 6); /// assert_eq!(bv.to_bytes(), vec!(0b01001000)); /// ``` pub fn pop(&mut self) -> bool { let ret = self.get(self.nbits - 1); // If we are unusing a whole word, make sure it is zeroed out if self.nbits % uint::BITS == 1 { *self.storage.get_mut(self.nbits / uint::BITS) = 0; } self.nbits -= 1; ret } /// Pushes a `bool` onto the end. /// /// # Example /// /// ``` /// use std::collections::Bitv; /// /// let mut bv = Bitv::new(); /// bv.push(true); /// bv.push(false); /// assert!(bv.eq_vec([true, false])); /// ``` pub fn push(&mut self, elem: bool) { let insert_pos = self.nbits; self.nbits += 1; if self.storage.len() * uint::BITS < self.nbits { self.storage.push(0); } self.set(insert_pos, elem); } } /// Transforms a byte-vector into a `Bitv`. Each byte becomes eight bits, /// with the most significant bits of each byte coming first. Each /// bit becomes `true` if equal to 1 or `false` if equal to 0. /// /// # Example /// /// ``` /// use std::collections::bitv; /// /// let bv = bitv::from_bytes([0b10100000, 0b00010010]); /// assert!(bv.eq_vec([true, false, true, false, /// false, false, false, false, /// false, false, false, true, /// false, false, true, false])); /// ``` pub fn from_bytes(bytes: &[u8]) -> Bitv { from_fn(bytes.len() * 8, |i| { let b = bytes[i / 8] as uint; let offset = i % 8; b >> (7 - offset) & 1 == 1 }) } /// Creates a `Bitv` of the specified length where the value at each /// index is `f(index)`. /// /// # Example /// /// ``` /// use std::collections::bitv::from_fn; /// /// let bv = from_fn(5, |i| { i % 2 == 0 }); /// assert!(bv.eq_vec([true, false, true, false, true])); /// ``` pub fn from_fn(len: uint, f: |index: uint| -> bool) -> Bitv { let mut bitv = Bitv::with_capacity(len, false); for i in range(0u, len) { bitv.set(i, f(i)); } bitv } impl Default for Bitv { #[inline] fn default() -> Bitv { Bitv::new() } } impl Collection for Bitv { #[inline] fn len(&self) -> uint { self.nbits } } impl Mutable for Bitv { #[inline] fn clear(&mut self) { for w in self.storage.iter_mut() { *w = 0u; } } } impl FromIterator<bool> for Bitv { fn from_iter<I:Iterator<bool>>(iterator: I) -> Bitv { let mut ret = Bitv::new(); ret.extend(iterator); ret } } impl Extendable<bool> for Bitv { #[inline] fn extend<I: Iterator<bool>>(&mut self, mut iterator: I) { let (min, _) = iterator.size_hint(); let nbits = self.nbits; self.reserve(nbits + min); for element in iterator { self.push(element) } } } impl Clone for Bitv { #[inline] fn clone(&self) -> Bitv { Bitv { storage: self.storage.clone(), nbits: self.nbits } } #[inline] fn clone_from(&mut self, source: &Bitv) { self.nbits = source.nbits; self.storage.reserve(source.storage.len()); for (i, w) in self.storage.iter_mut().enumerate() { *w = source.storage[i]; } } } impl PartialOrd for Bitv { #[inline] fn partial_cmp(&self, other: &Bitv) -> Option<Ordering> { iter::order::partial_cmp(self.iter(), other.iter()) } } impl Ord for Bitv { #[inline] fn cmp(&self, other: &Bitv) -> Ordering { iter::order::cmp(self.iter(), other.iter()) } } impl fmt::Show for Bitv { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { for bit in self.iter() { try!(write!(fmt, "{}", if bit { 1u } else { 0u })); } Ok(()) } } impl<S: hash::Writer> hash::Hash<S> for Bitv { fn hash(&self, state: &mut S) { self.nbits.hash(state); for (_, elem) in self.mask_words(0) { elem.hash(state); } } } impl cmp::PartialEq for Bitv { #[inline] fn eq(&self, other: &Bitv) -> bool { if self.nbits != other.nbits { return false; } self.mask_words(0).zip(other.mask_words(0)).all(|((_, w1), (_, w2))| w1 == w2) } } impl cmp::Eq for Bitv {} /// An iterator for `Bitv`. pub struct Bits<'a> { bitv: &'a Bitv, next_idx: uint, end_idx: uint, } impl<'a> Iterator<bool> for Bits<'a> { #[inline] fn next(&mut self) -> Option<bool> { if self.next_idx != self.end_idx { let idx = self.next_idx; self.next_idx += 1; Some(self.bitv.get(idx)) } else { None } } fn size_hint(&self) -> (uint, Option<uint>) { let rem = self.end_idx - self.next_idx; (rem, Some(rem)) } } impl<'a> DoubleEndedIterator<bool> for Bits<'a> { #[inline] fn next_back(&mut self) -> Option<bool> { if self.next_idx != self.end_idx { self.end_idx -= 1; Some(self.bitv.get(self.end_idx)) } else { None } } } impl<'a> ExactSize<bool> for Bits<'a> {} impl<'a> RandomAccessIterator<bool> for Bits<'a> { #[inline] fn indexable(&self) -> uint { self.end_idx - self.next_idx } #[inline] fn idx(&mut self, index: uint) -> Option<bool> { if index >= self.indexable() { None } else { Some(self.bitv.get(index)) } } } /// An implementation of a set using a bit vector as an underlying /// representation for holding unsigned numerical elements. /// /// It should also be noted that the amount of storage necessary for holding a /// set of objects is proportional to the maximum of the objects when viewed /// as a `uint`. /// /// # Example /// /// ``` /// use std::collections::{BitvSet, Bitv}; /// use std::collections::bitv; /// /// // It's a regular set /// let mut s = BitvSet::new(); /// s.insert(0); /// s.insert(3); /// s.insert(7); /// /// s.remove(&7); /// /// if !s.contains(&7) { /// println!("There is no 7"); /// } /// /// // Can initialize from a `Bitv` /// let other = BitvSet::from_bitv(bitv::from_bytes([0b11010000])); /// /// s.union_with(&other); /// /// // Print 0, 1, 3 in some order /// for x in s.iter() { /// println!("{}", x); /// } /// /// // Can convert back to a `Bitv` /// let bv: Bitv = s.unwrap(); /// assert!(bv.eq_vec([true, true, false, true, /// false, false, false, false])); /// ``` #[deriving(Clone)] pub struct BitvSet(Bitv); impl Default for BitvSet { #[inline] fn default() -> BitvSet { BitvSet::new() } } impl FromIterator<bool> for BitvSet { fn from_iter<I:Iterator<bool>>(iterator: I) -> BitvSet { let mut ret = BitvSet::new(); ret.extend(iterator); ret } } impl Extendable<bool> for BitvSet { #[inline] fn extend<I: Iterator<bool>>(&mut self, iterator: I) { self.get_mut_ref().extend(iterator); } } impl PartialOrd for BitvSet { #[inline] fn partial_cmp(&self, other: &BitvSet) -> Option<Ordering> { let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref()); iter::order::partial_cmp(a_iter, b_iter) } } impl Ord for BitvSet { #[inline] fn cmp(&self, other: &BitvSet) -> Ordering { let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref()); iter::order::cmp(a_iter, b_iter) } } impl cmp::PartialEq for BitvSet { #[inline] fn eq(&self, other: &BitvSet) -> bool { let (a_iter, b_iter) = match_words(self.get_ref(), other.get_ref()); iter::order::eq(a_iter, b_iter) } } impl cmp::Eq for BitvSet {} impl BitvSet { /// Creates a new bit vector set with initially no contents. /// /// # Example /// /// ``` /// use std::collections::BitvSet; /// let mut s = BitvSet::new(); /// ``` #[inline] pub fn new() -> BitvSet { BitvSet(Bitv::new()) } /// Creates a new bit vector set with initially no contents, able to /// hold `nbits` elements without resizing. /// /// # Example /// /// ``` /// use std::collections::BitvSet; /// let mut s = BitvSet::with_capacity(100); /// assert!(s.capacity() >= 100); /// ``` #[inline] pub fn with_capacity(nbits: uint) -> BitvSet { BitvSet(Bitv::with_capacity(nbits, false)) } /// Creates a new bit vector set from the given bit vector. /// /// # Example /// /// ``` /// use std::collections::{bitv, BitvSet}; /// /// let bv = bitv::from_bytes([0b01100000]); /// let s = BitvSet::from_bitv(bv); /// /// // Print 1, 2 in arbitrary order /// for x in s.iter() { /// println!("{}", x); /// } /// ``` #[inline] pub fn from_bitv(bitv: Bitv) -> BitvSet { BitvSet(bitv) } /// Returns the capacity in bits for this bit vector. Inserting any /// element less than this amount will not trigger a resizing. /// /// # Example /// /// ``` /// use std::collections::BitvSet; /// /// let mut s = BitvSet::with_capacity(100); /// assert!(s.capacity() >= 100); /// ``` #[inline] pub fn capacity(&self) -> uint { let &BitvSet(ref bitv) = self; bitv.capacity() } /// Grows the underlying vector to be able to store `size` bits. /// /// # Example /// /// ``` /// use std::collections::BitvSet; /// /// let mut s = BitvSet::new(); /// s.reserve(10); /// assert!(s.capacity() >= 10); /// ``` pub fn reserve(&mut self, size: uint) { let &BitvSet(ref mut bitv) = self; bitv.reserve(size) } /// Consumes this set to return the underlying bit vector. /// /// # Example /// /// ``` /// use std::collections::BitvSet; /// /// let mut s = BitvSet::new(); /// s.insert(0); /// s.insert(3); /// /// let bv = s.unwrap(); /// assert!(bv.eq_vec([true, false, false, true])); /// ``` #[inline] pub fn unwrap(self) -> Bitv { let BitvSet(bitv) = self; bitv } /// Returns a reference to the underlying bit vector. /// /// # Example /// /// ``` /// use std::collections::BitvSet; /// /// let mut s = BitvSet::new(); /// s.insert(0); /// /// let bv = s.get_ref(); /// assert_eq!(bv[0], true); /// ``` #[inline] pub fn get_ref<'a>(&'a self) -> &'a Bitv { let &BitvSet(ref bitv) = self; bitv } /// Returns a mutable reference to the underlying bit vector. /// /// # Example /// /// ``` /// use std::collections::BitvSet; /// /// let mut s = BitvSet::new(); /// s.insert(0); /// assert_eq!(s.contains(&0), true); /// { /// // Will free the set during bv's lifetime /// let bv = s.get_mut_ref(); /// bv.set(0, false); /// } /// assert_eq!(s.contains(&0), false); /// ``` #[inline] pub fn get_mut_ref<'a>(&'a mut self) -> &'a mut Bitv { let &BitvSet(ref mut bitv) = self; bitv } #[inline] fn other_op(&mut self, other: &BitvSet, f: |uint, uint| -> uint) { // Unwrap Bitvs let &BitvSet(ref mut self_bitv) = self; let &BitvSet(ref other_bitv) = other; // Expand the vector if necessary self_bitv.reserve(other_bitv.capacity()); // virtually pad other with 0's for equal lengths let mut other_words = { let (_, result) = match_words(self_bitv, other_bitv); result }; // Apply values found in other for (i, w) in other_words { let old = self_bitv.storage[i]; let new = f(old, w); *self_bitv.storage.get_mut(i) = new; } } /// Truncates the underlying vector to the least length required. /// /// # Example /// /// ``` /// use std::collections::BitvSet; /// /// let mut s = BitvSet::new(); /// s.insert(32183231); /// s.remove(&32183231); /// /// // Internal storage will probably be bigger than necessary /// println!("old capacity: {}", s.capacity()); /// /// // Now should be smaller /// s.shrink_to_fit(); /// println!("new capacity: {}", s.capacity()); /// ``` #[inline] pub fn shrink_to_fit(&mut self) { let &BitvSet(ref mut bitv) = self; // Obtain original length let old_len = bitv.storage.len(); // Obtain coarse trailing zero length let n = bitv.storage.iter().rev().take_while(|&&n| n == 0).count(); // Truncate let trunc_len = cmp::max(old_len - n, 1); bitv.storage.truncate(trunc_len); bitv.nbits = trunc_len * uint::BITS; } /// Iterator over each uint stored in the `BitvSet`. /// /// # Example /// /// ``` /// use std::collections::BitvSet; /// use std::collections::bitv; /// /// let s = BitvSet::from_bitv(bitv::from_bytes([0b01001010])); /// /// // Print 1, 4, 6 in arbitrary order /// for x in s.iter() { /// println!("{}", x); /// } /// ``` #[inline] pub fn iter<'a>(&'a self) -> BitPositions<'a> { BitPositions {set: self, next_idx: 0} } /// Iterator over each uint stored in `self` union `other`. /// See [union_with](#method.union_with) for an efficient in-place version. /// /// # Example /// /// ``` /// use std::collections::BitvSet; /// use std::collections::bitv; /// /// let a = BitvSet::from_bitv(bitv::from_bytes([0b01101000])); /// let b = BitvSet::from_bitv(bitv::from_bytes([0b10100000])); /// /// // Print 0, 1, 2, 4 in arbitrary order /// for x in a.union(&b) { /// println!("{}", x); /// } /// ``` #[inline] pub fn union<'a>(&'a self, other: &'a BitvSet) -> TwoBitPositions<'a> { TwoBitPositions { set: self, other: other, merge: |w1, w2| w1 | w2, current_word: 0, next_idx: 0 } } /// Iterator over each uint stored in `self` intersect `other`. /// See [intersect_with](#method.intersect_with) for an efficient in-place version. /// /// # Example /// /// ``` /// use std::collections::BitvSet; /// use std::collections::bitv; /// /// let a = BitvSet::from_bitv(bitv::from_bytes([0b01101000])); /// let b = BitvSet::from_bitv(bitv::from_bytes([0b10100000])); /// /// // Print 2 /// for x in a.intersection(&b) { /// println!("{}", x); /// } /// ``` #[inline] pub fn intersection<'a>(&'a self, other: &'a BitvSet) -> Take<TwoBitPositions<'a>> { let min = cmp::min(self.capacity(), other.capacity()); TwoBitPositions { set: self, other: other, merge: |w1, w2| w1 & w2, current_word: 0, next_idx: 0 }.take(min) } /// Iterator over each uint stored in the `self` setminus `other`. /// See [difference_with](#method.difference_with) for an efficient in-place version. /// /// # Example /// /// ``` /// use std::collections::BitvSet; /// use std::collections::bitv; /// /// let a = BitvSet::from_bitv(bitv::from_bytes([0b01101000])); /// let b = BitvSet::from_bitv(bitv::from_bytes([0b10100000])); /// /// // Print 1, 4 in arbitrary order /// for x in a.difference(&b) { /// println!("{}", x); /// } /// /// // Note that difference is not symmetric, /// // and `b - a` means something else. /// // This prints 0 /// for x in b.difference(&a) { /// println!("{}", x); /// } /// ``` #[inline] pub fn difference<'a>(&'a self, other: &'a BitvSet) -> TwoBitPositions<'a> { TwoBitPositions { set: self, other: other, merge: |w1, w2| w1 & !w2, current_word: 0, next_idx: 0 } } /// Iterator over each uint stored in the symmetric difference of `self` and `other`. /// See [symmetric_difference_with](#method.symmetric_difference_with) for /// an efficient in-place version. /// /// # Example /// /// ``` /// use std::collections::BitvSet; /// use std::collections::bitv; /// /// let a = BitvSet::from_bitv(bitv::from_bytes([0b01101000])); /// let b = BitvSet::from_bitv(bitv::from_bytes([0b10100000])); /// /// // Print 0, 1, 4 in arbitrary order /// for x in a.symmetric_difference(&b) { /// println!("{}", x); /// } /// ``` #[inline] pub fn symmetric_difference<'a>(&'a self, other: &'a BitvSet) -> TwoBitPositions<'a> { TwoBitPositions { set: self, other: other, merge: |w1, w2| w1 ^ w2, current_word: 0, next_idx: 0 } } /// Unions in-place with the specified other bit vector. /// /// # Example /// /// ``` /// use std::collections::BitvSet; /// use std::collections::bitv; /// /// let a = 0b01101000; /// let b = 0b10100000; /// let res = 0b11101000; /// /// let mut a = BitvSet::from_bitv(bitv::from_bytes([a])); /// let b = BitvSet::from_bitv(bitv::from_bytes([b])); /// /// a.union_with(&b); /// assert_eq!(a.unwrap(), bitv::from_bytes([res])); /// ``` #[inline] pub fn union_with(&mut self, other: &BitvSet) { self.other_op(other, |w1, w2| w1 | w2); } /// Intersects in-place with the specified other bit vector. /// /// # Example /// /// ``` /// use std::collections::BitvSet; /// use std::collections::bitv; /// /// let a = 0b01101000; /// let b = 0b10100000; /// let res = 0b00100000; /// /// let mut a = BitvSet::from_bitv(bitv::from_bytes([a])); /// let b = BitvSet::from_bitv(bitv::from_bytes([b])); /// /// a.intersect_with(&b); /// assert_eq!(a.unwrap(), bitv::from_bytes([res])); /// ``` #[inline] pub fn intersect_with(&mut self, other: &BitvSet) { self.other_op(other, |w1, w2| w1 & w2); } /// Makes this bit vector the difference with the specified other bit vector /// in-place. /// /// # Example /// /// ``` /// use std::collections::BitvSet; /// use std::collections::bitv; /// /// let a = 0b01101000; /// let b = 0b10100000; /// let a_b = 0b01001000; // a - b /// let b_a = 0b10000000; // b - a /// /// let mut bva = BitvSet::from_bitv(bitv::from_bytes([a])); /// let bvb = BitvSet::from_bitv(bitv::from_bytes([b])); /// /// bva.difference_with(&bvb); /// assert_eq!(bva.unwrap(), bitv::from_bytes([a_b])); /// /// let bva = BitvSet::from_bitv(bitv::from_bytes([a])); /// let mut bvb = BitvSet::from_bitv(bitv::from_bytes([b])); /// /// bvb.difference_with(&bva); /// assert_eq!(bvb.unwrap(), bitv::from_bytes([b_a])); /// ``` #[inline] pub fn difference_with(&mut self, other: &BitvSet) { self.other_op(other, |w1, w2| w1 & !w2); } /// Makes this bit vector the symmetric difference with the specified other /// bit vector in-place. /// /// # Example /// /// ``` /// use std::collections::BitvSet; /// use std::collections::bitv; /// /// let a = 0b01101000; /// let b = 0b10100000; /// let res = 0b11001000; /// /// let mut a = BitvSet::from_bitv(bitv::from_bytes([a])); /// let b = BitvSet::from_bitv(bitv::from_bytes([b])); /// /// a.symmetric_difference_with(&b); /// assert_eq!(a.unwrap(), bitv::from_bytes([res])); /// ``` #[inline] pub fn symmetric_difference_with(&mut self, other: &BitvSet) { self.other_op(other, |w1, w2| w1 ^ w2); } } impl fmt::Show for BitvSet { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { try!(write!(fmt, "{{")); let mut first = true; for n in self.iter() { if !first { try!(write!(fmt, ", ")); } try!(write!(fmt, "{}", n)); first = false; } write!(fmt, "}}") } } impl<S: hash::Writer> hash::Hash<S> for BitvSet { fn hash(&self, state: &mut S) { for pos in self.iter() { pos.hash(state); } } } impl Collection for BitvSet { #[inline] fn len(&self) -> uint { let &BitvSet(ref bitv) = self; bitv.storage.iter().fold(0, |acc, &n| acc + n.count_ones()) } } impl Mutable for BitvSet { #[inline] fn clear(&mut self) { let &BitvSet(ref mut bitv) = self; bitv.clear(); } } impl Set<uint> for BitvSet { #[inline] fn contains(&self, value: &uint) -> bool { let &BitvSet(ref bitv) = self; *value < bitv.nbits && bitv.get(*value) } #[inline] fn is_disjoint(&self, other: &BitvSet) -> bool { self.intersection(other).next().is_none() } #[inline] fn is_subset(&self, other: &BitvSet) -> bool { let &BitvSet(ref self_bitv) = self; let &BitvSet(ref other_bitv) = other; // Check that `self` intersect `other` is self self_bitv.mask_words(0).zip(other_bitv.mask_words(0)) .all(|((_, w1), (_, w2))| w1 & w2 == w1) && // Check that `self` setminus `other` is empty self_bitv.mask_words(other_bitv.storage.len()).all(|(_, w)| w == 0) } #[inline] fn is_superset(&self, other: &BitvSet) -> bool { other.is_subset(self) } } impl MutableSet<uint> for BitvSet { fn insert(&mut self, value: uint) -> bool { if self.contains(&value) { return false; } if value >= self.capacity() { let new_cap = cmp::max(value + 1, self.capacity() * 2); self.reserve(new_cap); } let &BitvSet(ref mut bitv) = self; if value >= bitv.nbits { // If we are increasing nbits, make sure we mask out any previously-unconsidered bits let old_rem = bitv.nbits % uint::BITS; if old_rem != 0 { let old_last_word = (bitv.nbits + uint::BITS - 1) / uint::BITS - 1; *bitv.storage.get_mut(old_last_word) &= (1 << old_rem) - 1; } bitv.nbits = value + 1; } bitv.set(value, true); return true; } fn remove(&mut self, value: &uint) -> bool { if !self.contains(value) { return false; } let &BitvSet(ref mut bitv) = self; bitv.set(*value, false); return true; } } /// An iterator for `BitvSet`. pub struct BitPositions<'a> { set: &'a BitvSet, next_idx: uint } /// An iterator combining two `BitvSet` iterators. pub struct TwoBitPositions<'a> { set: &'a BitvSet, other: &'a BitvSet, merge: |uint, uint|: 'a -> uint, current_word: uint, next_idx: uint } impl<'a> Iterator<uint> for BitPositions<'a> { fn next(&mut self) -> Option<uint> { while self.next_idx < self.set.capacity() { let idx = self.next_idx; self.next_idx += 1; if self.set.contains(&idx) { return Some(idx); } } return None; } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { (0, Some(self.set.capacity() - self.next_idx)) } } impl<'a> Iterator<uint> for TwoBitPositions<'a> { fn next(&mut self) -> Option<uint> { while self.next_idx < self.set.capacity() || self.next_idx < self.other.capacity() { let bit_idx = self.next_idx % uint::BITS; if bit_idx == 0 { let &BitvSet(ref s_bitv) = self.set; let &BitvSet(ref o_bitv) = self.other; // Merging the two words is a bit of an awkward dance since // one Bitv might be longer than the other let word_idx = self.next_idx / uint::BITS; let w1 = if word_idx < s_bitv.storage.len() { s_bitv.storage[word_idx] } else { 0 }; let w2 = if word_idx < o_bitv.storage.len() { o_bitv.storage[word_idx] } else { 0 }; self.current_word = (self.merge)(w1, w2); } self.next_idx += 1; if self.current_word & (1 << bit_idx) != 0 { return Some(self.next_idx - 1); } } return None; } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { let cap = cmp::max(self.set.capacity(), self.other.capacity()); (0, Some(cap - self.next_idx)) } } #[cfg(test)] mod tests { use std::prelude::*; use std::iter::range_step; use std::uint; use std::rand; use std::rand::Rng; use test::Bencher; use {Set, Mutable, MutableSet, MutableSeq}; use bitv::{Bitv, BitvSet, from_fn, from_bytes}; use bitv; use vec::Vec; static BENCH_BITS : uint = 1 << 14; #[test] fn test_to_str() { let zerolen = Bitv::new(); assert_eq!(zerolen.to_string().as_slice(), ""); let eightbits = Bitv::with_capacity(8u, false); assert_eq!(eightbits.to_string().as_slice(), "00000000") } #[test] fn test_0_elements() { let act = Bitv::new(); let exp = Vec::from_elem(0u, false); assert!(act.eq_vec(exp.as_slice())); } #[test] fn test_1_element() { let mut act = Bitv::with_capacity(1u, false); assert!(act.eq_vec([false])); act = Bitv::with_capacity(1u, true); assert!(act.eq_vec([true])); } #[test] fn test_2_elements() { let mut b = bitv::Bitv::with_capacity(2, false); b.set(0, true); b.set(1, false); assert_eq!(b.to_string().as_slice(), "10"); } #[test] fn test_10_elements() { let mut act; // all 0 act = Bitv::with_capacity(10u, false); assert!((act.eq_vec( [false, false, false, false, false, false, false, false, false, false]))); // all 1 act = Bitv::with_capacity(10u, true); assert!((act.eq_vec([true, true, true, true, true, true, true, true, true, true]))); // mixed act = Bitv::with_capacity(10u, false); act.set(0u, true); act.set(1u, true); act.set(2u, true); act.set(3u, true); act.set(4u, true); assert!((act.eq_vec([true, true, true, true, true, false, false, false, false, false]))); // mixed act = Bitv::with_capacity(10u, false); act.set(5u, true); act.set(6u, true); act.set(7u, true); act.set(8u, true); act.set(9u, true); assert!((act.eq_vec([false, false, false, false, false, true, true, true, true, true]))); // mixed act = Bitv::with_capacity(10u, false); act.set(0u, true); act.set(3u, true); act.set(6u, true); act.set(9u, true); assert!((act.eq_vec([true, false, false, true, false, false, true, false, false, true]))); } #[test] fn test_31_elements() { let mut act; // all 0 act = Bitv::with_capacity(31u, false); assert!(act.eq_vec( [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false])); // all 1 act = Bitv::with_capacity(31u, true); assert!(act.eq_vec( [true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true])); // mixed act = Bitv::with_capacity(31u, false); act.set(0u, true); act.set(1u, true); act.set(2u, true); act.set(3u, true); act.set(4u, true); act.set(5u, true); act.set(6u, true); act.set(7u, true); assert!(act.eq_vec( [true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false])); // mixed act = Bitv::with_capacity(31u, false); act.set(16u, true); act.set(17u, true); act.set(18u, true); act.set(19u, true); act.set(20u, true); act.set(21u, true); act.set(22u, true); act.set(23u, true); assert!(act.eq_vec( [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false])); // mixed act = Bitv::with_capacity(31u, false); act.set(24u, true); act.set(25u, true); act.set(26u, true); act.set(27u, true); act.set(28u, true); act.set(29u, true); act.set(30u, true); assert!(act.eq_vec( [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true])); // mixed act = Bitv::with_capacity(31u, false); act.set(3u, true); act.set(17u, true); act.set(30u, true); assert!(act.eq_vec( [false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, true])); } #[test] fn test_32_elements() { let mut act; // all 0 act = Bitv::with_capacity(32u, false); assert!(act.eq_vec( [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false])); // all 1 act = Bitv::with_capacity(32u, true); assert!(act.eq_vec( [true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true])); // mixed act = Bitv::with_capacity(32u, false); act.set(0u, true); act.set(1u, true); act.set(2u, true); act.set(3u, true); act.set(4u, true); act.set(5u, true); act.set(6u, true); act.set(7u, true); assert!(act.eq_vec( [true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false])); // mixed act = Bitv::with_capacity(32u, false); act.set(16u, true); act.set(17u, true); act.set(18u, true); act.set(19u, true); act.set(20u, true); act.set(21u, true); act.set(22u, true); act.set(23u, true); assert!(act.eq_vec( [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false])); // mixed act = Bitv::with_capacity(32u, false); act.set(24u, true); act.set(25u, true); act.set(26u, true); act.set(27u, true); act.set(28u, true); act.set(29u, true); act.set(30u, true); act.set(31u, true); assert!(act.eq_vec( [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true])); // mixed act = Bitv::with_capacity(32u, false); act.set(3u, true); act.set(17u, true); act.set(30u, true); act.set(31u, true); assert!(act.eq_vec( [false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, true, true])); } #[test] fn test_33_elements() { let mut act; // all 0 act = Bitv::with_capacity(33u, false); assert!(act.eq_vec( [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false])); // all 1 act = Bitv::with_capacity(33u, true); assert!(act.eq_vec( [true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true])); // mixed act = Bitv::with_capacity(33u, false); act.set(0u, true); act.set(1u, true); act.set(2u, true); act.set(3u, true); act.set(4u, true); act.set(5u, true); act.set(6u, true); act.set(7u, true); assert!(act.eq_vec( [true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false])); // mixed act = Bitv::with_capacity(33u, false); act.set(16u, true); act.set(17u, true); act.set(18u, true); act.set(19u, true); act.set(20u, true); act.set(21u, true); act.set(22u, true); act.set(23u, true); assert!(act.eq_vec( [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false])); // mixed act = Bitv::with_capacity(33u, false); act.set(24u, true); act.set(25u, true); act.set(26u, true); act.set(27u, true); act.set(28u, true); act.set(29u, true); act.set(30u, true); act.set(31u, true); assert!(act.eq_vec( [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, false])); // mixed act = Bitv::with_capacity(33u, false); act.set(3u, true); act.set(17u, true); act.set(30u, true); act.set(31u, true); act.set(32u, true); assert!(act.eq_vec( [false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true])); } #[test] fn test_equal_differing_sizes() { let v0 = Bitv::with_capacity(10u, false); let v1 = Bitv::with_capacity(11u, false); assert!(v0 != v1); } #[test] fn test_equal_greatly_differing_sizes() { let v0 = Bitv::with_capacity(10u, false); let v1 = Bitv::with_capacity(110u, false); assert!(v0 != v1); } #[test] fn test_equal_sneaky_small() { let mut a = bitv::Bitv::with_capacity(1, false); a.set(0, true); let mut b = bitv::Bitv::with_capacity(1, true); b.set(0, true); assert_eq!(a, b); } #[test] fn test_equal_sneaky_big() { let mut a = bitv::Bitv::with_capacity(100, false); for i in range(0u, 100) { a.set(i, true); } let mut b = bitv::Bitv::with_capacity(100, true); for i in range(0u, 100) { b.set(i, true); } assert_eq!(a, b); } #[test] fn test_from_bytes() { let bitv = from_bytes([0b10110110, 0b00000000, 0b11111111]); let str = format!("{}{}{}", "10110110", "00000000", "11111111"); assert_eq!(bitv.to_string().as_slice(), str.as_slice()); } #[test] fn test_to_bytes() { let mut bv = Bitv::with_capacity(3, true); bv.set(1, false); assert_eq!(bv.to_bytes(), vec!(0b10100000)); let mut bv = Bitv::with_capacity(9, false); bv.set(2, true); bv.set(8, true); assert_eq!(bv.to_bytes(), vec!(0b00100000, 0b10000000)); } #[test] fn test_from_bools() { let bools = vec![true, false, true, true]; let bitv: Bitv = bools.iter().map(|n| *n).collect(); assert_eq!(bitv.to_string().as_slice(), "1011"); } #[test] fn test_bitv_set_from_bools() { let bools = vec![true, false, true, true]; let a: BitvSet = bools.iter().map(|n| *n).collect(); let mut b = BitvSet::new(); b.insert(0); b.insert(2); b.insert(3); assert_eq!(a, b); } #[test] fn test_to_bools() { let bools = vec!(false, false, true, false, false, true, true, false); assert_eq!(from_bytes([0b00100110]).iter().collect::<Vec<bool>>(), bools); } #[test] fn test_bitv_iterator() { let bools = vec![true, false, true, true]; let bitv: Bitv = bools.iter().map(|n| *n).collect(); assert_eq!(bitv.iter().collect::<Vec<bool>>(), bools) let long = Vec::from_fn(10000, |i| i % 2 == 0); let bitv: Bitv = long.iter().map(|n| *n).collect(); assert_eq!(bitv.iter().collect::<Vec<bool>>(), long) } #[test] fn test_bitv_set_iterator() { let bools = [true, false, true, true]; let bitv: BitvSet = bools.iter().map(|n| *n).collect(); let idxs: Vec<uint> = bitv.iter().collect(); assert_eq!(idxs, vec!(0, 2, 3)); let long: BitvSet = range(0u, 10000).map(|n| n % 2 == 0).collect(); let real = range_step(0, 10000, 2).collect::<Vec<uint>>(); let idxs: Vec<uint> = long.iter().collect(); assert_eq!(idxs, real); } #[test] fn test_bitv_set_frombitv_init() { let bools = [true, false]; let lengths = [10, 64, 100]; for &b in bools.iter() { for &l in lengths.iter() { let bitset = BitvSet::from_bitv(Bitv::with_capacity(l, b)); assert_eq!(bitset.contains(&1u), b) assert_eq!(bitset.contains(&(l-1u)), b) assert!(!bitset.contains(&l)) } } } #[test] fn test_small_difference() { let mut b1 = Bitv::with_capacity(3, false); let mut b2 = Bitv::with_capacity(3, false); b1.set(0, true); b1.set(1, true); b2.set(1, true); b2.set(2, true); assert!(b1.difference(&b2)); assert!(b1.get(0)); assert!(!b1.get(1)); assert!(!b1.get(2)); } #[test] fn test_big_difference() { let mut b1 = Bitv::with_capacity(100, false); let mut b2 = Bitv::with_capacity(100, false); b1.set(0, true); b1.set(40, true); b2.set(40, true); b2.set(80, true); assert!(b1.difference(&b2)); assert!(b1.get(0)); assert!(!b1.get(40)); assert!(!b1.get(80)); } #[test] fn test_small_clear() { let mut b = Bitv::with_capacity(14, true); b.clear(); assert!(b.none()); } #[test] fn test_big_clear() { let mut b = Bitv::with_capacity(140, true); b.clear(); assert!(b.none()); } #[test] fn test_bitv_masking() { let b = Bitv::with_capacity(140, true); let mut bs = BitvSet::from_bitv(b); assert!(bs.contains(&139)); assert!(!bs.contains(&140)); assert!(bs.insert(150)); assert!(!bs.contains(&140)); assert!(!bs.contains(&149)); assert!(bs.contains(&150)); assert!(!bs.contains(&151)); } #[test] fn test_bitv_set_basic() { // calculate nbits with uint::BITS granularity fn calc_nbits(bits: uint) -> uint { uint::BITS * ((bits + uint::BITS - 1) / uint::BITS) } let mut b = BitvSet::new(); assert_eq!(b.capacity(), calc_nbits(0)); assert!(b.insert(3)); assert_eq!(b.capacity(), calc_nbits(3)); assert!(!b.insert(3)); assert!(b.contains(&3)); assert!(b.insert(4)); assert!(!b.insert(4)); assert!(b.contains(&3)); assert!(b.insert(400)); assert_eq!(b.capacity(), calc_nbits(400)); assert!(!b.insert(400)); assert!(b.contains(&400)); assert_eq!(b.len(), 3); } #[test] fn test_bitv_set_intersection() { let mut a = BitvSet::new(); let mut b = BitvSet::new(); assert!(a.insert(11)); assert!(a.insert(1)); assert!(a.insert(3)); assert!(a.insert(77)); assert!(a.insert(103)); assert!(a.insert(5)); assert!(b.insert(2)); assert!(b.insert(11)); assert!(b.insert(77)); assert!(b.insert(5)); assert!(b.insert(3)); let expected = [3, 5, 11, 77]; let actual = a.intersection(&b).collect::<Vec<uint>>(); assert_eq!(actual.as_slice(), expected.as_slice()); } #[test] fn test_bitv_set_difference() { let mut a = BitvSet::new(); let mut b = BitvSet::new(); assert!(a.insert(1)); assert!(a.insert(3)); assert!(a.insert(5)); assert!(a.insert(200)); assert!(a.insert(500)); assert!(b.insert(3)); assert!(b.insert(200)); let expected = [1, 5, 500]; let actual = a.difference(&b).collect::<Vec<uint>>(); assert_eq!(actual.as_slice(), expected.as_slice()); } #[test] fn test_bitv_set_symmetric_difference() { let mut a = BitvSet::new(); let mut b = BitvSet::new(); assert!(a.insert(1)); assert!(a.insert(3)); assert!(a.insert(5)); assert!(a.insert(9)); assert!(a.insert(11)); assert!(b.insert(3)); assert!(b.insert(9)); assert!(b.insert(14)); assert!(b.insert(220)); let expected = [1, 5, 11, 14, 220]; let actual = a.symmetric_difference(&b).collect::<Vec<uint>>(); assert_eq!(actual.as_slice(), expected.as_slice()); } #[test] fn test_bitv_set_union() { let mut a = BitvSet::new(); let mut b = BitvSet::new(); assert!(a.insert(1)); assert!(a.insert(3)); assert!(a.insert(5)); assert!(a.insert(9)); assert!(a.insert(11)); assert!(a.insert(160)); assert!(a.insert(19)); assert!(a.insert(24)); assert!(b.insert(1)); assert!(b.insert(5)); assert!(b.insert(9)); assert!(b.insert(13)); assert!(b.insert(19)); let expected = [1, 3, 5, 9, 11, 13, 19, 24, 160]; let actual = a.union(&b).collect::<Vec<uint>>(); assert_eq!(actual.as_slice(), expected.as_slice()); } #[test] fn test_bitv_set_subset() { let mut set1 = BitvSet::new(); let mut set2 = BitvSet::new(); assert!(set1.is_subset(&set2)); // {} {} set2.insert(100); assert!(set1.is_subset(&set2)); // {} { 1 } set2.insert(200); assert!(set1.is_subset(&set2)); // {} { 1, 2 } set1.insert(200); assert!(set1.is_subset(&set2)); // { 2 } { 1, 2 } set1.insert(300); assert!(!set1.is_subset(&set2)); // { 2, 3 } { 1, 2 } set2.insert(300); assert!(set1.is_subset(&set2)); // { 2, 3 } { 1, 2, 3 } set2.insert(400); assert!(set1.is_subset(&set2)); // { 2, 3 } { 1, 2, 3, 4 } set2.remove(&100); assert!(set1.is_subset(&set2)); // { 2, 3 } { 2, 3, 4 } set2.remove(&300); assert!(!set1.is_subset(&set2)); // { 2, 3 } { 2, 4 } set1.remove(&300); assert!(set1.is_subset(&set2)); // { 2 } { 2, 4 } } #[test] fn test_bitv_set_is_disjoint() { let a = BitvSet::from_bitv(from_bytes([0b10100010])); let b = BitvSet::from_bitv(from_bytes([0b01000000])); let c = BitvSet::new(); let d = BitvSet::from_bitv(from_bytes([0b00110000])); assert!(!a.is_disjoint(&d)); assert!(!d.is_disjoint(&a)); assert!(a.is_disjoint(&b)) assert!(a.is_disjoint(&c)) assert!(b.is_disjoint(&a)) assert!(b.is_disjoint(&c)) assert!(c.is_disjoint(&a)) assert!(c.is_disjoint(&b)) } #[test] fn test_bitv_set_intersect_with() { // Explicitly 0'ed bits let mut a = BitvSet::from_bitv(from_bytes([0b10100010])); let mut b = BitvSet::from_bitv(from_bytes([0b00000000])); let c = a.clone(); a.intersect_with(&b); b.intersect_with(&c); assert!(a.is_empty()); assert!(b.is_empty()); // Uninitialized bits should behave like 0's let mut a = BitvSet::from_bitv(from_bytes([0b10100010])); let mut b = BitvSet::new(); let c = a.clone(); a.intersect_with(&b); b.intersect_with(&c); assert!(a.is_empty()); assert!(b.is_empty()); // Standard let mut a = BitvSet::from_bitv(from_bytes([0b10100010])); let mut b = BitvSet::from_bitv(from_bytes([0b01100010])); let c = a.clone(); a.intersect_with(&b); b.intersect_with(&c); assert_eq!(a.len(), 2); assert_eq!(b.len(), 2); } #[test] fn test_bitv_set_eq() { let a = BitvSet::from_bitv(from_bytes([0b10100010])); let b = BitvSet::from_bitv(from_bytes([0b00000000])); let c = BitvSet::new(); assert!(a == a); assert!(a != b); assert!(a != c); assert!(b == b); assert!(b == c); assert!(c == c); } #[test] fn test_bitv_set_cmp() { let a = BitvSet::from_bitv(from_bytes([0b10100010])); let b = BitvSet::from_bitv(from_bytes([0b00000000])); let c = BitvSet::new(); assert_eq!(a.cmp(&b), Greater); assert_eq!(a.cmp(&c), Greater); assert_eq!(b.cmp(&a), Less); assert_eq!(b.cmp(&c), Equal); assert_eq!(c.cmp(&a), Less); assert_eq!(c.cmp(&b), Equal); } #[test] fn test_bitv_remove() { let mut a = BitvSet::new(); assert!(a.insert(1)); assert!(a.remove(&1)); assert!(a.insert(100)); assert!(a.remove(&100)); assert!(a.insert(1000)); assert!(a.remove(&1000)); a.shrink_to_fit(); assert_eq!(a.capacity(), uint::BITS); } #[test] fn test_bitv_lt() { let mut a = Bitv::with_capacity(5u, false); let mut b = Bitv::with_capacity(5u, false); assert!(!(a < b) && !(b < a)); b.set(2, true); assert!(a < b); a.set(3, true); assert!(a < b); a.set(2, true); assert!(!(a < b) && b < a); b.set(0, true); assert!(a < b); } #[test] fn test_ord() { let mut a = Bitv::with_capacity(5u, false); let mut b = Bitv::with_capacity(5u, false); assert!(a <= b && a >= b); a.set(1, true); assert!(a > b && a >= b); assert!(b < a && b <= a); b.set(1, true); b.set(2, true); assert!(b > a && b >= a); assert!(a < b && a <= b); } #[test] fn test_bitv_clone() { let mut a = BitvSet::new(); assert!(a.insert(1)); assert!(a.insert(100)); assert!(a.insert(1000)); let mut b = a.clone(); assert!(a == b); assert!(b.remove(&1)); assert!(a.contains(&1)); assert!(a.remove(&1000)); assert!(b.contains(&1000)); } #[test] fn test_small_bitv_tests() { let v = from_bytes([0]); assert!(!v.all()); assert!(!v.any()); assert!(v.none()); let v = from_bytes([0b00010100]); assert!(!v.all()); assert!(v.any()); assert!(!v.none()); let v = from_bytes([0xFF]); assert!(v.all()); assert!(v.any()); assert!(!v.none()); } #[test] fn test_big_bitv_tests() { let v = from_bytes([ // 88 bits 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); assert!(!v.all()); assert!(!v.any()); assert!(v.none()); let v = from_bytes([ // 88 bits 0, 0, 0b00010100, 0, 0, 0, 0, 0b00110100, 0, 0, 0]); assert!(!v.all()); assert!(v.any()); assert!(!v.none()); let v = from_bytes([ // 88 bits 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]); assert!(v.all()); assert!(v.any()); assert!(!v.none()); } #[test] fn test_bitv_push_pop() { let mut s = Bitv::with_capacity(5 * uint::BITS - 2, false); assert_eq!(s.len(), 5 * uint::BITS - 2); assert_eq!(s.get(5 * uint::BITS - 3), false); s.push(true); s.push(true); assert_eq!(s.get(5 * uint::BITS - 2), true); assert_eq!(s.get(5 * uint::BITS - 1), true); // Here the internal vector will need to be extended s.push(false); assert_eq!(s.get(5 * uint::BITS), false); s.push(false); assert_eq!(s.get(5 * uint::BITS + 1), false); assert_eq!(s.len(), 5 * uint::BITS + 2); // Pop it all off assert_eq!(s.pop(), false); assert_eq!(s.pop(), false); assert_eq!(s.pop(), true); assert_eq!(s.pop(), true); assert_eq!(s.len(), 5 * uint::BITS - 2); } #[test] fn test_bitv_truncate() { let mut s = Bitv::with_capacity(5 * uint::BITS, true); assert_eq!(s, Bitv::with_capacity(5 * uint::BITS, true)); assert_eq!(s.len(), 5 * uint::BITS); s.truncate(4 * uint::BITS); assert_eq!(s, Bitv::with_capacity(4 * uint::BITS, true)); assert_eq!(s.len(), 4 * uint::BITS); // Truncating to a size > s.len() should be a noop s.truncate(5 * uint::BITS); assert_eq!(s, Bitv::with_capacity(4 * uint::BITS, true)); assert_eq!(s.len(), 4 * uint::BITS); s.truncate(3 * uint::BITS - 10); assert_eq!(s, Bitv::with_capacity(3 * uint::BITS - 10, true)); assert_eq!(s.len(), 3 * uint::BITS - 10); s.truncate(0); assert_eq!(s, Bitv::with_capacity(0, true)); assert_eq!(s.len(), 0); } #[test] fn test_bitv_reserve() { let mut s = Bitv::with_capacity(5 * uint::BITS, true); // Check capacity assert_eq!(s.capacity(), 5 * uint::BITS); s.reserve(2 * uint::BITS); assert_eq!(s.capacity(), 5 * uint::BITS); s.reserve(7 * uint::BITS); assert_eq!(s.capacity(), 7 * uint::BITS); s.reserve(7 * uint::BITS); assert_eq!(s.capacity(), 7 * uint::BITS); s.reserve(7 * uint::BITS + 1); assert_eq!(s.capacity(), 8 * uint::BITS); // Check that length hasn't changed assert_eq!(s.len(), 5 * uint::BITS); s.push(true); s.push(false); s.push(true); assert_eq!(s.get(5 * uint::BITS - 1), true); assert_eq!(s.get(5 * uint::BITS - 0), true); assert_eq!(s.get(5 * uint::BITS + 1), false); assert_eq!(s.get(5 * uint::BITS + 2), true); } #[test] fn test_bitv_grow() { let mut bitv = from_bytes([0b10110110, 0b00000000, 0b10101010]); bitv.grow(32, true); assert_eq!(bitv, from_bytes([0b10110110, 0b00000000, 0b10101010, 0xFF, 0xFF, 0xFF, 0xFF])); bitv.grow(64, false); assert_eq!(bitv, from_bytes([0b10110110, 0b00000000, 0b10101010, 0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0, 0, 0, 0, 0])); bitv.grow(16, true); assert_eq!(bitv, from_bytes([0b10110110, 0b00000000, 0b10101010, 0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF])); } #[test] fn test_bitv_extend() { let mut bitv = from_bytes([0b10110110, 0b00000000, 0b11111111]); let ext = from_bytes([0b01001001, 0b10010010, 0b10111101]); bitv.extend(ext.iter()); assert_eq!(bitv, from_bytes([0b10110110, 0b00000000, 0b11111111, 0b01001001, 0b10010010, 0b10111101])); } #[test] fn test_bitv_set_show() { let mut s = BitvSet::new(); s.insert(1); s.insert(10); s.insert(50); s.insert(2); assert_eq!("{1, 2, 10, 50}".to_string(), s.to_string()); } fn rng() -> rand::IsaacRng { let seed: &[_] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]; rand::SeedableRng::from_seed(seed) } #[bench] fn bench_uint_small(b: &mut Bencher) { let mut r = rng(); let mut bitv = 0 as uint; b.iter(|| { for _ in range(0u, 100) { bitv |= 1 << ((r.next_u32() as uint) % uint::BITS); } &bitv }) } #[bench] fn bench_bitv_set_big_fixed(b: &mut Bencher) { let mut r = rng(); let mut bitv = Bitv::with_capacity(BENCH_BITS, false); b.iter(|| { for _ in range(0u, 100) { bitv.set((r.next_u32() as uint) % BENCH_BITS, true); } &bitv }) } #[bench] fn bench_bitv_set_big_variable(b: &mut Bencher) { let mut r = rng(); let mut bitv = Bitv::with_capacity(BENCH_BITS, false); b.iter(|| { for i in range(0u, 100) { bitv.set((r.next_u32() as uint) % BENCH_BITS, r.gen()); } &bitv }) } #[bench] fn bench_bitv_set_small(b: &mut Bencher) { let mut r = rng(); let mut bitv = Bitv::with_capacity(uint::BITS, false); b.iter(|| { for _ in range(0u, 100) { bitv.set((r.next_u32() as uint) % uint::BITS, true); } &bitv }) } #[bench] fn bench_bitvset_small(b: &mut Bencher) { let mut r = rng(); let mut bitv = BitvSet::new(); b.iter(|| { for _ in range(0u, 100) { bitv.insert((r.next_u32() as uint) % uint::BITS); } &bitv }) } #[bench] fn bench_bitvset_big(b: &mut Bencher) { let mut r = rng(); let mut bitv = BitvSet::new(); b.iter(|| { for _ in range(0u, 100) { bitv.insert((r.next_u32() as uint) % BENCH_BITS); } &bitv }) } #[bench] fn bench_bitv_big_union(b: &mut Bencher) { let mut b1 = Bitv::with_capacity(BENCH_BITS, false); let b2 = Bitv::with_capacity(BENCH_BITS, false); b.iter(|| { b1.union(&b2) }) } #[bench] fn bench_bitv_small_iter(b: &mut Bencher) { let bitv = Bitv::with_capacity(uint::BITS, false); b.iter(|| { let mut sum = 0; for _ in range(0u, 10) { for pres in bitv.iter() { sum += pres as uint; } } sum }) } #[bench] fn bench_bitv_big_iter(b: &mut Bencher) { let bitv = Bitv::with_capacity(BENCH_BITS, false); b.iter(|| { let mut sum = 0; for pres in bitv.iter() { sum += pres as uint; } sum }) } #[bench] fn bench_bitvset_iter(b: &mut Bencher) { let bitv = BitvSet::from_bitv(from_fn(BENCH_BITS, |idx| {idx % 3 == 0})); b.iter(|| { let mut sum = 0; for idx in bitv.iter() { sum += idx; } sum }) } }
29.081747
99
0.506597
28455a86926da63f565760ce9035358e3f334a77
86
#[path = "../../tracing/tests/support/mod.rs"] mod support; pub use self::support::*;
21.5
46
0.639535
56cd93d319d52be6e071779f86dfb8b18ca19fa9
2,926
use crate::model::{id::Id, messaging::MessagingMessage}; use crate::streaming::channel::NoOutgoing; use serde::{Deserialize, Serialize}; #[derive(Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase", tag = "type", content = "body")] pub enum MessagingIndexStreamEvent { Message(MessagingMessage), Read(Vec<Id<MessagingMessage>>), } #[derive(Serialize, Default, Debug, Clone)] pub struct Request {} impl misskey_core::streaming::ConnectChannelRequest for Request { type Incoming = MessagingIndexStreamEvent; type Outgoing = NoOutgoing; const NAME: &'static str = "messagingIndex"; } #[cfg(test)] mod tests { use super::{MessagingIndexStreamEvent, Request}; use crate::test::{websocket::TestClient, ClientExt}; use futures::{future, StreamExt}; #[tokio::test] async fn subscribe_unsubscribe() { let client = TestClient::new().await; let mut stream = client.user.channel(Request::default()).await.unwrap(); stream.disconnect().await.unwrap(); } #[tokio::test] async fn stream_message() { let client = TestClient::new().await; let user = client.user.me().await; let mut stream = client.user.channel(Request::default()).await.unwrap(); future::join( client .admin .test(crate::endpoint::messaging::messages::create::Request { text: Some("hi".to_string()), user_id: Some(user.id), group_id: None, file_id: None, }), async { loop { match stream.next().await.unwrap().unwrap() { MessagingIndexStreamEvent::Message(_) => break, _ => continue, } } }, ) .await; } #[tokio::test] async fn stream_read() { let client = TestClient::new().await; let user = client.user.me().await; let message = client .admin .test(crate::endpoint::messaging::messages::create::Request { text: Some("hi".to_string()), user_id: Some(user.id.clone()), group_id: None, file_id: None, }) .await; let mut stream = client.user.channel(Request::default()).await.unwrap(); future::join( client .user .test(crate::endpoint::messaging::messages::read::Request { message_id: message.id, }), async { loop { match stream.next().await.unwrap().unwrap() { MessagingIndexStreamEvent::Read(_) => break, _ => continue, } } }, ) .await; } }
30.164948
80
0.516405
f92850b0658269696ff84a51cc2df8d1252f2dee
46,299
// Copyright © 2019 The Rust Fuzz Project Developers. // // 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. //! The `Arbitrary` trait crate. //! //! This trait provides an [`Arbitrary`](./trait.Arbitrary.html) trait to //! produce well-typed, structured values, from raw, byte buffers. It is //! generally intended to be used with fuzzers like AFL or libFuzzer. See the //! [`Arbitrary`](./trait.Arbitrary.html) trait's documentation for details on //! automatically deriving, implementing, and/or using the trait. #![deny(bad_style)] #![deny(missing_docs)] #![deny(future_incompatible)] #![deny(nonstandard_style)] #![deny(rust_2018_compatibility)] #![deny(rust_2018_idioms)] #![deny(unused)] #[cfg(feature = "derive_arbitrary")] pub use derive_arbitrary::*; mod error; pub use error::*; pub mod unstructured; #[doc(inline)] pub use unstructured::Unstructured; pub mod size_hint; use core::cell::{Cell, RefCell, UnsafeCell}; use core::iter; use core::mem; use core::ops::{Range, RangeBounds, RangeFrom, RangeInclusive, RangeTo, RangeToInclusive}; use core::str; use core::time::Duration; use std::borrow::{Cow, ToOwned}; use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque}; use std::ffi::{CString, OsString}; use std::path::PathBuf; use std::rc::Rc; use std::sync::atomic::{AtomicBool, AtomicIsize, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; fn empty<T: 'static>() -> Box<dyn Iterator<Item = T>> { Box::new(iter::empty()) } fn once<T: 'static>(val: T) -> Box<dyn Iterator<Item = T>> { Box::new(iter::once(val)) } /// Generate arbitrary structured values from raw, unstructured data. /// /// The `Arbitrary` trait allows you to generate valid structured values, like /// `HashMap`s, or ASTs, or `MyTomlConfig`, or any other data structure from /// raw, unstructured bytes provided by a fuzzer. It also features built-in /// shrinking, so that if you find a test case that triggers a bug, you can find /// the smallest, most easiest-to-understand test case that still triggers that /// bug. /// /// # Deriving `Arbitrary` /// /// Automatically deriving the `Arbitrary` trait is the recommended way to /// implement `Arbitrary` for your types. /// /// Using the custom derive requires that you enable the `"derive"` cargo /// feature in your `Cargo.toml`: /// /// ```toml /// [dependencies] /// arbitrary = { version = "0.4", features = ["derive"] } /// ``` /// /// Then, you add the `#[derive(Arbitrary)]` annotation to your `struct` or /// `enum` type definition: /// /// ``` /// # #[cfg(feature = "derive")] mod foo { /// use arbitrary::Arbitrary; /// use std::collections::HashSet; /// /// #[derive(Arbitrary)] /// pub struct AddressBook { /// friends: HashSet<Friend>, /// } /// /// #[derive(Arbitrary, Hash, Eq, PartialEq)] /// pub enum Friend { /// Buddy { name: String }, /// Pal { age: usize }, /// } /// # } /// ``` /// /// Every member of the `struct` or `enum` must also implement `Arbitrary`. /// /// # Implementing `Arbitrary` By Hand /// /// Implementing `Arbitrary` mostly involves nested calls to other `Arbitrary` /// arbitrary implementations for each of your `struct` or `enum`'s members. But /// sometimes you need some amount of raw data, or you need to generate a /// variably-sized collection type, or you something of that sort. The /// [`Unstructured`][crate::Unstructured] type helps you with these tasks. /// /// ``` /// # #[cfg(feature = "derive")] mod foo { /// # pub struct MyCollection<T> { _t: std::marker::PhantomData<T> } /// # impl<T> MyCollection<T> { /// # pub fn new() -> Self { MyCollection { _t: std::marker::PhantomData } } /// # pub fn insert(&mut self, element: T) {} /// # } /// use arbitrary::{Arbitrary, Result, Unstructured}; /// /// impl<T> Arbitrary for MyCollection<T> /// where /// T: Arbitrary, /// { /// fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { /// // Get an iterator of arbitrary `T`s. /// let iter = u.arbitrary_iter::<T>()?; /// /// // And then create a collection! /// let mut my_collection = MyCollection::new(); /// for elem_result in iter { /// let elem = elem_result?; /// my_collection.insert(elem); /// } /// /// Ok(my_collection) /// } /// } /// # } /// ``` pub trait Arbitrary: Sized + 'static { /// Generate an arbitrary value of `Self` from the given unstructured data. /// /// Calling `Arbitrary::arbitrary` requires that you have some raw data, /// perhaps given to you by a fuzzer like AFL or libFuzzer. You wrap this /// raw data in an `Unstructured`, and then you can call `<MyType as /// Arbitrary>::arbitrary` to construct an arbitrary instance of `MyType` /// from that unstuctured data. /// /// Implementation may return an error if there is not enough data to /// construct a full instance of `Self`. This is generally OK: it is better /// to exit early and get the fuzzer to provide more input data, than it is /// to generate default values in place of the missing data, which would /// bias the distribution of generated values, and ultimately make fuzzing /// less efficient. /// /// ``` /// # #[cfg(feature = "derive")] fn foo() { /// use arbitrary::{Arbitrary, Unstructured}; /// /// #[derive(Arbitrary)] /// pub struct MyType { /// // ... /// } /// /// // Get the raw data from the fuzzer or wherever else. /// # let get_raw_data_from_fuzzer = || &[]; /// let raw_data: &[u8] = get_raw_data_from_fuzzer(); /// /// // Wrap that raw data in an `Unstructured`. /// let mut unstructured = Unstructured::new(raw_data); /// /// // Generate an arbitrary instance of `MyType` and do stuff with it. /// if let Ok(value) = MyType::arbitrary(&mut unstructured) { /// # let do_stuff = |_| {}; /// do_stuff(value); /// } /// # } /// ``` /// /// See also the documentation for [`Unstructured`][crate::Unstructured]. fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self>; /// Generate an arbitrary value of `Self` from the entirety of the given unstructured data. /// /// This is similar to Arbitrary::arbitrary, however it assumes that it is the /// last consumer of the given data, and is thus able to consume it all if it needs. /// See also the documentation for [`Unstructured`][crate::Unstructured]. fn arbitrary_take_rest(mut u: Unstructured<'_>) -> Result<Self> { Self::arbitrary(&mut u) } /// Get a size hint for how many bytes out of an `Unstructured` this type /// needs to construct itself. /// /// This is useful for determining how many elements we should insert when /// creating an arbitrary collection. /// /// The return value is similar to /// [`Iterator::size_hint`][iterator-size-hint]: it returns a tuple where /// the first element is a lower bound on the number of bytes required, and /// the second element is an optional upper bound. /// /// The default implementation return `(0, None)` which is correct for any /// type, but not ultimately that useful. Using `#[derive(Arbitrary)]` will /// create a better implementation. If you are writing an `Arbitrary` /// implementation by hand, and your type can be part of a dynamically sized /// collection (such as `Vec`), you are strongly encouraged to override this /// default with a better implementation. The /// [`size_hint`][crate::size_hint] module will help with this task. /// /// ## The `depth` Parameter /// /// If you 100% know that the type you are implementing `Arbitrary` for is /// not a recursive type, or your implementation is not transitively calling /// any other `size_hint` methods, you can ignore the `depth` parameter. /// Note that if you are implementing `Arbitrary` for a generic type, you /// cannot guarantee the lack of type recrusion! /// /// Otherwise, you need to use /// [`arbitrary::size_hint::recursion_guard(depth)`][crate::size_hint::recursion_guard] /// to prevent potential infinite recursion when calculating size hints for /// potentially recursive types: /// /// ``` /// use arbitrary::{Arbitrary, Unstructured, size_hint}; /// /// // This can potentially be a recursive type if `L` or `R` contain /// // something like `Box<Option<MyEither<L, R>>>`! /// enum MyEither<L, R> { /// Left(L), /// Right(R), /// } /// /// impl<L, R> Arbitrary for MyEither<L, R> /// where /// L: Arbitrary, /// R: Arbitrary, /// { /// fn arbitrary(u: &mut Unstructured) -> arbitrary::Result<Self> { /// // ... /// # unimplemented!() /// } /// /// fn size_hint(depth: usize) -> (usize, Option<usize>) { /// // Protect against potential infinite recursion with /// // `recursion_guard`. /// size_hint::recursion_guard(depth, |depth| { /// // If we aren't too deep, then `recursion_guard` calls /// // this closure, which implements the natural size hint. /// // Don't forget to use the new `depth` in all nested /// // `size_hint` calls! We recommend shadowing the /// // parameter, like what is done here, so that you can't /// // accidentally use the wrong depth. /// size_hint::or( /// <L as Arbitrary>::size_hint(depth), /// <R as Arbitrary>::size_hint(depth), /// ) /// }) /// } /// } /// ``` /// /// [iterator-size-hint]: https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.size_hint #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { let _ = depth; (0, None) } /// Generate an iterator of derived values which are "smaller" than the /// original `self` instance. /// /// You can use this to help find the smallest test case that reproduces a /// bug. /// /// Using `#[derive(Arbitrary)]` will automatically implement shrinking for /// your type. /// /// However, if you are implementing `Arbirary` by hand and you want support /// for shrinking your type, you must override the default provided /// implementation of `shrink`, which just returns an empty iterator. You /// should try pretty hard to have your `shrink` implementation return a /// *lazy* iterator: one that computes the next value as it is needed, /// rather than computing them up front when `shrink` is first called. fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { empty() } } impl Arbitrary for () { fn arbitrary(_: &mut Unstructured<'_>) -> Result<Self> { Ok(()) } #[inline] fn size_hint(_depth: usize) -> (usize, Option<usize>) { (0, Some(0)) } } impl Arbitrary for bool { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { Ok(<u8 as Arbitrary>::arbitrary(u)? & 1 == 1) } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { <u8 as Arbitrary>::size_hint(depth) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { Box::new(if *self { once(false) } else { empty() }) } } macro_rules! impl_arbitrary_for_integers { ( $( $ty:ty: $unsigned:ty; )* ) => { $( impl Arbitrary for $ty { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { let mut buf = [0; mem::size_of::<$ty>()]; u.fill_buffer(&mut buf)?; let mut x: $unsigned = 0; for i in 0..mem::size_of::<$ty>() { x |= buf[i] as $unsigned << (i * 8); } Ok(x as $ty) } #[inline] fn size_hint(_depth: usize) -> (usize, Option<usize>) { let n = mem::size_of::<$ty>(); (n, Some(n)) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { let mut x = *self; if x == 0 { return empty(); } Box::new(iter::once(0).chain(std::iter::from_fn(move || { x = x / 2; if x == 0 { None } else { Some(x) } }))) } } )* } } impl_arbitrary_for_integers! { u8: u8; u16: u16; u32: u32; u64: u64; u128: u128; usize: usize; i8: u8; i16: u16; i32: u32; i64: u64; i128: u128; isize: usize; } macro_rules! impl_arbitrary_for_floats { ( $( $ty:ident : $unsigned:ty; )* ) => { $( impl Arbitrary for $ty { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { Ok(Self::from_bits(<$unsigned as Arbitrary>::arbitrary(u)?)) } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { <$unsigned as Arbitrary>::size_hint(depth) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { if *self == 0.0 { empty() } else if !self.is_finite() { once(0.0) } else { let mut x = *self; Box::new(iter::once(0.0).chain(iter::from_fn(move || { // NB: do not test for zero like we do for integers // because dividing by two until we reach a fixed // point is NOT guaranteed to end at zero in // non-default rounding modes of IEEE-754! // // For example, with 64-bit floats and the // round-to-positive-infinity mode: // // 5e-324 / 2.0 == 5e-324 // // (5e-234 is the smallest postive number that can // be precisely represented in a 64-bit float.) let y = x; x = x / 2.0; if x == y { None } else { Some(x) } }))) } } } )* } } impl_arbitrary_for_floats! { f32: u32; f64: u64; } impl Arbitrary for char { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { use std::char; const CHAR_END: u32 = 0x0011_000; // The size of the surrogate blocks const SURROGATES_START: u32 = 0xD800; let mut c = <u32 as Arbitrary>::arbitrary(u)? % CHAR_END; if let Some(c) = char::from_u32(c) { return Ok(c); } else { // We found a surrogate, wrap and try again c -= SURROGATES_START; Ok(char::from_u32(c) .expect("Generated character should be valid! This is a bug in arbitrary-rs")) } } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { <u32 as Arbitrary>::size_hint(depth) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { let x = *self as u32; Box::new(x.shrink().filter_map(|x| { use std::convert::TryFrom; char::try_from(x).ok() })) } } impl Arbitrary for AtomicBool { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { Arbitrary::arbitrary(u).map(Self::new) } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { <bool as Arbitrary>::size_hint(depth) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { if self.load(Ordering::SeqCst) { once(AtomicBool::new(false)) } else { empty() } } } impl Arbitrary for AtomicIsize { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { Arbitrary::arbitrary(u).map(Self::new) } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { <isize as Arbitrary>::size_hint(depth) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { let x = self.load(Ordering::SeqCst); Box::new(x.shrink().map(Self::new)) } } impl Arbitrary for AtomicUsize { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { Arbitrary::arbitrary(u).map(Self::new) } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { <usize as Arbitrary>::size_hint(depth) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { let x = self.load(Ordering::SeqCst); Box::new(x.shrink().map(Self::new)) } } macro_rules! impl_range { ( $range:ty, $value_closure:expr, $value_ty:ty, $fun:ident($fun_closure:expr), $size_hint_closure:expr ) => { impl<A> Arbitrary for $range where A: Arbitrary + Clone + PartialOrd, { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { let value: $value_ty = Arbitrary::arbitrary(u)?; Ok($fun(value, $fun_closure)) } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { $size_hint_closure(depth) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { let value: $value_ty = $value_closure(self); Box::new(value.shrink().map(|v| $fun(v, $fun_closure))) } } }; } impl_range!( Range<A>, |r: &Range<A>| (r.start.clone(), r.end.clone()), (A, A), bounded_range(|(a, b)| a..b), |depth| crate::size_hint::and( <A as Arbitrary>::size_hint(depth), <A as Arbitrary>::size_hint(depth) ) ); impl_range!( RangeFrom<A>, |r: &RangeFrom<A>| r.start.clone(), A, unbounded_range(|a| a..), |depth| <A as Arbitrary>::size_hint(depth) ); impl_range!( RangeInclusive<A>, |r: &RangeInclusive<A>| (r.start().clone(), r.end().clone()), (A, A), bounded_range(|(a, b)| a..=b), |depth| crate::size_hint::and( <A as Arbitrary>::size_hint(depth), <A as Arbitrary>::size_hint(depth) ) ); impl_range!( RangeTo<A>, |r: &RangeTo<A>| r.end.clone(), A, unbounded_range(|b| ..b), |depth| <A as Arbitrary>::size_hint(depth) ); impl_range!( RangeToInclusive<A>, |r: &RangeToInclusive<A>| r.end.clone(), A, unbounded_range(|b| ..=b), |depth| <A as Arbitrary>::size_hint(depth) ); fn bounded_range<CB, I, R>(bounds: (I, I), cb: CB) -> R where CB: Fn((I, I)) -> R, I: PartialOrd, R: RangeBounds<I>, { let (mut start, mut end) = bounds; if start > end { mem::swap(&mut start, &mut end); } cb((start, end)) } fn unbounded_range<CB, I, R>(bound: I, cb: CB) -> R where CB: Fn(I) -> R, R: RangeBounds<I>, { cb(bound) } impl Arbitrary for Duration { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { Ok(Self::new( <u64 as Arbitrary>::arbitrary(u)?, u.int_in_range(0..=999_999_999)?, )) } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { crate::size_hint::and( <u64 as Arbitrary>::size_hint(depth), <u32 as Arbitrary>::size_hint(depth), ) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { Box::new( (self.as_secs(), self.subsec_nanos()) .shrink() .map(|(secs, nanos)| Duration::new(secs, nanos % 1_000_000_000)), ) } } impl<A: Arbitrary> Arbitrary for Option<A> { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { Ok(if <bool as Arbitrary>::arbitrary(u)? { Some(Arbitrary::arbitrary(u)?) } else { None }) } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { crate::size_hint::and( <bool as Arbitrary>::size_hint(depth), crate::size_hint::or((0, Some(0)), <A as Arbitrary>::size_hint(depth)), ) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { if let Some(ref a) = *self { Box::new(iter::once(None).chain(a.shrink().map(Some))) } else { empty() } } } impl<A: Arbitrary, B: Arbitrary> Arbitrary for std::result::Result<A, B> { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { Ok(if <bool as Arbitrary>::arbitrary(u)? { Ok(<A as Arbitrary>::arbitrary(u)?) } else { Err(<B as Arbitrary>::arbitrary(u)?) }) } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { crate::size_hint::and( <bool as Arbitrary>::size_hint(depth), crate::size_hint::or( <A as Arbitrary>::size_hint(depth), <B as Arbitrary>::size_hint(depth), ), ) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { match *self { Ok(ref a) => Box::new(a.shrink().map(Ok)), Err(ref b) => Box::new(b.shrink().map(Err)), } } } macro_rules! arbitrary_tuple { () => {}; ($last: ident $($xs: ident)*) => { arbitrary_tuple!($($xs)*); impl<$($xs: Arbitrary,)* $last: Arbitrary> Arbitrary for ($($xs,)* $last,) { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { Ok(($($xs::arbitrary(u)?,)* Arbitrary::arbitrary(u)?,)) } #[allow(unused_mut, non_snake_case)] fn arbitrary_take_rest(mut u: Unstructured<'_>) -> Result<Self> { $(let $xs = $xs::arbitrary(&mut u)?;)* let $last = $last::arbitrary_take_rest(u)?; Ok(($($xs,)* $last,)) } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { crate::size_hint::and_all(&[ <$last as Arbitrary>::size_hint(depth), $( <$xs as Arbitrary>::size_hint(depth) ),* ]) } #[allow(non_snake_case)] fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { let ( $( $xs, )* $last, ) = self; let ( $( mut $xs, )* mut $last,) = ( $( $xs.shrink(), )* $last.shrink(),); Box::new(iter::from_fn(move || { Some(( $( $xs.next()? ,)* $last.next()?, )) })) } } }; } arbitrary_tuple!(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z); macro_rules! arbitrary_array { {$n:expr, ($t:ident, $a:ident) $(($ts:ident, $as:ident))*} => { arbitrary_array!{($n - 1), $(($ts, $as))*} impl<T: Arbitrary> Arbitrary for [T; $n] { fn arbitrary(u: &mut Unstructured<'_>) -> Result<[T; $n]> { Ok([ Arbitrary::arbitrary(u)?, $(<$ts as Arbitrary>::arbitrary(u)?),* ]) } #[allow(unused_mut)] fn arbitrary_take_rest(mut u: Unstructured<'_>) -> Result<[T; $n]> { $(let $as = $ts::arbitrary(&mut u)?;)* let last = Arbitrary::arbitrary_take_rest(u)?; Ok([ $($as,)* last ]) } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { crate::size_hint::and_all(&[ <$t as Arbitrary>::size_hint(depth), $( <$ts as Arbitrary>::size_hint(depth) ),* ]) } #[allow(unused_mut)] // For the `[T; 1]` case. fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { let mut i = 0; let mut shrinkers = [ self[i].shrink(), $({ i += 1; let t: &$ts = &self[i]; t.shrink() }),* ]; Box::new(iter::from_fn(move || { let mut i = 0; Some([ shrinkers[i].next()?, $({ i += 1; let t: $ts = shrinkers[i].next()?; t }),* ]) })) } } }; ($n: expr,) => {}; } impl<T: Arbitrary> Arbitrary for [T; 0] { fn arbitrary(_: &mut Unstructured<'_>) -> Result<[T; 0]> { Ok([]) } fn arbitrary_take_rest(_: Unstructured<'_>) -> Result<[T; 0]> { Ok([]) } #[inline] fn size_hint(_: usize) -> (usize, Option<usize>) { crate::size_hint::and_all(&[]) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { Box::new(iter::from_fn(|| None)) } } arbitrary_array! { 32, (T, a) (T, b) (T, c) (T, d) (T, e) (T, f) (T, g) (T, h) (T, i) (T, j) (T, k) (T, l) (T, m) (T, n) (T, o) (T, p) (T, q) (T, r) (T, s) (T, u) (T, v) (T, w) (T, x) (T, y) (T, z) (T, aa) (T, ab) (T, ac) (T, ad) (T, ae) (T, af) (T, ag) } fn shrink_collection<'a, T, A: Arbitrary>( entries: impl Iterator<Item = T>, f: impl Fn(&T) -> Box<dyn Iterator<Item = A>>, ) -> Box<dyn Iterator<Item = Vec<A>>> { let entries: Vec<_> = entries.collect(); if entries.is_empty() { return empty(); } let mut shrinkers: Vec<Vec<_>> = vec![]; let mut i = entries.len(); loop { shrinkers.push(entries.iter().take(i).map(&f).collect()); i = i / 2; if i == 0 { break; } } Box::new(iter::once(vec![]).chain(iter::from_fn(move || loop { let mut shrinker = shrinkers.pop()?; let x: Option<Vec<A>> = shrinker.iter_mut().map(|s| s.next()).collect(); if x.is_none() { continue; } shrinkers.push(shrinker); return x; }))) } impl<A: Arbitrary> Arbitrary for Vec<A> { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { u.arbitrary_iter()?.collect() } fn arbitrary_take_rest(u: Unstructured<'_>) -> Result<Self> { u.arbitrary_take_rest_iter()?.collect() } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { crate::size_hint::and(<usize as Arbitrary>::size_hint(depth), (0, None)) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { shrink_collection(self.iter(), |x| x.shrink()) } } impl<K: Arbitrary + Ord, V: Arbitrary> Arbitrary for BTreeMap<K, V> { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { u.arbitrary_iter()?.collect() } fn arbitrary_take_rest(u: Unstructured<'_>) -> Result<Self> { u.arbitrary_take_rest_iter()?.collect() } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { crate::size_hint::and(<usize as Arbitrary>::size_hint(depth), (0, None)) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { let collections = shrink_collection(self.iter(), |(k, v)| Box::new(k.shrink().zip(v.shrink()))); Box::new(collections.map(|entries| entries.into_iter().collect())) } } impl<A: Arbitrary + Ord> Arbitrary for BTreeSet<A> { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { u.arbitrary_iter()?.collect() } fn arbitrary_take_rest(u: Unstructured<'_>) -> Result<Self> { u.arbitrary_take_rest_iter()?.collect() } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { crate::size_hint::and(<usize as Arbitrary>::size_hint(depth), (0, None)) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { let collections = shrink_collection(self.iter(), |v| v.shrink()); Box::new(collections.map(|entries| entries.into_iter().collect())) } } impl<A: Arbitrary + Ord> Arbitrary for BinaryHeap<A> { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { u.arbitrary_iter()?.collect() } fn arbitrary_take_rest(u: Unstructured<'_>) -> Result<Self> { u.arbitrary_take_rest_iter()?.collect() } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { crate::size_hint::and(<usize as Arbitrary>::size_hint(depth), (0, None)) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { let collections = shrink_collection(self.iter(), |v| v.shrink()); Box::new(collections.map(|entries| entries.into_iter().collect())) } } impl<K: Arbitrary + Eq + ::std::hash::Hash, V: Arbitrary> Arbitrary for HashMap<K, V> { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { u.arbitrary_iter()?.collect() } fn arbitrary_take_rest(u: Unstructured<'_>) -> Result<Self> { u.arbitrary_take_rest_iter()?.collect() } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { crate::size_hint::and(<usize as Arbitrary>::size_hint(depth), (0, None)) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { let collections = shrink_collection(self.iter(), |(k, v)| Box::new(k.shrink().zip(v.shrink()))); Box::new(collections.map(|entries| entries.into_iter().collect())) } } impl<A: Arbitrary + Eq + ::std::hash::Hash> Arbitrary for HashSet<A> { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { u.arbitrary_iter()?.collect() } fn arbitrary_take_rest(u: Unstructured<'_>) -> Result<Self> { u.arbitrary_take_rest_iter()?.collect() } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { crate::size_hint::and(<usize as Arbitrary>::size_hint(depth), (0, None)) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { let collections = shrink_collection(self.iter(), |v| v.shrink()); Box::new(collections.map(|entries| entries.into_iter().collect())) } } impl<A: Arbitrary> Arbitrary for LinkedList<A> { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { u.arbitrary_iter()?.collect() } fn arbitrary_take_rest(u: Unstructured<'_>) -> Result<Self> { u.arbitrary_take_rest_iter()?.collect() } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { crate::size_hint::and(<usize as Arbitrary>::size_hint(depth), (0, None)) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { let collections = shrink_collection(self.iter(), |v| v.shrink()); Box::new(collections.map(|entries| entries.into_iter().collect())) } } impl<A: Arbitrary> Arbitrary for VecDeque<A> { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { u.arbitrary_iter()?.collect() } fn arbitrary_take_rest(u: Unstructured<'_>) -> Result<Self> { u.arbitrary_take_rest_iter()?.collect() } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { crate::size_hint::and(<usize as Arbitrary>::size_hint(depth), (0, None)) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { let collections = shrink_collection(self.iter(), |v| v.shrink()); Box::new(collections.map(|entries| entries.into_iter().collect())) } } impl<A> Arbitrary for Cow<'static, A> where A: ToOwned + ?Sized, <A as ToOwned>::Owned: Arbitrary, { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { Arbitrary::arbitrary(u).map(Cow::Owned) } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { crate::size_hint::recursion_guard(depth, |depth| { <<A as ToOwned>::Owned as Arbitrary>::size_hint(depth) }) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { match *self { Cow::Owned(ref o) => Box::new(o.shrink().map(Cow::Owned)), Cow::Borrowed(b) => Box::new(b.to_owned().shrink().map(Cow::Owned)), } } } impl Arbitrary for String { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { let size = u.arbitrary_len::<u8>()?; match str::from_utf8(&u.peek_bytes(size).unwrap()) { Ok(s) => { u.get_bytes(size).unwrap(); Ok(s.into()) } Err(e) => { let i = e.valid_up_to(); let valid = u.get_bytes(i).unwrap(); let s = unsafe { debug_assert!(str::from_utf8(valid).is_ok()); str::from_utf8_unchecked(valid) }; Ok(s.into()) } } } fn arbitrary_take_rest(u: Unstructured<'_>) -> Result<Self> { let bytes = u.take_rest(); str::from_utf8(bytes) .map_err(|_| Error::IncorrectFormat) .map(Into::into) } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { crate::size_hint::and(<usize as Arbitrary>::size_hint(depth), (0, None)) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { let collections = shrink_collection(self.chars(), |ch| ch.shrink()); Box::new(collections.map(|chars| chars.into_iter().collect())) } } impl Arbitrary for CString { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { <Vec<u8> as Arbitrary>::arbitrary(u).map(|mut x| { x.retain(|&c| c != 0); Self::new(x).unwrap() }) } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { <Vec<u8> as Arbitrary>::size_hint(depth) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { let collections = shrink_collection(self.as_bytes().iter(), |b| { Box::new(b.shrink().filter(|&b| b != 0)) }); Box::new(collections.map(|bytes| Self::new(bytes).unwrap())) } } impl Arbitrary for OsString { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { <String as Arbitrary>::arbitrary(u).map(From::from) } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { <String as Arbitrary>::size_hint(depth) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { match self.clone().into_string() { Err(_) if self.is_empty() => empty(), Err(_) => once(OsString::from("".to_string())), Ok(s) => Box::new(s.shrink().map(From::from)), } } } impl Arbitrary for PathBuf { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { <OsString as Arbitrary>::arbitrary(u).map(From::from) } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { <OsString as Arbitrary>::size_hint(depth) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { let s = self.clone().into_os_string(); Box::new(s.shrink().map(From::from)) } } impl<A: Arbitrary> Arbitrary for Box<A> { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { Arbitrary::arbitrary(u).map(Self::new) } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { crate::size_hint::recursion_guard(depth, |depth| <A as Arbitrary>::size_hint(depth)) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { Box::new((&**self).shrink().map(Self::new)) } } impl<A: Arbitrary> Arbitrary for Box<[A]> { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { <Vec<A> as Arbitrary>::arbitrary(u).map(|x| x.into_boxed_slice()) } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { <Vec<A> as Arbitrary>::size_hint(depth) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { Box::new(shrink_collection(self.iter(), |x| x.shrink()).map(|v| v.into_boxed_slice())) } } impl Arbitrary for Box<str> { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { <String as Arbitrary>::arbitrary(u).map(|x| x.into_boxed_str()) } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { <String as Arbitrary>::size_hint(depth) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { let collections = shrink_collection(self.chars(), |ch| ch.shrink()); Box::new(collections.map(|chars| chars.into_iter().collect::<String>().into_boxed_str())) } } // impl Arbitrary for Box<CStr> { // fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { // <CString as Arbitrary>::arbitrary(u).map(|x| x.into_boxed_c_str()) // } // } // impl Arbitrary for Box<OsStr> { // fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { // <OsString as Arbitrary>::arbitrary(u).map(|x| x.into_boxed_osstr()) // // } // } impl<A: Arbitrary> Arbitrary for Arc<A> { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { Arbitrary::arbitrary(u).map(Self::new) } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { crate::size_hint::recursion_guard(depth, |depth| <A as Arbitrary>::size_hint(depth)) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { Box::new((&**self).shrink().map(Self::new)) } } impl<A: Arbitrary> Arbitrary for Rc<A> { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { Arbitrary::arbitrary(u).map(Self::new) } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { crate::size_hint::recursion_guard(depth, |depth| <A as Arbitrary>::size_hint(depth)) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { Box::new((&**self).shrink().map(Self::new)) } } impl<A: Arbitrary> Arbitrary for Cell<A> { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { Arbitrary::arbitrary(u).map(Self::new) } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { <A as Arbitrary>::size_hint(depth) } // Note: can't implement `shrink` without either more trait bounds on `A` // (copy or default) or `Cell::update`: // https://github.com/rust-lang/rust/issues/50186 } impl<A: Arbitrary> Arbitrary for RefCell<A> { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { Arbitrary::arbitrary(u).map(Self::new) } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { <A as Arbitrary>::size_hint(depth) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { let x = self.borrow(); Box::new(x.shrink().map(Self::new)) } } impl<A: Arbitrary> Arbitrary for UnsafeCell<A> { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { Arbitrary::arbitrary(u).map(Self::new) } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { <A as Arbitrary>::size_hint(depth) } // We can't non-trivially (i.e. not an empty iterator) implement `shrink` in // a safe way, since we don't have a safe way to get the inner value. } impl<A: Arbitrary> Arbitrary for Mutex<A> { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { Arbitrary::arbitrary(u).map(Self::new) } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { <A as Arbitrary>::size_hint(depth) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { match self.lock() { Err(_) => empty(), Ok(g) => Box::new(g.shrink().map(Self::new)), } } } impl<A: Arbitrary> Arbitrary for iter::Empty<A> { fn arbitrary(_: &mut Unstructured<'_>) -> Result<Self> { Ok(iter::empty()) } #[inline] fn size_hint(_depth: usize) -> (usize, Option<usize>) { (0, Some(0)) } // Nothing to shrink here. } impl<A: Arbitrary> Arbitrary for ::std::marker::PhantomData<A> { fn arbitrary(_: &mut Unstructured<'_>) -> Result<Self> { Ok(::std::marker::PhantomData) } #[inline] fn size_hint(_depth: usize) -> (usize, Option<usize>) { (0, Some(0)) } // Nothing to shrink here. } impl<A: Arbitrary> Arbitrary for ::std::num::Wrapping<A> { fn arbitrary(u: &mut Unstructured<'_>) -> Result<Self> { Arbitrary::arbitrary(u).map(::std::num::Wrapping) } #[inline] fn size_hint(depth: usize) -> (usize, Option<usize>) { <A as Arbitrary>::size_hint(depth) } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { let ref x = self.0; Box::new(x.shrink().map(::std::num::Wrapping)) } } #[cfg(test)] mod test { use super::*; #[test] fn finite_buffer_fill_buffer() { let x = [1, 2, 3, 4]; let mut rb = Unstructured::new(&x); let mut z = [0; 2]; rb.fill_buffer(&mut z).unwrap(); assert_eq!(z, [1, 2]); rb.fill_buffer(&mut z).unwrap(); assert_eq!(z, [3, 4]); rb.fill_buffer(&mut z).unwrap(); assert_eq!(z, [0, 0]); } #[test] fn arbitrary_for_integers() { let x = [1, 2, 3, 4]; let mut buf = Unstructured::new(&x); let expected = 1 | (2 << 8) | (3 << 16) | (4 << 24); let actual = i32::arbitrary(&mut buf).unwrap(); assert_eq!(expected, actual); } #[test] fn arbitrary_collection() { let x = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, ]; assert_eq!( Vec::<u8>::arbitrary(&mut Unstructured::new(&x)).unwrap(), &[2, 4, 6, 8, 1] ); assert_eq!( Vec::<u32>::arbitrary(&mut Unstructured::new(&x)).unwrap(), &[84148994] ); assert_eq!( String::arbitrary(&mut Unstructured::new(&x)).unwrap(), "\x01\x02\x03\x04\x05\x06\x07\x08" ); } #[test] fn arbitrary_take_rest() { let x = [1, 2, 3, 4]; assert_eq!( Vec::<u8>::arbitrary_take_rest(Unstructured::new(&x)).unwrap(), &[1, 2, 3, 4] ); assert_eq!( Vec::<u32>::arbitrary_take_rest(Unstructured::new(&x)).unwrap(), &[0x4030201] ); assert_eq!( String::arbitrary_take_rest(Unstructured::new(&x)).unwrap(), "\x01\x02\x03\x04" ); } #[test] fn shrink_tuple() { let tup = (10, 20, 30); assert_eq!( tup.shrink().collect::<Vec<_>>(), [(0, 0, 0), (5, 10, 15), (2, 5, 7), (1, 2, 3)] ); } #[test] fn shrink_array() { let tup = [10, 20, 30]; assert_eq!( tup.shrink().collect::<Vec<_>>(), [[0, 0, 0], [5, 10, 15], [2, 5, 7], [1, 2, 3]] ); } #[test] fn shrink_vec() { let v = vec![4, 4, 4, 4]; assert_eq!( v.shrink().collect::<Vec<_>>(), [ vec![], vec![0], vec![2], vec![1], vec![0, 0], vec![2, 2], vec![1, 1], vec![0, 0, 0, 0], vec![2, 2, 2, 2], vec![1, 1, 1, 1] ] ); } #[test] fn shrink_string() { let s = "aaaa".to_string(); assert_eq!( s.shrink().collect::<Vec<_>>(), [ "", "\u{0}", "0", "\u{18}", "\u{c}", "\u{6}", "\u{3}", "\u{1}", "\u{0}\u{0}", "00", "\u{18}\u{18}", "\u{c}\u{c}", "\u{6}\u{6}", "\u{3}\u{3}", "\u{1}\u{1}", "\u{0}\u{0}\u{0}\u{0}", "0000", "\u{18}\u{18}\u{18}\u{18}", "\u{c}\u{c}\u{c}\u{c}", "\u{6}\u{6}\u{6}\u{6}", "\u{3}\u{3}\u{3}\u{3}", "\u{1}\u{1}\u{1}\u{1}" ] .iter() .map(|s| s.to_string()) .collect::<Vec<_>>(), ); } #[test] fn shrink_cstring() { let s = CString::new(b"aaaa".to_vec()).unwrap(); assert_eq!( s.shrink().collect::<Vec<_>>(), [ &[][..], &[b'0'][..], &[0x18][..], &[0x0c][..], &[0x06][..], &[0x03][..], &[0x01][..], &[b'0', b'0'][..], &[0x18, 0x18][..], &[0x0c, 0x0c][..], &[0x06, 0x06][..], &[0x03, 0x03][..], &[0x01, 0x01][..], &[b'0', b'0', b'0', b'0'][..], &[0x18, 0x18, 0x18, 0x18][..], &[0x0c, 0x0c, 0x0c, 0x0c][..], &[0x06, 0x06, 0x06, 0x06][..], &[0x03, 0x03, 0x03, 0x03][..], &[0x01, 0x01, 0x01, 0x01][..], ] .iter() .map(|s| CString::new(s.to_vec()).unwrap()) .collect::<Vec<_>>(), ); } #[test] fn size_hint_for_tuples() { assert_eq!((7, Some(7)), <(bool, u16, i32) as Arbitrary>::size_hint(0)); assert_eq!( (1 + mem::size_of::<usize>(), None), <(u8, Vec<u8>) as Arbitrary>::size_hint(0) ); } }
31.346649
108
0.519061
c138ec0d9150cba4145cdeedded6d1e642d39681
448
#![no_main] use arbitrary::Unstructured; use libfuzzer_sys::fuzz_target; fuzz_target!(|bytes: &[u8]| { let mut u = Unstructured::new(bytes); let (bytes, _config) = match wasm_tools_fuzz::generate_valid_module(&mut u, |_, _| Ok(())) { Ok(m) => m, Err(_) => return, }; // Print the Wasm module. if let Err(e) = wasmprinter::print_bytes(&bytes) { panic!("Failed to print valid module: {}", e); } });
24.888889
96
0.591518
4a84aeb0a68f21979a80aca7eda8c2cd4bb945cb
2,497
use core::convert::TryInto; use core::marker::PhantomData; use embedded_hal::blocking::i2c::{Write, WriteRead}; pub const LSM_MAG_I2C_ADDR: u8 = 0b001_1110; #[allow(non_camel_case_types)] pub struct LSM303LDHC_MAG<TI2C> { phantom: PhantomData<TI2C>, } #[derive(Clone, Debug)] #[repr(u8)] #[allow(dead_code)] pub enum DataRate { Rate0_75hz = 0b000 << 2, Rate1_5Hz = 0b001 << 2, Rate3Hz = 0b010 << 2, Rate7_5Hz = 0b011 << 2, Rate15Hz = 0b100 << 2, Rate30Hz = 0b101 << 2, Rate75Hz = 0b110 << 2, Rate220Hz = 0b111 << 2, } #[derive(Clone, Debug)] pub struct MagData { pub x: i16, pub y: i16, pub z: i16, } #[derive(Clone, Debug)] pub struct TempData(pub i16); impl<TI2C: WriteRead + Write> LSM303LDHC_MAG<TI2C> { pub fn init(i2c: &mut TI2C, data_rate: DataRate) -> Result<Self, <TI2C as Write>::Error> { i2c.write(LSM_MAG_I2C_ADDR, &[register::MR_REG_M, 0x00])?; i2c.write( LSM_MAG_I2C_ADDR, &[register::CRA_REG_M, data_rate as u8 | 0x80], )?; Ok(Self { phantom: PhantomData, }) } pub fn read_reg(&mut self, i2c: &mut TI2C, reg: u8) -> Result<u8, <TI2C as WriteRead>::Error> { let mut buf = [0u8]; i2c.write_read(LSM_MAG_I2C_ADDR, &[reg], &mut buf)?; Ok(buf[0]) } pub fn read_sample(&mut self, i2c: &mut TI2C) -> Result<MagData, <TI2C as WriteRead>::Error> { let mut buf = [0u8; 6]; i2c.write_read(LSM_MAG_I2C_ADDR, &[register::OUT_X_H_M], &mut buf)?; let x = i16::from_be_bytes(buf[0..=1].try_into().unwrap()); let z = i16::from_be_bytes(buf[2..=3].try_into().unwrap()); let y = i16::from_be_bytes(buf[4..=5].try_into().unwrap()); Ok(MagData { x, y, z }) } pub fn read_temp(&mut self, _i2c: &mut TI2C) -> Result<TempData, <TI2C as WriteRead>::Error> { todo!() } } #[allow(dead_code)] pub mod register { pub const CRA_REG_M: u8 = 0x00; pub const CRB_REG_M: u8 = 0x01; pub const MR_REG_M: u8 = 0x02; pub const OUT_X_H_M: u8 = 0x03; pub const OUT_X_L_M: u8 = 0x04; pub const OUT_Z_H_M: u8 = 0x05; pub const OUT_Z_L_M: u8 = 0x06; pub const OUT_Y_H_M: u8 = 0x07; pub const OUT_Y_L_M: u8 = 0x08; pub const SR_REG_M: u8 = 0x09; pub const IRA_REG_M: u8 = 0x0A; pub const IRB_REG_M: u8 = 0x0B; pub const IRC_REG_M: u8 = 0x0C; pub const TEMP_OUT_H_M: u8 = 0x31; pub const TEMP_OUT_L_M: u8 = 0x32; }
27.141304
99
0.603925
5da133a31262a168572a4960a6fdafc59088a12b
6,076
// 3D Projective Geometric Algebra // Written by a generator written by enki. #![allow(unused_imports)] #![allow(dead_code)] #![allow(non_upper_case_globals)] #![allow(non_snake_case)] #![allow(non_camel_case_types)] #![feature(const_slice_len)] use std::fmt; use std::ops::{Index,IndexMut,Add,Sub,Mul,BitAnd,BitOr,BitXor,Not}; type float_t = f64; // use std::f64::consts::PI; const PI: float_t = 3.14159265358979323846; const basis: &'static [&'static str] = &[ "1","e0" ]; const basis_count: usize = basis.len(); #[derive(Default,Debug,Clone,Copy,PartialEq)] struct DUAL { mvec: [float_t; basis_count] } impl DUAL { pub const fn zero() -> Self { Self { mvec: [0.0; basis_count] } } pub const fn new(f: float_t, idx: usize) -> Self { let mut ret = Self::zero(); ret.mvec[idx] = f; ret } } // basis vectors are available as global constants. const e0: DUAL = DUAL::new(1.0, 1); impl Index<usize> for DUAL { type Output = float_t; fn index<'a>(&'a self, index: usize) -> &'a Self::Output { &self.mvec[index] } } impl IndexMut<usize> for DUAL { fn index_mut<'a>(&'a mut self, index: usize) -> &'a mut Self::Output { &mut self.mvec[index] } } impl fmt::Display for DUAL { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut n = 0; let ret = self.mvec.iter().enumerate().filter_map(|(i, &coeff)| { if coeff > 0.00001 || coeff < -0.00001 { n = 1; Some(format!("{}{}", format!("{:.*}", 7, coeff).trim_end_matches('0').trim_end_matches('.'), if i > 0 { basis[i] } else { "" } ) ) } else { None } }).collect::<Vec<String>>().join(" + "); if n==0 { write!(f,"0") } else { write!(f, "{}", ret) } } } // Reverse // Reverse the order of the basis blades. impl DUAL { pub fn Reverse(self: Self) -> DUAL { let mut res = DUAL::zero(); let a = self; res[0]=a[0]; res[1]=a[1]; res } } // Dual // Poincare duality operator. impl DUAL { pub fn Dual(self: Self) -> DUAL { let mut res = DUAL::zero(); let a = self; res[0]=a[1]; res[1]=a[0]; res } } impl Not for DUAL { type Output = DUAL; fn not(self: Self) -> DUAL { let mut res = DUAL::zero(); let a = self; res[0]=a[1]; res[1]=a[0]; res } } // Conjugate // Clifford Conjugation impl DUAL { pub fn Conjugate(self: Self) -> DUAL { let mut res = DUAL::zero(); let a = self; res[0]=a[0]; res[1]=-a[1]; res } } // Involute // Main involution impl DUAL { pub fn Involute(self: Self) -> DUAL { let mut res = DUAL::zero(); let a = self; res[0]=a[0]; res[1]=-a[1]; res } } // Mul // The geometric product. impl Mul for DUAL { type Output = DUAL; fn mul(self: DUAL, b: DUAL) -> DUAL { let mut res = DUAL::zero(); let a = self; res[0]=b[0]*a[0]; res[1]=b[1]*a[0]+b[0]*a[1]; res } } // Wedge // The outer product. (MEET) impl BitXor for DUAL { type Output = DUAL; fn bitxor(self: DUAL, b: DUAL) -> DUAL { let mut res = DUAL::zero(); let a = self; res[0]=b[0]*a[0]; res[1]=b[1]*a[0]+b[0]*a[1]; res } } // Vee // The regressive product. (JOIN) impl BitAnd for DUAL { type Output = DUAL; fn bitand(self: DUAL, b: DUAL) -> DUAL { let mut res = DUAL::zero(); let a = self; res[1]=b[1]*a[1]; res[0]=b[0]*a[1]+b[1]*a[0]; res } } // Dot // The inner product. impl BitOr for DUAL { type Output = DUAL; fn bitor(self: DUAL, b: DUAL) -> DUAL { let mut res = DUAL::zero(); let a = self; res[0]=b[0]*a[0]; res[1]=b[1]*a[0]+b[0]*a[1]; res } } // Add // Multivector addition impl Add for DUAL { type Output = DUAL; fn add(self: DUAL, b: DUAL) -> DUAL { let mut res = DUAL::zero(); let a = self; res[0] = a[0]+b[0]; res[1] = a[1]+b[1]; res } } // Sub // Multivector subtraction impl Sub for DUAL { type Output = DUAL; fn sub(self: DUAL, b: DUAL) -> DUAL { let mut res = DUAL::zero(); let a = self; res[0] = a[0]-b[0]; res[1] = a[1]-b[1]; res } } // smul // scalar/multivector multiplication impl Mul<DUAL> for float_t { type Output = DUAL; fn mul(self: float_t, b: DUAL) -> DUAL { let mut res = DUAL::zero(); let a = self; res[0] = a*b[0]; res[1] = a*b[1]; res } } // muls // multivector/scalar multiplication impl Mul<float_t> for DUAL { type Output = DUAL; fn mul(self: DUAL, b: float_t) -> DUAL { let mut res = DUAL::zero(); let a = self; res[0] = a[0]*b; res[1] = a[1]*b; res } } // sadd // scalar/multivector addition impl Add<DUAL> for float_t { type Output = DUAL; fn add(self: float_t, b: DUAL) -> DUAL { let mut res = DUAL::zero(); let a = self; res[0] = a+b[0]; res[1] = b[1]; res } } // adds // multivector/scalar addition impl Add<float_t> for DUAL { type Output = DUAL; fn add(self: DUAL, b: float_t) -> DUAL { let mut res = DUAL::zero(); let a = self; res[0] = a[0]+b; res[1] = a[1]; res } } impl DUAL { pub fn norm(self: Self) -> float_t { let scalar_part = (self * self.Conjugate())[0]; scalar_part.abs().sqrt() } pub fn inorm(self: Self) -> float_t { self.Dual().norm() } pub fn normalized(self: Self) -> Self { self * (1.0 / self.norm()) } } fn main() { println!("e0*e0 : {}", e0 * e0); println!("pss : {}", e0); println!("pss*pss : {}", e0*e0); }
20.119205
95
0.493417
18c9d28822096dea2e87f99c5b33f3c06643242e
6,844
//! Manipulate lines of text and groups of lines. use crate::positions::SingleLineSpan; use lazy_static::lazy_static; use regex::Regex; use std::{cmp::max, fmt}; /// A distinct number type for line numbers, to prevent confusion with /// other numerical data. /// /// Zero-indexed internally. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct LineNumber(pub usize); impl LineNumber { pub fn one_indexed(&self) -> usize { self.0 + 1 } } impl fmt::Debug for LineNumber { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_fmt(format_args!("LineNumber: {}", self.0)) } } impl From<usize> for LineNumber { fn from(number: usize) -> Self { Self(number) } } pub fn format_line_num(line_num: LineNumber) -> String { format!("{} ", line_num.one_indexed()) } /// A position in a single line of a string. #[derive(Debug, PartialEq, Clone, Copy)] struct LinePosition { /// Both zero-indexed. pub line: LineNumber, column: usize, } /// A struct for efficiently converting absolute string positions to /// line-relative positions. #[derive(Debug)] pub struct NewlinePositions { /// A vector of the start positions of all the lines in `s`. positions: Vec<usize>, str_length: usize, } impl From<&str> for NewlinePositions { fn from(s: &str) -> Self { lazy_static! { static ref NEWLINE_RE: Regex = Regex::new("\n").unwrap(); } let mut positions: Vec<_> = NEWLINE_RE.find_iter(s).map(|mat| mat.end()).collect(); positions.insert(0, 0); NewlinePositions { positions, str_length: s.len(), } } } impl NewlinePositions { /// Convert to single-line spans. If the original span crosses a /// newline, the vec will contain multiple items. pub fn from_offsets(&self, region_start: usize, region_end: usize) -> Vec<SingleLineSpan> { let mut res = vec![]; for (line_num, line_start) in self.positions.iter().enumerate() { let line_end = match self.positions.get(line_num + 1) { // TODO: this assumes lines terminate with \n, not \r\n. Some(v) => *v - 1, None => self.str_length, }; if region_start > line_end { continue; } if *line_start > region_end { break; } res.push(SingleLineSpan { line: line_num.into(), start_col: if *line_start > region_start { 0 } else { region_start - line_start }, end_col: if region_end < line_end { region_end - line_start } else { line_end - line_start }, }); } res } pub fn from_offsets_relative_to( &self, start: SingleLineSpan, region_start: usize, region_end: usize, ) -> Vec<SingleLineSpan> { let mut res = vec![]; for pos in self.from_offsets(region_start, region_end) { if pos.line.0 == 0 { res.push(SingleLineSpan { line: start.line, start_col: start.start_col + pos.start_col, end_col: start.start_col + pos.end_col, }); } else { res.push(SingleLineSpan { line: (start.line.0 + pos.line.0).into(), start_col: pos.start_col, end_col: pos.end_col, }); } } res } } /// Return the length of `s` in codepoints. This is important when /// finding character boundaries for slicing without errors. pub fn codepoint_len(s: &str) -> usize { s.chars().count() } /// The first `len` codepoints of `s`. This is safer than slicing by /// bytes, which panics if the byte isn't on a codepoint boundary. pub fn substring_by_codepoint(s: &str, start: usize, end: usize) -> &str { let byte_start = s.char_indices().nth(start).unwrap().0; match s.char_indices().nth(end) { Some(byte_end) => &s[byte_start..byte_end.0], None => &s[byte_start..], } } pub trait MaxLine { fn max_line(&self) -> LineNumber; } impl<S: AsRef<str>> MaxLine for S { fn max_line(&self) -> LineNumber { (max(1, self.as_ref().lines().count()) - 1).into() } } #[cfg(test)] mod tests { use super::*; use pretty_assertions::assert_eq; #[test] fn from_offsets_first_line() { let newline_positions: NewlinePositions = "foo".into(); let line_spans = newline_positions.from_offsets(1, 3); assert_eq!( line_spans, vec![SingleLineSpan { line: 0.into(), start_col: 1, end_col: 3 }] ); } #[test] fn from_offsets_first_char() { let newline_positions: NewlinePositions = "foo".into(); let line_spans = newline_positions.from_offsets(0, 0); assert_eq!( line_spans, vec![SingleLineSpan { line: 0.into(), start_col: 0, end_col: 0 }] ); } #[test] fn from_offsets_split_over_multiple_lines() { let newline_positions: NewlinePositions = "foo\nbar\nbaz\naaaaaaaaaaa".into(); let line_spans = newline_positions.from_offsets(5, 10); assert_eq!( line_spans, vec![ (SingleLineSpan { line: 1.into(), start_col: 1, end_col: 3 }), (SingleLineSpan { line: 2.into(), start_col: 0, end_col: 2 }) ] ); } #[test] fn str_max_line() { let line: String = "foo\nbar".into(); assert_eq!(line.max_line().0, 1); } #[test] fn empty_str_max_line() { let line: String = "".into(); assert_eq!(line.max_line().0, 0); } #[test] fn from_offsets_relative_to() { let newline_positions: NewlinePositions = "foo\nbar".into(); let pos = SingleLineSpan { line: 1.into(), start_col: 1, end_col: 1, }; let line_spans = newline_positions.from_offsets_relative_to(pos, 1, 2); assert_eq!( line_spans, vec![SingleLineSpan { line: 1.into(), start_col: 2, end_col: 3 }] ); } #[test] fn codepoint_len_non_ascii() { assert_eq!(codepoint_len("ƒoo"), 3); } }
27.266932
95
0.527031
bf2b24066a1f9d3e3a64c9bc2ca803b6c4fa481d
4,589
#![cfg(all(test, feature = "test_e2e"))] mod setup; use azure_core::prelude::*; use azure_cosmos::prelude::*; use azure_cosmos::resources::collection::*; #[tokio::test] async fn create_and_delete_collection() { const DATABASE_NAME: &str = "test-cosmos-db-create-and-delete-collection"; const COLLECTION_NAME: &str = "test-collection-create-and-delete-collection"; let client = setup::initialize().unwrap(); client .create_database( azure_core::Context::new(), DATABASE_NAME, CreateDatabaseOptions::new(), ) .await .unwrap(); let database_client = client.into_database_client(DATABASE_NAME); // create a new collection let collection = database_client .create_collection( Context::new(), COLLECTION_NAME, CreateCollectionOptions::new("/id"), ) .await .unwrap(); let collections = database_client.list_collections().execute().await.unwrap(); assert!(collections.collections.len() == 1); // try to get the previously created collection let collection_client = database_client .clone() .into_collection_client(COLLECTION_NAME); let collection_after_get = collection_client .get_collection(Context::new(), GetCollectionOptions::new()) .await .unwrap(); assert!(collection.collection.rid == collection_after_get.collection.rid); // check GetPartitionKeyRanges: https://docs.microsoft.com/rest/api/cosmos-db/get-partition-key-ranges collection_client .get_partition_key_ranges() .execute() .await .unwrap(); // delete the collection collection_client .delete_collection(Context::new(), DeleteCollectionOptions::new()) .await .unwrap(); let collections = database_client.list_collections().execute().await.unwrap(); assert!(collections.collections.len() == 0); database_client.delete_database().execute().await.unwrap(); } #[tokio::test] async fn replace_collection() { let client = setup::initialize().unwrap(); const DATABASE_NAME: &str = "test-cosmos-db"; const COLLECTION_NAME: &str = "test-collection"; client .create_database( azure_core::Context::new(), DATABASE_NAME, CreateDatabaseOptions::new(), ) .await .unwrap(); let database_client = client.into_database_client(DATABASE_NAME); // create a new collection let indexing_policy = IndexingPolicy { automatic: true, indexing_mode: IndexingMode::Consistent, included_paths: vec![], excluded_paths: vec![], }; let options = CreateCollectionOptions::new("/id") .offer(Offer::S2) .indexing_policy(indexing_policy); let collection = database_client .create_collection(Context::new(), COLLECTION_NAME, options) .await .unwrap(); let collections = database_client.list_collections().execute().await.unwrap(); assert_eq!(collections.collections.len(), 1); assert_eq!( collection.collection.indexing_policy, collections.collections[0].indexing_policy ); // Let's change the indexing mode! let indexes = IncludedPathIndex { kind: KeyKind::Hash, data_type: DataType::String, precision: Some(3), }; let ip = IncludedPath { path: "/*".to_owned(), indexes: Some(vec![indexes]), }; let mut new_ip = IndexingPolicy { automatic: true, indexing_mode: IndexingMode::Consistent, included_paths: vec![ip], excluded_paths: vec![], }; new_ip .excluded_paths .push("/\"excludeme\"/?".to_owned().into()); let collection_client = database_client .clone() .into_collection_client(COLLECTION_NAME); let _replace_collection_response = collection_client .replace_collection( Context::new(), ReplaceCollectionOptions::new("/id").indexing_policy(new_ip), ) .await .unwrap(); let collections = database_client.list_collections().execute().await.unwrap(); assert_eq!(collections.collections.len(), 1); let eps: Vec<&ExcludedPath> = collections.collections[0] .indexing_policy .excluded_paths .iter() .filter(|excluded_path| excluded_path.path == "/\"excludeme\"/?") .collect(); assert!(eps.len() > 0); database_client.delete_database().execute().await.unwrap(); }
29.993464
106
0.633253
d7a6bd42ceef0a1ab54ae513c5d61b17f5dd1d7d
2,174
mod base; use crate::base::{ destroy, new_mma8451, new_mma8452, new_mma8453, new_mma8652, new_mma8653, BitFlags as BF, Register, ADDRESS, }; use embedded_hal_mock::i2c::Transaction as I2cTrans; use mma8x5x::DataStatus; macro_rules! get_data_status { ($name:ident, $create:ident, $bit_flag:ident, $status_flag:ident) => { get_test!( $name, $create, STATUS, BF::$bit_flag, data_status, DataStatus { $status_flag: true, ..DataStatus::default() } ); }; } macro_rules! tests { ($name:ident, $create:ident) => { mod $name { use super::*; get_test!( nothing, $create, STATUS, 0, data_status, DataStatus::default() ); get_test!( all, $create, STATUS, BF::XYZOW | BF::ZOW | BF::YOW | BF::XOW | BF::XYZDR | BF::ZDR | BF::YDR | BF::XDR, data_status, DataStatus { xyz_overwrite: true, z_overwrite: true, y_overwrite: true, x_overwrite: true, xyz_new_data: true, z_new_data: true, y_new_data: true, x_new_data: true, } ); get_data_status!(xyzow, $create, XYZOW, xyz_overwrite); get_data_status!(xow, $create, XOW, x_overwrite); get_data_status!(yow, $create, YOW, y_overwrite); get_data_status!(zow, $create, ZOW, z_overwrite); get_data_status!(xyzdr, $create, XYZDR, xyz_new_data); get_data_status!(xdr, $create, XDR, x_new_data); get_data_status!(ydr, $create, YDR, y_new_data); get_data_status!(zdr, $create, ZDR, z_new_data); } }; } tests!(mma8451, new_mma8451); tests!(mma8452, new_mma8452); tests!(mma8453, new_mma8453); tests!(mma8652, new_mma8652); tests!(mma8653, new_mma8653);
30.194444
98
0.49494
c16cec457709b0cc843321bbdff7d9318841be97
1,005
#[derive(Clone, Copy, Debug)] pub enum EntityError { None, BareError, VerifyFailed, InvalidInternalState, InvalidProof, ConsistencyError, ComplexEventsAreNotSupported, EventIdDoesntMatch, ProfileIdDoesntMatch, EmptyChange, ContactNotFound, EventNotFound, InvalidChainSequence, InvalidEventId, AttestationRequesterDoesntMatch, AttestationNonceDoesntMatch, InvalidHubResponse, InvalidParameter, SecureChannelVerificationFailed, SecureChannelCannotBeAuthenticated, } impl EntityError { /// Integer code associated with the error domain. pub const DOMAIN_CODE: u32 = 20_000; /// Descriptive name for the error domain. pub const DOMAIN_NAME: &'static str = "OCKAM_ENTITY"; } impl From<EntityError> for ockam_core::Error { fn from(e: EntityError) -> ockam_core::Error { ockam_core::Error::new( EntityError::DOMAIN_CODE + (e as u32), EntityError::DOMAIN_NAME, ) } }
25.125
57
0.695522
b9a172a8163c39663c1f3997b604369e6b18bfaf
15,237
use image::{ImageResult, RgbImage}; use mli::{Backward, Forward, Graph, Train}; use mli_conv::{Conv2n, Conv3}; use mli_defconv::DefConv2InternalOffsets; use mli_dense::Dense2; use mli_ndarray::{Map1One, Map2One, Map3One, Reshape3to2}; use mli_relu::Blu; use mli_sigmoid::Logistic; use mnist::{Mnist, MnistBuilder}; use ndarray::{Array, Array3, ArrayView, ArrayView3, OwnedRepr}; use rand_core::{RngCore, SeedableRng}; use rand_distr::{Distribution, Normal}; use rand_xoshiro::Xoshiro256PlusPlus; use std::path::{Path, PathBuf}; use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt(name = "mnist", about = "An example of using MLI to classify MNIST")] struct Opt { /// Number of epochs #[structopt(short = "t", default_value = "4000")] epochs: usize, /// Number of epochs per output image #[structopt(short = "s", default_value = "1000")] show_every: usize, /// Pre-start learning rate #[structopt(short = "p", default_value = "0.1")] prestart_learning_rate: f32, /// Pre-start learning samples #[structopt(short = "l", default_value = "20000")] prestart_learning_samples: usize, /// Initial learning rate #[structopt(short = "i", default_value = "0.1")] initial_learning_rate: f32, /// Learning rate multiplier per epoch #[structopt(short = "m", default_value = "0.99999")] learning_rate_multiplier: f32, /// Seed #[structopt(short = "z", default_value = "0")] seed: u64, /// Beta value for AdaMax NAG Momentum #[structopt(short = "b", default_value = "0.99")] betam: f32, /// Beta value for AdaMax NAG Variance #[structopt(short = "v", default_value = "0.999")] betav: f32, /// Directory containing the MNIST files #[structopt(parse(from_os_str))] mnist_dir: PathBuf, /// Output directory #[structopt(parse(from_os_str))] output_dir: PathBuf, } // fn sobel(image: &Array2<f32>) -> Array2<f32> { // let down_filter = array![[-1.0, -2.0, -1.0], [0.0, 0.0, 0.0], [1.0, 2.0, 1.0],]; // let right_filter = down_filter.t().to_owned(); // let down = Conv2::new(down_filter).forward(&image).1; // let right = Conv2::new(right_filter).forward(&image).1; // (down.map(|f| f.powi(2)) + right.map(|f| f.powi(2))).map(|f| f.sqrt()) // } // fn open_image(path: impl AsRef<Path>) -> ImageResult<Array2<f32>> { // let image = open_gray_image(path)?; // Ok(image.map(|&n| f32::from(n) / 255.0)) // } // fn save_image_internal(path: impl AsRef<Path>, image: &Array2<f32>) -> ImageResult<()> { // let image = image.map(|&n| num::clamp(n * 255.0, 0.0, 255.0) as u8); // save_gray_image(path, image.view()) // } fn save_image_color_internal(path: impl AsRef<Path>, image: &Array3<f32>) -> ImageResult<()> { let image = image.map(|&n| num::clamp(n * 255.0, 0.0, 255.0) as u8); if let [height, width, 3] = *image.shape() { let slice = image.as_slice().unwrap(); let image = RgbImage::from_raw(width as u32, height as u32, slice.to_vec()) .expect("failed to create image from raw vec"); image.save(path) } else { panic!("bad format image"); } } fn mnist_train(mnist: &Mnist) -> ArrayView3<'_, u8> { ArrayView::from_shape((60000, 28, 28), mnist.trn_img.as_slice()).expect("mnist data corrupted") } fn main() -> ImageResult<()> { let opt = Opt::from_args(); let mnist = MnistBuilder::new() .base_path(&opt.mnist_dir.display().to_string()) .label_format_digit() .finalize(); let train = mnist_train(&mnist).mapv(|u| u as f32 / 255.0); //////////////////////// // Defining the model // //////////////////////// let conv_layers = 2; let filter_radius = 1usize; let filter_depth = 2usize; let filter_area = (filter_radius * 2 + 1).pow(2); let filter_volume = filter_area * filter_depth; let num_outputs = 10; let dense_line = 28 - 2 * conv_layers * filter_radius; let dense_area = dense_line * dense_line; let dense_volume = dense_area * num_outputs; let defconv_total_strides = 28; let mut prng = make_prng(opt.seed); let mut prng_defconv = make_prng(prng.next_u64()); let mut random_defconv = |samples: usize, mean: f32, variance: f32| -> DefConv2InternalOffsets { // Xavier initialize by changing the variance to be 1/N where N is the area of the filter. DefConv2InternalOffsets::new( Array::from_iter( Normal::new(mean / samples as f32, variance / samples as f32) .unwrap() .sample_iter(&mut prng_defconv) .take(samples), ) .into_shape(samples) .unwrap(), Array::from_iter( Normal::new(0.0, 5.0) .unwrap() .sample_iter(&mut prng_defconv) .take(2 * samples), ) .into_shape((samples, 2)) .unwrap(), [defconv_total_strides, defconv_total_strides], ) }; // let mut prng_2filter = make_prng(prng.next_u32()); // let mut random_2filter = |mean: f32, variance: f32| -> Conv2<OwnedRepr<f32>> { // // Xavier initialize by changing the variance to be 1/N where N is the area of the filter. // Conv2::new( // Array::from_iter( // Normal::new(mean / filter_area as f32, variance / filter_area as f32) // .unwrap() // .sample_iter(&mut prng_2filter) // .take(filter_area), // ) // .into_shape((filter_radius * 2 + 1, filter_radius * 2 + 1)) // .unwrap(), // ) // }; let mut prng_2nfilter = make_prng(prng.next_u64()); let mut random_2nfilter = |mean: f32, variance: f32| -> Conv2n<OwnedRepr<f32>> { // Xavier initialize by changing the variance to be 1/N where N is the area of the filter. Conv2n::new( Array::from_iter( Normal::new(mean / filter_area as f32, variance / filter_area as f32) .unwrap() .sample_iter(&mut prng_2nfilter) .take(filter_volume), ) .into_shape((filter_depth, filter_radius * 2 + 1, filter_radius * 2 + 1)) .unwrap(), ) }; let mut prng_3filter = make_prng(prng.next_u64()); let mut random_3filter = |mean: f32, variance: f32| -> Conv3<OwnedRepr<f32>> { // Xavier initialize by changing the variance to be 1/N where N is the volume of the filter. Conv3::new( Array::from_iter( Normal::new(mean / filter_volume as f32, variance / filter_volume as f32) .unwrap() .sample_iter(&mut prng_3filter) .take(filter_volume), ) .into_shape((filter_depth, filter_radius * 2 + 1, filter_radius * 2 + 1)) .unwrap(), ) }; let mut prng_blu = make_prng(prng.next_u64()); let mut random_blu = |mean: f32, variance: f32| -> Blu { // Xavier initialize by changing the variance to be 1/N where N is the number of neurons. let distr = Normal::new(mean, variance).unwrap(); Blu::new(distr.sample(&mut prng_blu), distr.sample(&mut prng_blu)) }; let mut prng_dense2 = make_prng(prng.next_u64()); let mut random_dense2 = |mean: f32, variance: f32| -> Dense2<OwnedRepr<f32>> { // Xavier initialize by changing the variance to be 1/N where N is the area of the filter. Dense2::new( Array::from_iter( Normal::new(mean / filter_area as f32, variance / filter_area as f32) .unwrap() .sample_iter(&mut prng_dense2) .take(dense_volume), ) .into_shape((num_outputs, dense_line, dense_line)) .unwrap(), ) }; let mut generate_filter = || { random_defconv(10, 1.0, 0.5) .map(random_2nfilter(0.0, 4.0)) .map(Map3One(random_blu(0.0, 0.5))) .map(random_3filter(0.0, 4.0)) .map(Reshape3to2::new()) .map(Map2One(random_blu(0.0, 0.5))) .map(random_dense2(0.0, 4.0)) .map(Map1One(Logistic)) }; ////////////// // Training // ////////////// loop { let mut train_filter = generate_filter(); let mut learn_rate = opt.initial_learning_rate; // Weird hack to initialize the momentum to zero without knowing the shape of the ndarray in advance. let dummy_image = train.outer_iter().next().unwrap().to_owned(); let mut momentum = { let (internal, mut output) = train_filter.forward(&dummy_image); output *= 0.0; train_filter.backward_train(&dummy_image, &internal, &output) }; let mut last_loss = 0.0; let mut exponentially_decaying_loss_average = 0.0; let mut exponentially_decaying_accuracy_average = 0.0; let mut prestart = true; momentum *= 0.0f32; for i in 0..opt.epochs { // Iterate through every image in the epoch. for (sample_ix, (image, &label)) in train .outer_iter() .map(|a| a.to_owned()) .zip(mnist.trn_lbl.iter()) .enumerate() { // Compute beta * momentum. momentum *= opt.betam; train_filter.train(&momentum); let (internal, output) = train_filter.forward(&image); // Show the image if the frame is divisible by show_every. if sample_ix % opt.show_every == 0 { // Plot the sample locations from the deformable conv net in the center. let mut splat: Array3<f32> = Array::zeros([1024, 1024, 3]); let defconv = &((((((train_filter.0).0).0).0).0).0).0; // Get the weight distance so we can normalize the weights. let weight_distance = defconv .def_conv .weights .iter() .map(|&n| n.powi(2)) .sum::<f32>() .sqrt(); // Draw all the offsets and weights. for (offset, &weight) in defconv .offsets .0 .outer_iter() .zip(defconv.def_conv.weights.iter()) { let splat_offset = [ (offset[0] * 32.0 + splat.shape()[0] as f32 / 2.0).round(), (offset[1] * 32.0 + splat.shape()[1] as f32 / 2.0).round(), ]; if splat_offset[0] >= 0.0 && splat_offset[0] < splat.shape()[0] as f32 && splat_offset[1] >= 0.0 && splat_offset[1] < splat.shape()[1] as f32 { splat[[splat_offset[0] as usize, splat_offset[1] as usize, 0]] = weight / weight_distance; splat[[splat_offset[0] as usize, splat_offset[1] as usize, 1]] = 1.0 - weight / weight_distance; } } // Draw the splat for the epoch. save_image_color_internal( opt.output_dir .join(format!("splat{:03}_sample{:06}.png", i, sample_ix)), &splat, )?; } if i == opt.epochs - 1 { eprintln!("Finished!"); return Ok(()); } let output_len = output.len() as f32; let local_learn_rate = if prestart { if sample_ix > opt.prestart_learning_samples { prestart = false; } opt.prestart_learning_rate } else { let llr = learn_rate; learn_rate *= opt.learning_rate_multiplier; llr }; // Compute the loss for display only (we don't actually need the loss itself for backprop, just its derivative). let onehot = Array::from_iter((0..10).map(|n| if n == label { 1.0 } else { 0.0 })); let delta_loss = 2.0 * (output.clone() - &onehot); let loss = output .iter() .enumerate() .map(|(ix, &n)| { let expected = if ix == label as usize { 1.0 } else { 0.0 }; (n - expected).powi(2) }) .sum::<f32>() / output_len; exponentially_decaying_loss_average *= 0.999; exponentially_decaying_loss_average += loss * 0.001; exponentially_decaying_accuracy_average *= 0.999; let correct = output .iter() .enumerate() .max_by_key(|(_, &n)| float_ord::FloatOrd(n)) .unwrap() .0 == label as usize; if correct { exponentially_decaying_accuracy_average += 0.001; } if sample_ix % opt.show_every == 0 { eprintln!( "epoch {:03} sample {:06} loss: {} ({:+}%), accuracy: {}, learn_rate: {}", i, sample_ix, exponentially_decaying_loss_average, (exponentially_decaying_loss_average - last_loss) / last_loss * 100.0, exponentially_decaying_accuracy_average, local_learn_rate ); last_loss = exponentially_decaying_loss_average; } if !loss.is_normal() { eprintln!("abnormal loss at epoch {}; starting over", i); break; } // Compute the output delta. let mut output_delta = delta_loss; output_delta *= -local_learn_rate / output_len; // Compute the trainable variable delta. let mut train_delta = train_filter.backward_train(&image, &internal, &output_delta); // Make the train delta a small component. train_delta *= 1.0 - opt.betam; train_filter.train(&train_delta); // Add the small component to the momentum. momentum += train_delta; } } } } fn make_prng(seed: u64) -> Xoshiro256PlusPlus { Xoshiro256PlusPlus::seed_from_u64(seed) }
42.442897
128
0.514734
ab429255381664f06886123123d985fd84186720
16,753
//! Multi probe LSH use crate::data::{Integer, Numeric}; use crate::{prelude::*, utils::create_rng}; use fnv::FnvHashSet; use itertools::Itertools; use ndarray::prelude::*; use ndarray::stack; use num::{Float, One, Zero}; use rand::distributions::Uniform; use rand::seq::SliceRandom; use rand::Rng; use statrs::function::factorial::binomial; use std::cmp::Ordering; use std::collections::BinaryHeap; /// Query directed probing /// /// Implementation of paper: /// /// Liv, Q., Josephson, W., Whang, L., Charikar, M., & Li, K. (n.d.). /// Multi-Probe LSH: Efficient Indexing for High-Dimensional Similarity Search /// Retrieved from https://www.cs.princeton.edu/cass/papers/mplsh_vldb07.pdf pub trait QueryDirectedProbe<N, K> { fn query_directed_probe(&self, q: &[N], budget: usize) -> Result<Vec<Vec<K>>>; } /// Step wise probing pub trait StepWiseProbe<N, K>: VecHash<N, K> { fn step_wise_probe(&self, q: &[N], budget: usize, hash_len: usize) -> Result<Vec<Vec<K>>>; } impl<N> StepWiseProbe<N, i8> for SignRandomProjections<N> where N: Numeric, { fn step_wise_probe(&self, q: &[N], budget: usize, hash_len: usize) -> Result<Vec<Vec<i8>>> { let probing_seq = step_wise_probing(hash_len, budget, false); let original_hash = self.hash_vec_query(q); let a = probing_seq .iter() .map(|pertub| { original_hash .iter() .zip(pertub) .map( |(&original, &shift)| { if shift == 1 { original * -1 } else { original } }, ) .collect_vec() }) .collect_vec(); Ok(a) } } fn uniform_without_replacement<T: Copy>(bucket: &mut [T], n: usize) -> Vec<T> { // https://stackoverflow.com/questions/196017/unique-non-repeating-random-numbers-in-o1#196065 let mut max_idx = bucket.len() - 1; let mut rng = create_rng(0); let mut samples = Vec::with_capacity(n); for _ in 0..n { let idx = rng.sample(Uniform::new(0, max_idx)); debug_assert!(idx < bucket.len()); unsafe { samples.push(*bucket.get_unchecked(idx)); }; bucket.swap(idx, max_idx); max_idx -= 1; } samples } fn create_hash_permutation(hash_len: usize, n: usize) -> Vec<i8> { let mut permut = vec![0; hash_len]; let shift_options = [-1i8, 1]; let mut idx: Vec<usize> = (0..hash_len).collect(); let candidate_idx = uniform_without_replacement(&mut idx, n); let mut rng = create_rng(0); for i in candidate_idx { debug_assert!(i < permut.len()); let v = *shift_options.choose(&mut rng).unwrap(); // bounds check not needed as i cannot be larger than permut unsafe { *permut.get_unchecked_mut(i) += v } } permut } /// Retrieve perturbation indexes. Every index in a hash can be perturbed by +1 or -1. /// /// First retrieve all hashes where 1 index is changed, /// then all combinations where two indexes are changed etc. /// /// # Arguments /// * - `hash_length` The hash length is used to determine all the combinations of indexes that can be shifted. /// * - `n_perturbation` The number of indexes allowed to be changed. We generally first deplete /// * - `two_shifts` If true every index is changed by +1 and -1, else only by +1. fn step_wise_perturb( hash_length: usize, n_perturbations: usize, two_shifts: bool, ) -> impl Iterator<Item = Vec<(usize, i8)>> { let multiply; if two_shifts { multiply = 2 } else { multiply = 1 } let idx = 0..hash_length * multiply; let switchpoint = hash_length; let a = idx.combinations(n_perturbations).map(move |comb| { // return of comb are indexes and perturbations (-1 or +1). // where idx are the indexes that are perturbed. // if n_perturbations is 2 output could be: // comb -> [(0, -1), (3, 1)] // if n_perturbations is 4 output could be: // comb -> [(1, -1), (9, -1), (4, 1), (3, -1)] comb.iter() .map(|&i| { if i >= switchpoint { (i - switchpoint, -1) } else { (i, 1) } }) .collect_vec() }); a } /// Generates new hashes by step wise shifting one indexes. /// First all one index shifts are returned (these are closer to the original hash) /// then the two index shifts, three index shifts etc. /// /// This is done until the budget is depleted. fn step_wise_probing(hash_len: usize, mut budget: usize, two_shifts: bool) -> Vec<Vec<i8>> { let mut hash_perturbs = Vec::with_capacity(budget); let n = hash_len as u64; // number of combinations (indexes we allow to perturb) let mut k = 1; while budget > 0 && k <= n { // binomial coefficient // times two as we have -1 and +1. let multiply; if two_shifts { multiply = 2 } else { multiply = 1 } let n_combinations = binomial(n, k) as usize * multiply; step_wise_perturb(n as usize, k as usize, two_shifts) .take(budget as usize) .for_each(|v| { let mut new_perturb = vec![0; hash_len]; v.iter().for_each(|(idx, shift)| { debug_assert!(*idx < new_perturb.len()); let v = unsafe { new_perturb.get_unchecked_mut(*idx) }; *v += *shift; }); hash_perturbs.push(new_perturb) }); k += 1; budget -= n_combinations; } hash_perturbs } #[derive(PartialEq, Clone)] struct PerturbState<'a, N, K> where N: Numeric + Float + Copy, { // original sorted zj z: &'a [usize], // original xi(delta) distances: &'a [N], // selection of zjs // We start with the first one, as this is the lowest score. selection: Vec<usize>, switchpoint: usize, original_hash: Option<Vec<K>>, } impl<'a, N, K> PerturbState<'a, N, K> where N: Numeric + Float, K: Integer, { fn new(z: &'a [usize], distances: &'a [N], switchpoint: usize, hash: Vec<K>) -> Self { PerturbState { z, distances, selection: vec![0], switchpoint, original_hash: Some(hash), } } fn score(&self) -> N { let mut score = Zero::zero(); for &index in self.selection.iter() { debug_assert!(index < self.z.len()); let zj = unsafe { *self.z.get_unchecked(index) }; debug_assert!(zj < self.distances.len()); unsafe { score += self.distances.get_unchecked(zj).clone() }; } score } // map zj value to (i, delta) as in paper fn i_delta(&self) -> Vec<(usize, K)> { let mut out = Vec::with_capacity(self.z.len()); for &idx in self.selection.iter() { debug_assert!(idx < self.z.len()); let zj = unsafe { *self.z.get_unchecked(idx) }; let delta; let index; if zj >= self.switchpoint { delta = One::one(); index = zj - self.switchpoint; } else { delta = K::from_i8(-1).unwrap(); index = zj; } out.push((index, delta)) } out } fn check_bounds(&mut self, max: usize) -> Result<()> { if max == self.z.len() - 1 { Err(Error::Failed("Out of bounds".to_string())) } else { self.selection.push(max + 1); Ok(()) } } fn shift(&mut self) -> Result<()> { let max = self.selection.pop().unwrap(); self.check_bounds(max) } fn expand(&mut self) -> Result<()> { let max = self.selection[self.selection.len() - 1]; self.check_bounds(max) } fn gen_hash(&mut self) -> Vec<K> { let mut hash = self.original_hash.take().expect("hash already taken"); for (i, delta) in self.i_delta() { debug_assert!(i < hash.len()); let ptr = unsafe { hash.get_unchecked_mut(i) }; *ptr += delta } hash } } // implement ordering so that we can create a min heap impl<N, K> Ord for PerturbState<'_, N, K> where N: Numeric + Float, K: Integer, { fn cmp(&self, other: &PerturbState<N, K>) -> Ordering { self.partial_cmp(other).unwrap() } } impl<N, K> PartialOrd for PerturbState<'_, N, K> where N: Numeric + Float, K: Integer, { fn partial_cmp(&self, other: &PerturbState<N, K>) -> Option<Ordering> { other.score().partial_cmp(&self.score()) } } impl<N, K> Eq for PerturbState<'_, N, K> where N: Numeric + Float, K: Integer, { } macro_rules! impl_query_directed_probe { ($vechash:ident) => { impl<N, K> $vechash<N, K> where N: Numeric + Float, K: Integer, { /// Computes the distance between the query hash and the boundary of the slot r (W in the paper) /// /// As stated by Multi-Probe LSH paper: /// For δ ∈ {−1, +1}, let xi(δ) be the distance of q from the boundary of the slot fn distance_to_bound(&self, q: &[N], hash: Option<&Vec<K>>) -> (Array1<N>, Array1<N>) { let hash = match hash { None => self.hash_vec(q).to_vec(), Some(h) => h.iter().map(|&k| N::from(k).unwrap()).collect_vec(), }; let f = self.a.dot(&aview1(q)) + &self.b; let xi_min1 = f - &aview1(&hash) * self.r; let xi_plus1: Array1<N> = xi_min1.map(|x| self.r - *x); (xi_min1, xi_plus1) } } impl<N, K> QueryDirectedProbe<N, K> for $vechash<N, K> where N: Numeric + Float, K: Integer, { fn query_directed_probe(&self, q: &[N], budget: usize) -> Result<Vec<Vec<K>>> { // https://www.cs.princeton.edu/cass/papers/mplsh_vldb07.pdf // https://www.youtube.com/watch?v=c5DHtx5VxX8 let hash = self.hash_vec_query(q); let (xi_min, xi_plus) = self.distance_to_bound(q, Some(&hash)); // >= this point = +1 // < this point = -1 let switchpoint = xi_min.len(); let distances: Vec<N> = stack!(Axis(0), xi_min, xi_plus).to_vec(); // indexes of the least scores to the highest // all below is an argsort let z = distances.clone(); let mut z = z.iter().enumerate().collect::<Vec<_>>(); z.sort_unstable_by(|(_idx_a, a), (_idx_b, b)| a.partial_cmp(b).unwrap()); let z = z.iter().map(|(idx, _)| *idx).collect::<Vec<_>>(); let mut hashes = Vec::with_capacity(budget + 1); hashes.push(hash.clone()); // Algorithm 1 from paper let mut heap = BinaryHeap::new(); let a0 = PerturbState::new(&z, &distances, switchpoint, hash); heap.push(a0); for _ in 0..budget { let mut ai = match heap.pop() { Some(ai) => ai, None => { return Err(Error::Failed( "All query directed probing combinations depleted".to_string(), )) } }; let mut a_s = ai.clone(); let mut a_e = ai.clone(); if a_s.shift().is_ok() { heap.push(a_s); } if a_e.expand().is_ok() { heap.push(a_e); } hashes.push(ai.gen_hash()) } Ok(hashes) } } }; } impl_query_directed_probe!(L2); impl_query_directed_probe!(MIPS); impl<N, K, H, T> LSH<H, N, T, K> where N: Numeric, K: Integer, H: VecHash<N, K>, T: HashTables<N, K>, { pub fn multi_probe_bucket_union(&self, v: &[N]) -> Result<FnvHashSet<u32>> { self.validate_vec(v)?; let mut bucket_union = FnvHashSet::default(); // Check if hasher has implemented this trait. If so follow this more specialized path. // Only L2 should have implemented it. This is the trick to choose a different function // path for the L2 struct. let h0 = &self.hashers[0]; if h0.as_query_directed_probe().is_some() { for (i, hasher) in self.hashers.iter().enumerate() { if let Some(h) = hasher.as_query_directed_probe() { let hashes = h.query_directed_probe(v, self._multi_probe_budget)?; for hash in hashes { self.process_bucket_union_result(&hash, i, &mut bucket_union)? } } } } else if h0.as_step_wise_probe().is_some() { for (i, hasher) in self.hashers.iter().enumerate() { if let Some(h) = hasher.as_step_wise_probe() { let hashes = h.step_wise_probe(v, self._multi_probe_budget, self.n_projections)?; for hash in hashes { self.process_bucket_union_result(&hash, i, &mut bucket_union)? } } } } else { unimplemented!() } Ok(bucket_union) } } #[cfg(test)] mod test { use super::*; #[test] fn test_permutation() { let permut = create_hash_permutation(5, 3); println!("{:?}", permut); } #[test] fn test_step_wise_perturb() { let a = step_wise_perturb(4, 2, true); assert_eq!( vec![vec![(0, 1), (1, 1)], vec![(0, 1), (2, 1)]], a.take(2).collect_vec() ); } #[test] fn test_step_wise_probe() { let a = step_wise_probing(4, 20, true); assert_eq!(vec![1, 0, 0, 0], a[0]); assert_eq!(vec![0, 1, -1, 0], a[a.len() - 1]); } #[test] fn test_l2_xi_distances() { let l2 = L2::<f32>::new(4, 4., 3, 1); let (xi_min, xi_plus) = l2.distance_to_bound(&[1., 2., 3., 1.], None); assert_eq!(xi_min, arr1(&[2.0210547, 1.9154847, 0.89937115])); assert_eq!(xi_plus, arr1(&[1.9789453, 2.0845153, 3.1006289])); } #[test] fn test_perturbstate() { let distances = [1., 0.1, 3., 2., 9., 4., 0.8, 5.]; // argsort let z = vec![1, 6, 0, 3, 2, 5, 7, 4]; let switchpoint = 4; let a0 = PerturbState::new(&z, &distances, switchpoint, vec![0, 0, 0, 0]); // initial selection is the first zj [0] // This leads to: // distance/score: 0.1 // index: 1 // delta: -1 assert_eq!(a0.clone().gen_hash(), [0, -1, 0, 0]); assert_eq!(a0.score(), 0.1); assert_eq!(a0.selection, [0]); // after expansion operation selection is [0, 1] // This leads to: // distance/ score: 0.1 + 0.8 // index: [1, 2] // delta: [-1, 1] let mut ae = a0.clone(); ae.expand().unwrap(); assert_eq!(ae.gen_hash(), [0, -1, 1, 0]); assert_eq!(ae.score(), 0.1 + 0.8); assert_eq!(ae.selection, [0, 1]); // after shift operation selection is [1] // This leads to: // distance/ score: 0.8 // index: 2 // delta: 1 let mut a_s = a0.clone(); a_s.shift().unwrap(); assert_eq!(a_s.gen_hash(), [0, 0, 1, 0]); assert_eq!(a_s.score(), 0.8); assert_eq!(a_s.selection, [1]); } #[test] fn test_query_directed_probe() { let l2 = <L2>::new(4, 4., 3, 1); let hashes = l2.query_directed_probe(&[1., 2., 3., 1.], 4).unwrap(); println!("{:?}", hashes) } #[test] fn test_query_directed_bounds() { // if shift and expand operation have reached the end of the vecs an error should be returned let mut lsh = hi8::LshMem::new(2, 1, 1).multi_probe(1000).l2(4.).unwrap(); lsh.store_vec(&[1.]).unwrap(); assert!(lsh.query_bucket_ids(&[1.]).is_err()) } }
32.84902
111
0.511789
efda3b263cc97fae94f08fb2dda1522424763779
15,001
use crate::convert::TryFrom; use crate::mem; use crate::ops::{self, Add, Sub, Try}; use crate::usize; use super::{FusedIterator, TrustedLen}; /// Objects that can be stepped over in both directions. /// /// The `steps_between` function provides a way to efficiently compare /// two `Step` objects. #[unstable(feature = "step_trait", reason = "likely to be replaced by finer-grained traits", issue = "42168")] pub trait Step: Clone + PartialOrd + Sized { /// Returns the number of steps between two step objects. The count is /// inclusive of `start` and exclusive of `end`. /// /// Returns `None` if it is not possible to calculate `steps_between` /// without overflow. fn steps_between(start: &Self, end: &Self) -> Option<usize>; /// Replaces this step with `1`, returning itself. fn replace_one(&mut self) -> Self; /// Replaces this step with `0`, returning itself. fn replace_zero(&mut self) -> Self; /// Adds one to this step, returning the result. fn add_one(&self) -> Self; /// Subtracts one to this step, returning the result. fn sub_one(&self) -> Self; /// Adds a `usize`, returning `None` on overflow. fn add_usize(&self, n: usize) -> Option<Self>; /// Subtracts a `usize`, returning `None` on underflow. fn sub_usize(&self, n: usize) -> Option<Self> { // this default implementation makes the addition of `sub_usize` a non-breaking change let _ = n; unimplemented!() } } // These are still macro-generated because the integer literals resolve to different types. macro_rules! step_identical_methods { () => { #[inline] fn replace_one(&mut self) -> Self { mem::replace(self, 1) } #[inline] fn replace_zero(&mut self) -> Self { mem::replace(self, 0) } #[inline] fn add_one(&self) -> Self { Add::add(*self, 1) } #[inline] fn sub_one(&self) -> Self { Sub::sub(*self, 1) } } } macro_rules! step_impl_unsigned { ($($t:ty)*) => ($( #[unstable(feature = "step_trait", reason = "likely to be replaced by finer-grained traits", issue = "42168")] impl Step for $t { #[inline] fn steps_between(start: &$t, end: &$t) -> Option<usize> { if *start < *end { usize::try_from(*end - *start).ok() } else { Some(0) } } #[inline] #[allow(unreachable_patterns)] fn add_usize(&self, n: usize) -> Option<Self> { match <$t>::try_from(n) { Ok(n_as_t) => self.checked_add(n_as_t), Err(_) => None, } } #[inline] #[allow(unreachable_patterns)] fn sub_usize(&self, n: usize) -> Option<Self> { match <$t>::try_from(n) { Ok(n_as_t) => self.checked_sub(n_as_t), Err(_) => None, } } step_identical_methods!(); } )*) } macro_rules! step_impl_signed { ($( [$t:ty : $unsigned:ty] )*) => ($( #[unstable(feature = "step_trait", reason = "likely to be replaced by finer-grained traits", issue = "42168")] impl Step for $t { #[inline] fn steps_between(start: &$t, end: &$t) -> Option<usize> { if *start < *end { // Use .wrapping_sub and cast to unsigned to compute the // difference that may not fit inside the range of $t. usize::try_from(end.wrapping_sub(*start) as $unsigned).ok() } else { Some(0) } } #[inline] #[allow(unreachable_patterns)] fn add_usize(&self, n: usize) -> Option<Self> { match <$unsigned>::try_from(n) { Ok(n_as_unsigned) => { // Wrapping in unsigned space handles cases like // `-120_i8.add_usize(200) == Some(80_i8)`, // even though 200_usize is out of range for i8. let wrapped = (*self as $unsigned).wrapping_add(n_as_unsigned) as $t; if wrapped >= *self { Some(wrapped) } else { None // Addition overflowed } } Err(_) => None, } } #[inline] #[allow(unreachable_patterns)] fn sub_usize(&self, n: usize) -> Option<Self> { match <$unsigned>::try_from(n) { Ok(n_as_unsigned) => { // Wrapping in unsigned space handles cases like // `80_i8.sub_usize(200) == Some(-120_i8)`, // even though 200_usize is out of range for i8. let wrapped = (*self as $unsigned).wrapping_sub(n_as_unsigned) as $t; if wrapped <= *self { Some(wrapped) } else { None // Subtraction underflowed } } Err(_) => None, } } step_identical_methods!(); } )*) } step_impl_unsigned!(usize u8 u16 u32 u64 u128); step_impl_signed!([isize: usize] [i8: u8] [i16: u16]); step_impl_signed!([i32: u32] [i64: u64] [i128: u128]); macro_rules! range_exact_iter_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] impl ExactSizeIterator for ops::Range<$t> { } )*) } macro_rules! range_incl_exact_iter_impl { ($($t:ty)*) => ($( #[stable(feature = "inclusive_range", since = "1.26.0")] impl ExactSizeIterator for ops::RangeInclusive<$t> { } )*) } macro_rules! range_trusted_len_impl { ($($t:ty)*) => ($( #[unstable(feature = "trusted_len", issue = "37572")] unsafe impl TrustedLen for ops::Range<$t> { } )*) } macro_rules! range_incl_trusted_len_impl { ($($t:ty)*) => ($( #[unstable(feature = "trusted_len", issue = "37572")] unsafe impl TrustedLen for ops::RangeInclusive<$t> { } )*) } #[stable(feature = "rust1", since = "1.0.0")] impl<A: Step> Iterator for ops::Range<A> { type Item = A; #[inline] fn next(&mut self) -> Option<A> { if self.start < self.end { // We check for overflow here, even though it can't actually // happen. Adding this check does however help llvm vectorize loops // for some ranges that don't get vectorized otherwise, // and this won't actually result in an extra check in an optimized build. if let Some(mut n) = self.start.add_usize(1) { mem::swap(&mut n, &mut self.start); Some(n) } else { None } } else { None } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { match Step::steps_between(&self.start, &self.end) { Some(hint) => (hint, Some(hint)), None => (usize::MAX, None) } } #[inline] fn nth(&mut self, n: usize) -> Option<A> { if let Some(plus_n) = self.start.add_usize(n) { if plus_n < self.end { self.start = plus_n.add_one(); return Some(plus_n) } } self.start = self.end.clone(); None } #[inline] fn last(mut self) -> Option<A> { self.next_back() } #[inline] fn min(mut self) -> Option<A> { self.next() } #[inline] fn max(mut self) -> Option<A> { self.next_back() } } // These macros generate `ExactSizeIterator` impls for various range types. // Range<{u,i}64> and RangeInclusive<{u,i}{32,64,size}> are excluded // because they cannot guarantee having a length <= usize::MAX, which is // required by ExactSizeIterator. range_exact_iter_impl!(usize u8 u16 u32 isize i8 i16 i32); range_incl_exact_iter_impl!(u8 u16 i8 i16); // These macros generate `TrustedLen` impls. // // They need to guarantee that .size_hint() is either exact, or that // the upper bound is None when it does not fit the type limits. range_trusted_len_impl!(usize isize u8 i8 u16 i16 u32 i32 u64 i64 u128 i128); range_incl_trusted_len_impl!(usize isize u8 i8 u16 i16 u32 i32 u64 i64 u128 i128); #[stable(feature = "rust1", since = "1.0.0")] impl<A: Step> DoubleEndedIterator for ops::Range<A> { #[inline] fn next_back(&mut self) -> Option<A> { if self.start < self.end { self.end = self.end.sub_one(); Some(self.end.clone()) } else { None } } #[inline] fn nth_back(&mut self, n: usize) -> Option<A> { if let Some(minus_n) = self.end.sub_usize(n) { if minus_n > self.start { self.end = minus_n.sub_one(); return Some(self.end.clone()) } } self.end = self.start.clone(); None } } #[stable(feature = "fused", since = "1.26.0")] impl<A: Step> FusedIterator for ops::Range<A> {} #[stable(feature = "rust1", since = "1.0.0")] impl<A: Step> Iterator for ops::RangeFrom<A> { type Item = A; #[inline] fn next(&mut self) -> Option<A> { let mut n = self.start.add_one(); mem::swap(&mut n, &mut self.start); Some(n) } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { (usize::MAX, None) } #[inline] fn nth(&mut self, n: usize) -> Option<A> { let plus_n = self.start.add_usize(n).expect("overflow in RangeFrom::nth"); self.start = plus_n.add_one(); Some(plus_n) } } #[stable(feature = "fused", since = "1.26.0")] impl<A: Step> FusedIterator for ops::RangeFrom<A> {} #[unstable(feature = "trusted_len", issue = "37572")] unsafe impl<A: Step> TrustedLen for ops::RangeFrom<A> {} #[stable(feature = "inclusive_range", since = "1.26.0")] impl<A: Step> Iterator for ops::RangeInclusive<A> { type Item = A; #[inline] fn next(&mut self) -> Option<A> { self.compute_is_empty(); if self.is_empty.unwrap_or_default() { return None; } let is_iterating = self.start < self.end; self.is_empty = Some(!is_iterating); Some(if is_iterating { let n = self.start.add_one(); mem::replace(&mut self.start, n) } else { self.start.clone() }) } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { if self.is_empty() { return (0, Some(0)); } match Step::steps_between(&self.start, &self.end) { Some(hint) => (hint.saturating_add(1), hint.checked_add(1)), None => (usize::MAX, None), } } #[inline] fn nth(&mut self, n: usize) -> Option<A> { self.compute_is_empty(); if self.is_empty.unwrap_or_default() { return None; } if let Some(plus_n) = self.start.add_usize(n) { use crate::cmp::Ordering::*; match plus_n.partial_cmp(&self.end) { Some(Less) => { self.is_empty = Some(false); self.start = plus_n.add_one(); return Some(plus_n); } Some(Equal) => { self.is_empty = Some(true); return Some(plus_n); } _ => {} } } self.is_empty = Some(true); None } #[inline] fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B> { self.compute_is_empty(); if self.is_empty() { return Try::from_ok(init); } let mut accum = init; while self.start < self.end { let n = self.start.add_one(); let n = mem::replace(&mut self.start, n); accum = f(accum, n)?; } self.is_empty = Some(true); if self.start == self.end { accum = f(accum, self.start.clone())?; } Try::from_ok(accum) } #[inline] fn last(mut self) -> Option<A> { self.next_back() } #[inline] fn min(mut self) -> Option<A> { self.next() } #[inline] fn max(mut self) -> Option<A> { self.next_back() } } #[stable(feature = "inclusive_range", since = "1.26.0")] impl<A: Step> DoubleEndedIterator for ops::RangeInclusive<A> { #[inline] fn next_back(&mut self) -> Option<A> { self.compute_is_empty(); if self.is_empty.unwrap_or_default() { return None; } let is_iterating = self.start < self.end; self.is_empty = Some(!is_iterating); Some(if is_iterating { let n = self.end.sub_one(); mem::replace(&mut self.end, n) } else { self.end.clone() }) } #[inline] fn nth_back(&mut self, n: usize) -> Option<A> { self.compute_is_empty(); if self.is_empty.unwrap_or_default() { return None; } if let Some(minus_n) = self.end.sub_usize(n) { use crate::cmp::Ordering::*; match minus_n.partial_cmp(&self.start) { Some(Greater) => { self.is_empty = Some(false); self.end = minus_n.sub_one(); return Some(minus_n); } Some(Equal) => { self.is_empty = Some(true); return Some(minus_n); } _ => {} } } self.is_empty = Some(true); None } #[inline] fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R where Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B> { self.compute_is_empty(); if self.is_empty() { return Try::from_ok(init); } let mut accum = init; while self.start < self.end { let n = self.end.sub_one(); let n = mem::replace(&mut self.end, n); accum = f(accum, n)?; } self.is_empty = Some(true); if self.start == self.end { accum = f(accum, self.start.clone())?; } Try::from_ok(accum) } } #[stable(feature = "fused", since = "1.26.0")] impl<A: Step> FusedIterator for ops::RangeInclusive<A> {}
29.298828
94
0.500967
89867fb3b1017d7f5d5426d27aa7b58e851c5361
710
//! A simple event queue. This is a resource that stays inside the World and //! is used to store events before they're processed by the game state. use super::GameEvent; use std::collections::VecDeque; #[derive(Default)] pub struct EventQueue { events: VecDeque<Box<dyn GameEvent + Sync + Send>>, } impl EventQueue { pub fn push<T>(&mut self, event: T) where T: GameEvent + Sync + Send + 'static, { self.push_boxed(Box::new(event)); } pub fn push_boxed(&mut self, event: Box<dyn GameEvent + Sync + Send>) { self.events.push_back(event); } pub fn pop(&mut self) -> Option<Box<dyn GameEvent + Sync + Send>> { self.events.pop_front() } }
24.482759
76
0.635211
d6333cf4c431de4bfc54cf06ee0732ad695d6df1
3,455
#![recursion_limit="128"] mod api_dump; mod database; mod emitter_lua; mod emitter_rust; mod roblox_install; mod run_in_roblox; mod reflection_types; use std::{ collections::HashMap, path::PathBuf, error::Error, }; use serde_derive::Deserialize; use rbx_dom_weak::{RbxTree, RbxValue, RbxInstanceProperties}; use crate::{ run_in_roblox::{inject_plugin_main, run_in_roblox}, api_dump::Dump, database::ReflectionDatabase, }; static PLUGIN_MODEL: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/plugin.rbxmx")); #[derive(Debug, Deserialize)] #[serde(tag = "type")] enum PluginMessage { Version { version: [u32; 4], }, #[serde(rename_all = "camelCase")] DefaultProperties { class_name: String, properties: HashMap<String, RbxValue>, } } fn main() -> Result<(), Box<dyn Error>> { let (dump_source, dump) = Dump::read_with_source()?; let plugin = { let mut plugin = RbxTree::new(RbxInstanceProperties { name: String::from("generate_rbx_reflection plugin"), class_name: String::from("Folder"), properties: Default::default(), }); let root_id = plugin.get_root_id(); rbx_xml::decode(&mut plugin, root_id, PLUGIN_MODEL) .expect("Couldn't deserialize built-in plugin"); inject_plugin_main(&mut plugin); inject_api_dump(&mut plugin, dump_source); plugin }; let messages = run_in_roblox(&plugin); let mut default_properties = HashMap::new(); let mut studio_version = [0, 0, 0, 0]; for message in &messages { if let Ok(str) = std::str::from_utf8(message) { println!("{}", str); } let deserialized = serde_json::from_slice(&message) .expect("Couldn't deserialize message"); match deserialized { PluginMessage::Version { version } => { studio_version = version; } PluginMessage::DefaultProperties { class_name, properties } => { default_properties.insert(class_name, properties); } } } let database = ReflectionDatabase { dump, default_properties, studio_version, }; let rust_output_dir = { let mut rust_output_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); rust_output_dir.pop(); rust_output_dir.push("rbx_reflection"); rust_output_dir.push("src"); rust_output_dir }; let lua_output_dir = { let mut lua_output_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); lua_output_dir.pop(); lua_output_dir.push("rbx_dom_lua"); lua_output_dir.push("src"); lua_output_dir.push("ReflectionDatabase"); lua_output_dir }; emitter_rust::emit(&database, &rust_output_dir)?; emitter_lua::emit(&database, &lua_output_dir)?; Ok(()) } fn inject_api_dump(plugin: &mut RbxTree, source: String) { let root_id = plugin.get_root_id(); let dump_node = RbxInstanceProperties { class_name: String::from("StringValue"), name: String::from("ApiDump"), properties: { let mut properties = HashMap::new(); properties.insert( String::from("Value"), RbxValue::String { value: source }, ); properties }, }; plugin.insert_instance(dump_node, root_id); }
25.783582
87
0.606368
1ae9c6ad874102314f91c1e9f958274345ab44a4
10,265
use std::os::unix::io::RawFd; use std::mem; use std::ptr; use libc; use nix; use libc::{c_void, c_ulong, sigset_t, size_t}; use libc::{kill, signal}; use libc::{F_GETFD, F_SETFD, F_DUPFD_CLOEXEC, FD_CLOEXEC, MNT_DETACH}; use libc::{SIG_DFL, SIG_SETMASK}; use run::{ChildInfo, MAX_PID_LEN}; use error::ErrorCode as Err; // And at this point we've reached a special time in the life of the // child. The child must now be considered hamstrung and unable to // do anything other than syscalls really. // // ESPECIALLY YOU CAN NOT DO MEMORY (DE)ALLOCATIONS // // See better explanation at: // https://github.com/rust-lang/rust/blob/c1e865c/src/libstd/sys/unix/process.rs#L202 // // In particular ChildInfo is passed by refernce here to avoid // deallocating (parts of) it. pub unsafe fn child_after_clone(child: &ChildInfo) -> ! { let mut epipe = child.error_pipe; child.cfg.death_sig.as_ref().map(|&sig| { if libc::prctl(ffi::PR_SET_PDEATHSIG, sig as c_ulong, 0, 0, 0) != 0 { fail(Err::ParentDeathSignal, epipe); } }); // Now we must wait until parent set some environment for us. It's mostly // for uid_map/gid_map. But also used for attaching debugger and maybe // other things let mut wbuf = [0u8]; loop { // TODO(tailhook) put some timeout on this pipe? let rc = libc::read(child.wakeup_pipe, (&mut wbuf).as_ptr() as *mut c_void, 1); if rc == 0 { // Parent already dead presumably before we had a chance to // set PDEATHSIG, so just send signal ourself in that case if let Some(sig) = child.cfg.death_sig { kill(libc::getpid(), sig as i32); libc::_exit(127); } else { // In case we wanted to daemonize, just continue // // TODO(tailhook) not sure it's best thing to do. Maybe parent // failed to setup uid/gid map for us. Do we want to check // specific options? Or should we just always die? break; } } else if rc < 0 { let errno = nix::errno::errno(); if errno == libc::EINTR as i32 || errno == libc::EAGAIN as i32 { continue; } else { fail(Err::PipeError, errno); } } else { // Do we need to check that exactly one byte is received? break; } } // Move error pipe file descriptors in case they clobber stdio while epipe < 3 { let nerr = libc::fcntl(epipe, F_DUPFD_CLOEXEC, 3); if nerr < 0 { fail(Err::CreatePipe, epipe); } epipe = nerr; } for &(nstype, fd) in child.setns_namespaces { if libc::setns(fd, nstype.bits()) != 0 { fail(Err::SetNs, epipe); } } if !child.pid_env_vars.is_empty() { let mut buf = [0u8; MAX_PID_LEN+1]; let data = format_pid_fixed(&mut buf, libc::getpid()); for &(index, offset) in child.pid_env_vars { // we know that there are at least MAX_PID_LEN+1 bytes in buffer child.environ[index].offset(offset as isize) .copy_from(data.as_ptr() as *const i8, data.len()); } } child.pivot.as_ref().map(|piv| { if ffi::pivot_root(piv.new_root.as_ptr(), piv.put_old.as_ptr()) != 0 { fail(Err::ChangeRoot, epipe); } if libc::chdir(piv.workdir.as_ptr()) != 0 { fail(Err::ChangeRoot, epipe); } if piv.unmount_old_root { if libc::umount2(piv.old_inside.as_ptr(), MNT_DETACH) != 0 { fail(Err::ChangeRoot, epipe); } } }); child.chroot.as_ref().map(|chroot| { if libc::chroot(chroot.root.as_ptr()) != 0 { fail(Err::ChangeRoot, epipe); } if libc::chdir(chroot.workdir.as_ptr()) != 0 { fail(Err::ChangeRoot, epipe); } }); child.keep_caps.as_ref().map(|_| { // Don't use securebits because on older systems it doesn't work if libc::prctl(libc::PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0 { fail(Err::CapSet, epipe); } }); child.cfg.gid.as_ref().map(|&gid| { if libc::setgid(gid) != 0 { fail(Err::SetUser, epipe); } }); child.cfg.supplementary_gids.as_ref().map(|groups| { if libc::setgroups(groups.len() as size_t, groups.as_ptr()) != 0 { fail(Err::SetUser, epipe); } }); child.cfg.uid.as_ref().map(|&uid| { if libc::setuid(uid) != 0 { fail(Err::SetUser, epipe); } }); child.keep_caps.as_ref().map(|caps| { let header = ffi::CapsHeader { version: ffi::CAPS_V3, pid: 0, }; let data = ffi::CapsData { effective_s0: caps[0], permitted_s0: caps[0], inheritable_s0: caps[0], effective_s1: caps[1], permitted_s1: caps[1], inheritable_s1: caps[1], }; if libc::syscall(libc::SYS_capset, &header, &data) != 0 { fail(Err::CapSet, epipe); } for idx in 0..caps.len()*32 { if caps[(idx >> 5) as usize] & (1 << (idx & 31)) != 0 { let rc = libc::prctl( libc::PR_CAP_AMBIENT, libc::PR_CAP_AMBIENT_RAISE, idx, 0, 0); if rc != 0 && nix::errno::errno() == libc::ENOTSUP { // no need to iterate if ambient caps are notsupported break; } } } }); child.cfg.work_dir.as_ref().map(|dir| { if libc::chdir(dir.as_ptr()) != 0 { fail(Err::Chdir, epipe); } }); for &(dest_fd, src_fd) in child.fds { if src_fd == dest_fd { let flags = libc::fcntl(src_fd, F_GETFD); if flags < 0 || libc::fcntl(src_fd, F_SETFD, flags & !FD_CLOEXEC) < 0 { fail(Err::StdioError, epipe); } } else { if libc::dup2(src_fd, dest_fd) < 0 { fail(Err::StdioError, epipe); } } } for &(start, end) in child.close_fds { if start < end { for fd in start..end { if child.fds.iter().find(|&&(cfd, _)| cfd == fd).is_none() { // Close may fail with ebadf, and it's okay libc::close(fd); } } } } if child.cfg.restore_sigmask { let mut sigmask: sigset_t = mem::uninitialized(); libc::sigemptyset(&mut sigmask); libc::pthread_sigmask(SIG_SETMASK, &sigmask, ptr::null_mut()); for sig in 1..32 { signal(sig, SIG_DFL); } } if let Some(callback) = child.before_exec { if let Err(e) = callback() { fail_errno(Err::BeforeExec, e.raw_os_error().unwrap_or(10873289), epipe); } } libc::execve(child.filename, child.args.as_ptr(), // cancelling mutability, it should be fine child.environ.as_ptr() as *const *const i8); fail(Err::Exec, epipe); } unsafe fn fail(code: Err, output: RawFd) -> ! { fail_errno(code, nix::errno::errno(), output) } unsafe fn fail_errno(code: Err, errno: i32, output: RawFd) -> ! { let bytes = [ code as u8, (errno >> 24) as u8, (errno >> 16) as u8, (errno >> 8) as u8, (errno >> 0) as u8, // TODO(tailhook) rustc adds a special sentinel at the end of error // code. Do we really need it? Assuming our pipes are always cloexec'd. ]; // Writes less than PIPE_BUF should be atomic. It's also unclear what // to do if error happened anyway libc::write(output, bytes.as_ptr() as *const c_void, 5); libc::_exit(127); } fn format_pid_fixed<'a>(buf: &'a mut [u8], pid: libc::pid_t) -> &'a [u8] { buf[buf.len()-1] = 0; if pid == 0 { buf[buf.len()-2] = b'0'; return &buf[buf.len()-2..] } else { let mut tmp = pid; // can't use stdlib function because that can allocate for n in (0..buf.len()-1).rev() { buf[n] = (tmp % 10) as u8 + b'0'; tmp /= 10; if tmp == 0 { return &buf[n..]; } } unreachable!("can't format pid"); }; } /// We don't use functions from nix here because they may allocate memory /// which we can't to this this module. mod ffi { use libc::{c_char, c_int}; pub const PR_SET_PDEATHSIG: c_int = 1; pub const CAPS_V3: u32 = 0x20080522; #[repr(C)] pub struct CapsHeader { pub version: u32, pub pid: i32, } #[repr(C)] pub struct CapsData { pub effective_s0: u32, pub permitted_s0: u32, pub inheritable_s0: u32, pub effective_s1: u32, pub permitted_s1: u32, pub inheritable_s1: u32, } extern { pub fn pivot_root(new_root: *const c_char, put_old: *const c_char) -> c_int; } } #[cfg(test)] mod test { use rand::{thread_rng, Rng}; use run::MAX_PID_LEN; use std::ffi::CStr; use super::format_pid_fixed; fn fmt_normal(val: i32) -> String { let mut buf = [0u8; MAX_PID_LEN+1]; let slice = format_pid_fixed(&mut buf, val); return CStr::from_bytes_with_nul(slice).unwrap() .to_string_lossy().to_string(); } #[test] fn test_format() { assert_eq!(fmt_normal(0), "0"); assert_eq!(fmt_normal(1), "1"); assert_eq!(fmt_normal(7), "7"); assert_eq!(fmt_normal(79), "79"); assert_eq!(fmt_normal(254), "254"); assert_eq!(fmt_normal(1158), "1158"); assert_eq!(fmt_normal(77839), "77839"); } #[test] fn test_random() { for _ in 0..100000 { let x = thread_rng().gen(); if x < 0 { continue; } assert_eq!(fmt_normal(x), format!("{}", x)); } } }
30.918675
85
0.52187
fe5c770138fc718649e5d9d98f1f864830ba7802
233
#![feature(into_cow, associated_type_defaults)] #[macro_use] extern crate log; pub mod sqlsyntax; pub mod tempdb; mod byteutils; mod columnvalueops; mod databaseinfo; mod databasestorage; mod identifier; mod queryplan; mod types;
14.5625
47
0.7897
22a9f9a36e98fb472b393efb6648c099398f7f36
12,859
use coarsetime::{Clock, Duration, UnixTimeStamp}; use ct_codecs::{Base64UrlSafeNoPadding, Encoder}; use rand::RngCore; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use std::collections::HashSet; use std::convert::TryInto; use crate::common::VerificationOptions; use crate::error::*; use crate::serde_additions; pub const DEFAULT_TIME_TOLERANCE_SECS: u64 = 900; /// Type representing the fact that no application-defined claims is necessary. #[derive(Copy, Clone, Debug, Serialize, Deserialize)] pub struct NoCustomClaims {} /// Depending on applications, the `audiences` property may be either a set or a string. /// We support both. #[derive(Debug, Clone, Eq, PartialEq)] pub enum Audiences { AsSet(HashSet<String>), AsString(String), } impl Audiences { /// Return `true` if the audiences are represented as a set. pub fn is_set(&self) -> bool { matches!(self, Audiences::AsSet(_)) } /// Return `true` if the audiences are represented as a string. pub fn is_string(&self) -> bool { matches!(self, Audiences::AsString(_)) } /// Return `true` if the audiences include any of the `allowed_audiences` entries pub fn contains(&self, allowed_audiences: &HashSet<String>) -> bool { match self { Audiences::AsString(audience) => allowed_audiences.contains(audience), Audiences::AsSet(audiences) => { audiences.intersection(allowed_audiences).next().is_some() } } } /// Get the audiences as a set pub fn into_set(self) -> HashSet<String> { match self { Audiences::AsSet(audiences_set) => audiences_set, Audiences::AsString(audiences) => { let mut audiences_set = HashSet::new(); if !audiences.is_empty() { audiences_set.insert(audiences); } audiences_set } } } /// Get the audiences as a string. /// If it was originally serialized as a set, it can be only converted to a string if it contains at most one element. pub fn into_string(self) -> Result<String, Error> { match self { Audiences::AsString(audiences_str) => Ok(audiences_str), Audiences::AsSet(audiences) => { if audiences.len() > 1 { bail!(JWTError::TooManyAudiences); } Ok(audiences .iter() .next() .map(|x| x.to_string()) .unwrap_or_default()) } } } } impl TryInto<String> for Audiences { type Error = Error; fn try_into(self) -> Result<String, Error> { self.into_string() } } impl From<Audiences> for HashSet<String> { fn from(audiences: Audiences) -> HashSet<String> { audiences.into_set() } } impl<T: ToString> From<T> for Audiences { fn from(audience: T) -> Self { Audiences::AsString(audience.to_string()) } } /// A set of JWT claims. /// /// The `CustomClaims` parameter can be set to `NoCustomClaims` if only standard claims are used, /// or to a user-defined type that must be `serde`-serializable if custom claims are required. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct JWTClaims<CustomClaims> { /// Time the claims were created at #[serde( rename = "iat", default, skip_serializing_if = "Option::is_none", with = "self::serde_additions::unix_timestamp" )] pub issued_at: Option<UnixTimeStamp>, /// Time the claims expire at #[serde( rename = "exp", default, skip_serializing_if = "Option::is_none", with = "self::serde_additions::unix_timestamp" )] pub expires_at: Option<UnixTimeStamp>, /// Time the claims will be invalid until #[serde( rename = "nbf", default, skip_serializing_if = "Option::is_none", with = "self::serde_additions::unix_timestamp" )] pub invalid_before: Option<UnixTimeStamp>, /// Issuer - This can be set to anything application-specific #[serde(rename = "iss", default, skip_serializing_if = "Option::is_none")] pub issuer: Option<String>, /// Subject - This can be set to anything application-specific #[serde(rename = "sub", default, skip_serializing_if = "Option::is_none")] pub subject: Option<String>, /// Audience #[serde( rename = "aud", default, skip_serializing_if = "Option::is_none", with = "self::serde_additions::audiences" )] pub audiences: Option<Audiences>, /// JWT identifier /// /// That property was originally designed to avoid replay attacks, but keeping /// all previously sent JWT token IDs is unrealistic. /// /// Replay attacks are better addressed by keeping only the timestamp of the last /// valid token for a user, and rejecting anything older in future tokens. #[serde(rename = "jti", default, skip_serializing_if = "Option::is_none")] pub jwt_id: Option<String>, /// Nonce #[serde(rename = "nonce", default, skip_serializing_if = "Option::is_none")] pub nonce: Option<String>, /// Custom (application-defined) claims #[serde(flatten)] pub custom: CustomClaims, } impl<CustomClaims> JWTClaims<CustomClaims> { pub(crate) fn validate(&self, options: &VerificationOptions) -> Result<(), Error> { let now = Clock::now_since_epoch(); let time_tolerance = options .time_tolerance .unwrap_or_else(|| Duration::from_secs(DEFAULT_TIME_TOLERANCE_SECS)); if let Some(reject_before) = options.reject_before { ensure!(now <= reject_before, JWTError::OldTokenReused); } if let Some(time_issued) = self.issued_at { ensure!(time_issued <= now + time_tolerance, JWTError::ClockDrift); if let Some(max_validity) = options.max_validity { ensure!( now <= time_issued || now - time_issued <= max_validity, JWTError::TokenIsTooOld ); } } if !options.accept_future { if let Some(invalid_before) = self.invalid_before { ensure!(now >= invalid_before, JWTError::TokenNotValidYet); } } if let Some(expires_at) = self.expires_at { ensure!( now - time_tolerance <= expires_at, JWTError::TokenHasExpired ); } if let Some(allowed_issuers) = &options.allowed_issuers { if let Some(issuer) = &self.issuer { ensure!( allowed_issuers.contains(issuer), JWTError::RequiredIssuerMismatch ); } else { bail!(JWTError::RequiredIssuerMissing); } } if let Some(required_subject) = &options.required_subject { if let Some(subject) = &self.subject { ensure!( subject == required_subject, JWTError::RequiredSubjectMismatch ); } else { bail!(JWTError::RequiredSubjectMissing); } } if let Some(required_nonce) = &options.required_nonce { if let Some(nonce) = &self.nonce { ensure!(nonce == required_nonce, JWTError::RequiredNonceMismatch); } else { bail!(JWTError::RequiredNonceMissing); } } if let Some(allowed_audiences) = &options.allowed_audiences { if let Some(audiences) = &self.audiences { ensure!( audiences.contains(allowed_audiences), JWTError::RequiredAudienceMismatch ); } else { bail!(JWTError::RequiredAudienceMissing); } } Ok(()) } /// Set the token as not being valid until `unix_timestamp` pub fn invalid_before(mut self, unix_timestamp: UnixTimeStamp) -> Self { self.invalid_before = Some(unix_timestamp); self } /// Set the issuer pub fn with_issuer(mut self, issuer: impl ToString) -> Self { self.issuer = Some(issuer.to_string()); self } /// Set the subject pub fn with_subject(mut self, subject: impl ToString) -> Self { self.subject = Some(subject.to_string()); self } /// Register one or more audiences (optional recipient identifiers), as a set pub fn with_audiences(mut self, audiences: HashSet<impl ToString>) -> Self { self.audiences = Some(Audiences::AsSet( audiences.iter().map(|x| x.to_string()).collect(), )); self } /// Set a unique audience (an optional recipient identifier), as a string pub fn with_audience(mut self, audience: impl ToString) -> Self { self.audiences = Some(Audiences::AsString(audience.to_string())); self } /// Set the JWT identifier pub fn with_jwt_id(mut self, jwt_id: impl ToString) -> Self { self.jwt_id = Some(jwt_id.to_string()); self } /// Set the nonce pub fn with_nonce(mut self, nonce: impl ToString) -> Self { self.nonce = Some(nonce.to_string()); self } /// Create a nonce, attach it and return it pub fn create_nonce(&mut self) -> String { let mut raw_nonce = [0u8; 24]; let mut rng = rand::thread_rng(); rng.fill_bytes(&mut raw_nonce); let nonce = Base64UrlSafeNoPadding::encode_to_string(raw_nonce).unwrap(); self.nonce = Some(nonce); self.nonce.as_deref().unwrap().to_string() } } pub struct Claims; impl Claims { /// Create a new set of claims, without custom data, expiring in `valid_for`. pub fn create(valid_for: Duration) -> JWTClaims<NoCustomClaims> { let now = Some(Clock::now_since_epoch()); JWTClaims { issued_at: now, expires_at: Some(now.unwrap() + valid_for), invalid_before: now, audiences: None, issuer: None, jwt_id: None, subject: None, nonce: None, custom: NoCustomClaims {}, } } /// Create a new set of claims, with custom data, expiring in `valid_for`. pub fn with_custom_claims<CustomClaims: Serialize + DeserializeOwned>( custom_claims: CustomClaims, valid_for: Duration, ) -> JWTClaims<CustomClaims> { let now = Some(Clock::now_since_epoch()); JWTClaims { issued_at: now, expires_at: Some(now.unwrap() + valid_for), invalid_before: now, audiences: None, issuer: None, jwt_id: None, subject: None, nonce: None, custom: custom_claims, } } /// Create a new set of claims, with custom data, expiring in `valid_for` and starts in invalid_before. pub fn with_custom_claims_given_valid_period<CustomClaims: Serialize + DeserializeOwned>( custom_claims: CustomClaims, invalid_before: UnixTimeStamp, valid_for: Duration, ) -> JWTClaims<CustomClaims> { let now = Some(Clock::now_since_epoch()); JWTClaims { issued_at: now, expires_at: Some(invalid_before + valid_for), invalid_before: Some(invalid_before), audiences: None, issuer: None, jwt_id: None, subject: None, nonce: None, custom: custom_claims, } } } #[cfg(test)] mod tests { use super::*; #[test] fn should_set_standard_claims() { let exp = Duration::from_mins(10); let mut audiences = HashSet::new(); audiences.insert("audience1".to_string()); audiences.insert("audience2".to_string()); let claims = Claims::create(exp) .with_audiences(audiences.clone()) .with_issuer("issuer") .with_jwt_id("jwt_id") .with_nonce("nonce") .with_subject("subject"); assert_eq!(claims.audiences, Some(Audiences::AsSet(audiences))); assert_eq!(claims.issuer, Some("issuer".to_owned())); assert_eq!(claims.jwt_id, Some("jwt_id".to_owned())); assert_eq!(claims.nonce, Some("nonce".to_owned())); assert_eq!(claims.subject, Some("subject".to_owned())); } #[test] fn parse_floating_point_unix_time() { let claims: JWTClaims<()> = serde_json::from_str(r#"{"exp":1617757825.8}"#).unwrap(); assert_eq!( claims.expires_at, Some(UnixTimeStamp::from_secs(1617757825)) ); } }
33.486979
122
0.587448
18c450583160c7e6ca3697c9c8a0870090161a36
1,812
use crate::{Bundle, Component, DynamicBundle, Entity, World}; /// Converts a reference to `Self` to a [WorldBuilder] pub trait WorldBuilderSource { fn build(&mut self) -> WorldBuilder; } impl WorldBuilderSource for World { fn build(&mut self) -> WorldBuilder { WorldBuilder { world: self, current_entity: None, } } } /// Modify a [World] using the builder pattern #[derive(Debug)] pub struct WorldBuilder<'a> { pub world: &'a mut World, pub current_entity: Option<Entity>, } impl<'a> WorldBuilder<'a> { pub fn entity(&mut self) -> &mut Self { self.current_entity = Some(self.world.reserve_entity()); self } pub fn set_entity(&mut self, entity: Entity) -> &mut Self { self.current_entity = Some(entity); self } pub fn with<T>(&mut self, component: T) -> &mut Self where T: Component, { self.world .insert_one(self.current_entity.expect("Cannot add component because the 'current entity' is not set. You should spawn an entity first."), component) .unwrap(); self } pub fn with_bundle(&mut self, components: impl DynamicBundle) -> &mut Self { self.world .insert(self.current_entity.expect("Cannot add component because the 'current entity' is not set. You should spawn an entity first."), components) .unwrap(); self } pub fn spawn_batch<I>(&mut self, components_iter: I) -> &mut Self where I: IntoIterator, I::Item: Bundle, { self.world.spawn_batch(components_iter); self } pub fn spawn(&mut self, components: impl DynamicBundle) -> &mut Self { self.current_entity = Some(self.world.spawn(components)); self } }
27.454545
161
0.610375
91dcb62233b07ddc4cd789be979383282c14a31e
428
extern crate reqwest; use crate::config::{base_transaction_service_url, build_number, version}; use crate::models::service::about::About; use crate::utils::errors::ApiResult; pub fn get_about() -> ApiResult<About> { Ok(About { transaction_service_base_url: base_transaction_service_url(), name: env!("CARGO_PKG_NAME").to_string(), version: version(), build_number: build_number(), }) }
28.533333
73
0.693925
ffe25a57a1081b80d40f5d0e795db17efbf18f17
1,330
// Copyright 2021 The Grin Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use self::core::genesis; use grin_core as core; use grin_util as util; mod chain_test_helper; use self::chain_test_helper::{clean_output_dir, init_chain, mine_chain}; #[test] fn data_files() { util::init_test_logger(); let chain_dir = ".grin_df"; clean_output_dir(chain_dir); // Mine a few blocks on a new chain. { let chain = mine_chain(chain_dir, 4); chain.validate(false).unwrap(); assert_eq!(chain.head().unwrap().height, 3); }; // Now reload the chain from existing data files and check it is valid. { let chain = init_chain(chain_dir, genesis::genesis_dev()); chain.validate(false).unwrap(); assert_eq!(chain.head().unwrap().height, 3); } // Cleanup chain directory clean_output_dir(chain_dir); }
28.297872
75
0.728571
f9bc4420cd69309ab0c94a2d0a4cb8efd01860dc
1,345
extern crate bindgen; use cmake::Config; use std::env; use std::path::PathBuf; fn main() { // Generate bindings for RediSearch let bindings = bindgen::Builder::default() .header("src/include/redisearch_api.h") //.clang_arg("-I src/include") // For redismodule.h .whitelist_var("(RS|RediSearch|REDISEARCH_|GC_POLICY).*") .whitelist_function("RediSearch.*") .blacklist_item("RedisModule.*") .blacklist_type("__darwin_.*") .size_t_is_usize(true) .raw_line("use redis_module::raw::{RedisModuleCtx, RedisModuleString};") .generate() .expect("error generating RediSearch bindings"); let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); bindings .write_to_file(out_path.join("bindings.rs")) .expect("failed to write bindings to file"); // Find and link statically to libredisearch.a // TODO: Consider splitting the low level libredisearch wrapper off into a separate `-sys` crate. let mut dst = Config::new("RediSearch") .define("RS_BUILD_STATIC", "ON") .define("GIT_DESCRIBE_VERSION", "0.0.0") .build_target("redisearchS") .build(); dst.push("build"); println!("cargo:rustc-link-search=native={}", dst.display()); println!("cargo:rustc-link-lib=static=redisearch"); }
32.804878
101
0.645353
acf0667fd0e463bf7d1828698c297195ab15d5ec
56,725
// Copyright Materialize, Inc. and contributors. All rights reserved. // // Use of this software is governed by the Business Source License // included in the LICENSE file. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0. //! Data structures stored in Blobs and Logs in serialized form. // NB: Everything starting with Blob* is directly serialized as a Blob value. // Ditto for Log* and the Log. The others are used internally in these top-level // structs. use std::cmp::Ordering; use std::collections::{HashMap, HashSet}; use std::fmt; use std::io::Cursor; use std::ops::Range; use bytes::BufMut; use differential_dataflow::trace::Description; use ore::cast::CastFrom; use persist_types::Codec; use prost::Message; use semver::Version; use serde::{Deserialize, Serialize}; use timely::progress::{Antichain, Timestamp}; use timely::PartialOrder; use crate::error::Error; use crate::gen::persist::{ proto_batch_inline, ProtoArrangement, ProtoBatchFormat, ProtoBatchInline, ProtoMeta, ProtoStreamRegistration, ProtoTraceBatchInline, ProtoTraceBatchMeta, ProtoU64Antichain, ProtoU64Description, ProtoUnsealedBatchInline, ProtoUnsealedBatchMeta, }; use crate::indexed::columnar::parquet::{ decode_trace_parquet, decode_unsealed_parquet, encode_trace_parquet, encode_unsealed_parquet, }; use crate::indexed::columnar::ColumnarRecords; use crate::storage::SeqNo; /// An internally unique id for a persisted stream. External users identify /// streams with a string, which is then mapped internally to this. #[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct Id(pub u64); /// The structure serialized and stored as an entry in a /// [crate::storage::Log]. /// /// Invariants: /// - The updates field is non-empty. #[derive(Debug, Serialize, Deserialize)] pub struct LogEntry { /// Pairs of stream id and the updates themselves. // // We could require that each Id is included at most once, but at the // moment, there's no particular reason we'd need to. pub updates: Vec<(Id, Vec<((Vec<u8>, Vec<u8>), u64, isize)>)>, } /// The structure serialized and stored as a value in [crate::storage::Blob] /// storage for metadata keys. /// /// Invariants: /// - All strings in id_mapping are unique. /// - All ids in id_mapping are unique. /// - All strings in graveyard are unique. /// - All ids in graveyard are unique. /// - None of the strings in graveyard are present in any of the (string, id) /// tuples in id_mapping. /// - None of the ids in graveyard are present in any of the (string, id) tuples /// in id_mapping. /// - The same set of ids are present in id_mapping, unsealeds, and traces. /// - For each id, the ts_lower in the unsealed is <= the ts_upper in the /// corresponding trace. (This is less than equals and not strictly equals /// because truncating the unnecessary elements out of unsealed is fallible, and /// is allowed to lag behind the migration of new data into trace) /// - id_mapping.len() + graveyard.len() is == next_stream_id. /// - All of the keys for trace and unsealed batches are unique across all persisted /// streams. #[derive(Clone, Debug, Eq, PartialEq)] pub struct BlobMeta { /// Which mutations are included in the represented state. /// /// Persist is a state machine, with all mutating requests modeled as input /// state changes sequenced into a log. Periodically those state changes are /// applied and the resulting state is written out to blob storage. This /// field indicates which prefix of the log (`0..=self.seqno`) has been /// included in the state represented by this BlobMeta. SeqNo(0) represents /// the initial empty state, the first mutation is SeqNo(1). /// /// Invariant: For each UnsealedMeta in `unsealeds`, this is >= the last /// batch's upper. If they are not equal, there is logically an empty batch /// between [last batch's upper, self.seqno). pub seqno: SeqNo, /// Internal stream id indexed by external stream name. /// /// Invariant: Each stream name and stream id are in here at most once. pub id_mapping: Vec<StreamRegistration>, /// Set of deleted streams, indexed by external stream name. pub graveyard: Vec<StreamRegistration>, /// Arrangements indexed by stream id. /// /// Invariant: Each stream id is in here at most once. pub arrangements: Vec<ArrangementMeta>, } /// Registration information for a single stream. #[derive(Clone, Debug, Eq, PartialEq)] pub struct StreamRegistration { /// The external stream name. pub name: String, /// The internal stream id. pub id: Id, /// The codec used to encode and decode keys in this stream. pub key_codec_name: String, /// The codec used to encode and decode values in this stream. pub val_codec_name: String, } /// The metadata necessary to reconstruct an Arrangement. /// /// Invariants: /// - The unsealed_batch SeqNo ranges are sorted and non-overlapping. /// - The trace_batch Descriptions are sorted, non-overlapping, and contiguous. /// - Every batch's since frontier is <= the overall trace's since frontier. /// - The compaction level of trace_batches is weakly decreasing when iterating /// from oldest to most recent time intervals. /// - Every trace_batch's upper is <= the overall trace's seal frontier. #[derive(Clone, Debug, Eq, PartialEq)] pub struct ArrangementMeta { /// The stream this unsealed belongs to. pub id: Id, /// Frontier this trace has been sealed up to. pub seal: Antichain<u64>, /// Compaction frontier for the batches contained in this trace. /// There may still be batches containing updates at times < since, but the /// the trace only contains correct answers for times at or in advance of this /// of this frontier. Readers are expected to advance any updates < since to /// since. pub since: Antichain<u64>, /// The batches that make up the Unsealed. pub unsealed_batches: Vec<UnsealedBatchMeta>, /// The batches that make up the Trace. pub trace_batches: Vec<TraceBatchMeta>, } /// The metadata necessary to reconstruct a [BlobUnsealedBatch]. /// /// Invariants: /// - The [lower, upper) interval of sequence numbers in desc is non-empty. #[derive(Clone, Debug, Eq, PartialEq)] pub struct UnsealedBatchMeta { /// The key to retrieve the [BlobUnsealedBatch] from blob storage. pub key: String, /// The format of the stored batch data. pub format: ProtoBatchFormat, /// Half-open interval [lower, upper) of sequence numbers that this batch /// contains updates for. pub desc: Range<SeqNo>, /// The maximum timestamp of any update contained in this batch. pub ts_upper: u64, /// The minimum timestamp from any update contained in this batch. pub ts_lower: u64, /// Size of the encoded batch. pub size_bytes: u64, } /// The metadata necessary to reconstruct a [BlobTraceBatch]. /// /// Invariants: /// - The Description's time interval is non-empty. /// - TODO: key invariants? #[derive(Clone, Debug, Eq, PartialEq)] pub struct TraceBatchMeta { /// The key to retrieve the batch's data from the blob store. pub key: String, /// The format of the stored batch data. pub format: ProtoBatchFormat, /// The half-open time interval `[lower, upper)` this batch contains data /// for. pub desc: Description<u64>, /// The compaction level of each batch. pub level: u64, /// Size of the encoded batch. pub size_bytes: u64, } /// The structure serialized and stored as a value in [crate::storage::Blob] /// storage for data keys corresponding to unsealed data. /// /// Invariants: /// - The [lower, upper) interval of sequence numbers in desc is non-empty. /// - The updates field is non-empty. #[derive(Clone, Debug)] pub struct BlobUnsealedBatch { /// Which updates are included in this batch. pub desc: Range<SeqNo>, /// The updates themselves. pub updates: Vec<ColumnarRecords>, } /// The structure serialized and stored as a value in [crate::storage::Blob] /// storage for data keys corresponding to trace data. /// /// This batch represents the data that was originally written at some time in /// [lower, upper) (more precisely !< lower and < upper). The individual record /// times may have later been advanced by compaction to something <= since. /// This means the ability to reconstruct the state of the collection at times < since /// has been lost. However, there may still be records present in the batch whose /// times are < since. Users iterating through updates must take care to advance /// records with times < since to since in order to correctly answer queries at /// times >= since. /// /// Invariants: /// - The [lower, upper) interval of times in desc is non-empty. /// - The timestamp of each update is >= to desc.lower(). /// - The timestamp of each update is < desc.upper() iff desc.upper() > desc.since(). /// Otherwise the timestamp of each update is <= desc.since(). /// - The values in updates are sorted by (key, value, time). /// - The values in updates are "consolidated", i.e. (key, value, time) is /// unique. /// - All entries have a non-zero diff. /// - (Intentionally no invariant around update non-emptiness because we might /// need empty batches to make the timestamps line up.) /// /// TODO: This probably wants to be a different level of abstraction, so we can /// put multiple small batches in a single blob but also break a very large /// batch over multiple blobs. We also may want to break the latter into chunks /// for checksum and encryption? #[derive(Clone, Debug)] pub struct BlobTraceBatch { /// Which updates are included in this batch. pub desc: Description<u64>, /// The updates themselves. pub updates: Vec<ColumnarRecords>, } impl LogEntry { /// Asserts Self's documented invariants, returning an error if any are /// violated. pub fn validate(&self) -> Result<(), Error> { // TODO: It's unclear if this invariant is useful/harmful. Feel free to // remove it if it ends up not making sense. if self.updates.is_empty() { return Err("updates is empty".into()); } Ok(()) } } impl Default for BlobMeta { fn default() -> Self { BlobMeta { seqno: SeqNo(0), id_mapping: Vec::new(), graveyard: Vec::new(), arrangements: Vec::new(), } } } impl BlobMeta { /// Asserts Self's documented invariants, returning an error if any are /// violated. pub fn validate(&self) -> Result<(), Error> { let mut ids = HashSet::new(); let mut names = HashSet::new(); for r in self.id_mapping.iter() { if names.contains(&r.name) { return Err(format!("duplicate external stream name: {}", r.name).into()); } names.insert(r.name.clone()); if ids.contains(&r.id) { return Err(format!("duplicate internal stream id: {:?}", r.id).into()); } ids.insert(r.id); } let mut deleted_ids = HashSet::new(); let mut deleted_names = HashSet::new(); for r in self.graveyard.iter() { if names.contains(&r.name) { return Err(format!( "duplicate external stream name {} across deleted and registered streams", r.name ) .into()); } if ids.contains(&r.id) { return Err(format!( "duplicate internal stream id {:?} across deleted and registered streams", r.id ) .into()); } if deleted_names.contains(&r.name) { return Err(format!("duplicate deleted external stream name: {}", r.name).into()); } deleted_names.insert(r.name.clone()); if deleted_ids.contains(&r.id) { return Err(format!("duplicate deleted internal stream id: {:?}", r.id).into()); } deleted_ids.insert(r.id); } let next_stream_id = self.next_stream_id(); if u64::cast_from(deleted_ids.len() + ids.len()) != next_stream_id.0 { return Err(format!( "next stream {:?}, but only registered {} ids and deleted {} ids", next_stream_id, ids.len(), deleted_ids.len() ) .into()); } let mut arrangements = HashMap::new(); for f in self.arrangements.iter() { if !ids.contains(&f.id) { return Err(format!("arrangements id {:?} not present in id_mapping", f.id).into()); } if arrangements.contains_key(&f.id) { return Err(format!("duplicate arrangement: {:?}", f.id).into()); } arrangements.insert(f.id, f); f.validate()?; } for id in ids.iter() { let arrangement = arrangements.get(id).ok_or_else(|| { Error::from(format!( "id_mapping id {:?} not present in arrangements", id )) })?; let unsealed_seqno_upper = arrangement.unsealed_seqno_upper(); if !unsealed_seqno_upper.less_equal(&self.seqno) { return Err(Error::from(format!( "id {:?} unsealed seqno_upper {:?} is not less or equal to the blob's seqno {:?}", id, unsealed_seqno_upper, self.seqno, ))); } } let mut batch_keys = HashSet::new(); for a in self.arrangements.iter() { for batch in a.unsealed_batches.iter() { if batch_keys.contains(&batch.key) { return Err( format!("duplicate batch key found in unsealed: {}", batch.key).into(), ); } batch_keys.insert(batch.key.clone()); } for batch in a.trace_batches.iter() { if batch_keys.contains(&batch.key) { return Err(format!("duplicate batch key found in trace: {}", batch.key).into()); } batch_keys.insert(batch.key.clone()); } } Ok(()) } /// The next Id to issue for a stream being added to id_mapping. pub fn next_stream_id(&self) -> Id { let current_highest = self .id_mapping .iter() .chain(self.graveyard.iter()) .map(|s| s.id) .max(); current_highest.map_or(Id(0), |id| Id(id.0 + 1)) } } impl Default for ArrangementMeta { fn default() -> Self { ArrangementMeta { id: Id(0), since: Antichain::from_elem(Timestamp::minimum()), seal: Antichain::from_elem(Timestamp::minimum()), unsealed_batches: Vec::new(), trace_batches: Vec::new(), } } } impl ArrangementMeta { /// Create a new [ArrangementMeta] belonging to `id`. pub fn new(id: Id) -> Self { ArrangementMeta { id, ..Default::default() } } /// Asserts Self's documented invariants, returning an error if any are /// violated. pub fn validate(&self) -> Result<(), Error> { let mut unsealed_prev: Option<&UnsealedBatchMeta> = None; for meta in self.unsealed_batches.iter() { meta.validate()?; if let Some(prev) = unsealed_prev { if prev.desc.end > meta.desc.start { return Err(format!( "invalid batch sequence: {:?} followed by {:?}", prev.desc, meta.desc ) .into()); } } unsealed_prev = Some(&meta) } let mut trace_prev: Option<&TraceBatchMeta> = None; for meta in self.trace_batches.iter() { if !PartialOrder::less_equal(meta.desc.since(), &self.since) { return Err(format!( "invalid batch since: {:?} in advance of trace since {:?}", meta.desc, self.since ) .into()); } if !PartialOrder::less_equal(meta.desc.upper(), &self.seal) { return Err(format!( "invalid batch upper: {:?} in advance of trace seal {:?}", meta.desc, self.seal, ) .into()); } meta.validate()?; if let Some(prev) = trace_prev { if prev.desc.upper() != meta.desc.lower() { return Err(format!( "invalid batch sequence: {:?} followed by {:?}", prev.desc, meta.desc, ) .into()); } if prev.level < meta.level { return Err(format!( "invalid batch sequence: compaction level {} followed by {}", prev.level, meta.level ) .into()); } } trace_prev = Some(&meta) } Ok(()) } /// Returns an open upper bound on the seqnos contained in this unsealed. pub fn unsealed_seqno_upper(&self) -> SeqNo { self.unsealed_batches .last() .map_or_else(|| SeqNo(0), |meta| meta.desc.end) } /// Returns an open upper bound on the timestamps of data contained in this /// trace. pub fn trace_ts_upper(&self) -> Antichain<u64> { self.trace_batches.last().map_or_else( || Antichain::from_elem(Timestamp::minimum()), |meta| meta.desc.upper().clone(), ) } } impl UnsealedBatchMeta { /// Asserts Self's documented invariants, returning an error if any are /// violated. pub fn validate(&self) -> Result<(), Error> { // TODO: It's unclear if the equal case (an empty desc) is // useful/harmful. Feel free to make this a less_than if empty descs end // up making sense. if self.desc.end <= self.desc.start { return Err(format!("invalid desc: {:?}", &self.desc).into()); } Ok(()) } } impl TraceBatchMeta { /// Asserts Self's documented invariants, returning an error if any are /// violated. pub fn validate(&self) -> Result<(), Error> { // TODO: It's unclear if the equal case (an empty desc) is // useful/harmful. Feel free to make this a less_than if empty descs end // up making sense. if PartialOrder::less_equal(self.desc.upper(), &self.desc.lower()) { return Err(format!("invalid desc: {:?}", &self.desc).into()); } Ok(()) } } impl BlobUnsealedBatch { /// Asserts Self's documented invariants, returning an error if any are /// violated. pub fn validate(&self) -> Result<(), Error> { // TODO: It's unclear if the equal case (an empty desc) is // useful/harmful. Feel free to make this a less_than if empty descs end // up making sense. if self.desc.end <= self.desc.start { return Err(format!("invalid desc: {:?}", &self.desc).into()); } // TODO: It's unclear if this invariant is useful/harmful. Feel free to // remove it if it ends up not making sense. if self.updates.is_empty() { return Err("updates is empty".into()); } Ok(()) } } // BlobUnsealedBatch doesn't really need to implement Codec (it's never stored // as a key or value in a persisted record) but it's nice to have a common // interface for this. impl Codec for BlobUnsealedBatch { fn codec_name() -> String { "parquet[UnsealedBatch]".into() } fn encode<B>(&self, buf: &mut B) where B: BufMut, { encode_unsealed_parquet(&mut buf.writer(), &self).expect("writes to BufMut are infallible"); } fn decode<'a>(buf: &'a [u8]) -> Result<Self, String> { decode_unsealed_parquet(&mut Cursor::new(&buf)).map_err(|err| err.to_string()) } } impl BlobTraceBatch { /// Asserts the documented invariants, returning an error if any are /// violated. pub fn validate(&self) -> Result<(), Error> { // TODO: It's unclear if the equal case (an empty desc) is // useful/harmful. Feel free to make this a less_than if empty descs end // up making sense. if PartialOrder::less_equal(self.desc.upper(), &self.desc.lower()) { return Err(format!("invalid desc: {:?}", &self.desc).into()); } let mut prev: Option<(PrettyBytes<'_>, PrettyBytes<'_>, u64)> = None; for update in self.updates.iter().flat_map(|u| u.iter()) { let ((key, val), ts, diff) = update; // Check ts against desc. if !self.desc.lower().less_equal(&ts) { return Err(format!( "timestamp {} is less than the batch lower: {:?}", ts, self.desc ) .into()); } if PartialOrder::less_than(self.desc.since(), self.desc.upper()) { if self.desc.upper().less_equal(&ts) { return Err(format!( "timestamp {} is greater than or equal to the batch upper: {:?}", ts, self.desc ) .into()); } } else if self.desc.since().less_than(&ts) { return Err(format!( "timestamp {} is greater than the batch since: {:?}", ts, self.desc, ) .into()); } // Check ordering. let this = (PrettyBytes(&key), PrettyBytes(&val), ts); if let Some(prev) = prev { match prev.cmp(&this) { Ordering::Less => {} // Correct. Ordering::Equal => return Err(format!("unconsolidated: {:?}", this).into()), Ordering::Greater => { return Err(format!("unsorted: {:?} was before {:?}", prev, this).into()) } } } prev = Some(this); // Check data invariants. if diff == 0 { return Err(format!("update with 0 diff: {:?}", PrettyRecord(update)).into()); } } Ok(()) } } // BlobTraceBatch doesn't really need to implement Codec (it's never stored as a // key or value in a persisted record) but it's nice to have a common interface // for this. impl Codec for BlobTraceBatch { fn codec_name() -> String { "parquet[TraceBatch]".into() } fn encode<B>(&self, buf: &mut B) where B: BufMut, { encode_trace_parquet(&mut buf.writer(), self).expect("writes to BufMut are infallible"); } fn decode<'a>(buf: &'a [u8]) -> Result<Self, String> { decode_trace_parquet(&mut Cursor::new(&buf)).map_err(|err| err.to_string()) } } #[derive(PartialOrd, Ord, PartialEq, Eq)] struct PrettyBytes<'a>(&'a [u8]); impl fmt::Debug for PrettyBytes<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match std::str::from_utf8(self.0) { Ok(x) => fmt::Debug::fmt(x, f), Err(_) => fmt::Debug::fmt(self.0, f), } } } struct PrettyRecord<'a>(((&'a [u8], &'a [u8]), u64, isize)); impl fmt::Debug for PrettyRecord<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let ((k, v), ts, diff) = &self.0; fmt::Debug::fmt(&((PrettyBytes(&k), PrettyBytes(&v)), ts, diff), f) } } impl From<ProtoMeta> for BlobMeta { fn from(x: ProtoMeta) -> Self { let mut meta = BlobMeta { seqno: SeqNo(x.seqno), id_mapping: x.id_mapping.into_iter().map(|x| x.into()).collect(), graveyard: x.graveyard.into_iter().map(|x| x.into()).collect(), arrangements: x.arrangements.into_iter().map(|x| x.into()).collect(), }; // TODO: Make the types on BlobMeta be HashMaps and remove this sort. meta.id_mapping.sort_by_key(|x| x.id); meta.graveyard.sort_by_key(|x| x.id); meta.arrangements.sort_by_key(|x| x.id); meta } } impl From<(u64, ProtoArrangement)> for ArrangementMeta { fn from(x: (u64, ProtoArrangement)) -> Self { let (id, x) = x; ArrangementMeta { id: Id(id), seal: x .seal .map_or_else(|| Antichain::from_elem(u64::minimum()), |x| x.into()), since: x .since .map_or_else(|| Antichain::from_elem(u64::minimum()), |x| x.into()), unsealed_batches: x.unsealed_batches.into_iter().map(|x| x.into()).collect(), trace_batches: x.trace_batches.into_iter().map(|x| x.into()).collect(), } } } impl From<(u64, ProtoStreamRegistration)> for StreamRegistration { fn from(x: (u64, ProtoStreamRegistration)) -> Self { let (id, x) = x; StreamRegistration { id: Id(id), name: x.name, key_codec_name: x.key_codec_name, val_codec_name: x.val_codec_name, } } } impl From<ProtoUnsealedBatchMeta> for UnsealedBatchMeta { fn from(x: ProtoUnsealedBatchMeta) -> Self { UnsealedBatchMeta { format: x.format(), key: x.key, desc: SeqNo(x.seqno_lower)..SeqNo(x.seqno_upper), ts_upper: x.ts_upper, ts_lower: x.ts_lower, size_bytes: x.size_bytes, } } } impl From<ProtoTraceBatchMeta> for TraceBatchMeta { fn from(x: ProtoTraceBatchMeta) -> Self { TraceBatchMeta { format: x.format(), key: x.key, desc: x.desc.map_or_else( || { Description::new( Antichain::from_elem(u64::minimum()), Antichain::from_elem(u64::minimum()), Antichain::from_elem(u64::minimum()), ) }, |x| x.into(), ), level: x.level, size_bytes: x.size_bytes, } } } impl From<ProtoU64Description> for Description<u64> { fn from(x: ProtoU64Description) -> Self { Description::new( x.lower .map_or_else(|| Antichain::from_elem(u64::minimum()), |x| x.into()), x.upper .map_or_else(|| Antichain::from_elem(u64::minimum()), |x| x.into()), x.since .map_or_else(|| Antichain::from_elem(u64::minimum()), |x| x.into()), ) } } impl From<ProtoU64Antichain> for Antichain<u64> { fn from(x: ProtoU64Antichain) -> Self { Antichain::from(x.elements) } } impl From<(&BlobMeta, &Version)> for ProtoMeta { fn from(x: (&BlobMeta, &Version)) -> Self { let (x, b) = x; ProtoMeta { version: b.to_string(), seqno: x.seqno.0, id_mapping: x.id_mapping.iter().map(|x| (x.id.0, x.into())).collect(), graveyard: x.graveyard.iter().map(|x| (x.id.0, x.into())).collect(), arrangements: x.arrangements.iter().map(|x| (x.id.0, x.into())).collect(), } } } impl From<&ArrangementMeta> for ProtoArrangement { fn from(x: &ArrangementMeta) -> Self { ProtoArrangement { since: Some((&x.since).into()), seal: Some((&x.seal).into()), unsealed_batches: x.unsealed_batches.iter().map(|x| x.into()).collect(), trace_batches: x.trace_batches.iter().map(|x| x.into()).collect(), } } } impl From<&StreamRegistration> for ProtoStreamRegistration { fn from(x: &StreamRegistration) -> Self { ProtoStreamRegistration { name: x.name.clone(), key_codec_name: x.key_codec_name.clone(), val_codec_name: x.val_codec_name.clone(), } } } impl From<&UnsealedBatchMeta> for ProtoUnsealedBatchMeta { fn from(x: &UnsealedBatchMeta) -> Self { ProtoUnsealedBatchMeta { key: x.key.clone(), format: x.format.into(), seqno_upper: x.desc.end.0, seqno_lower: x.desc.start.0, ts_upper: x.ts_upper, ts_lower: x.ts_lower, size_bytes: x.size_bytes, } } } impl From<&TraceBatchMeta> for ProtoTraceBatchMeta { fn from(x: &TraceBatchMeta) -> Self { ProtoTraceBatchMeta { key: x.key.clone(), format: x.format.into(), desc: Some((&x.desc).into()), level: x.level, size_bytes: x.size_bytes, } } } impl From<&Antichain<u64>> for ProtoU64Antichain { fn from(x: &Antichain<u64>) -> Self { ProtoU64Antichain { elements: x.elements().to_vec(), } } } impl From<&Description<u64>> for ProtoU64Description { fn from(x: &Description<u64>) -> Self { ProtoU64Description { lower: Some(x.lower().into()), upper: Some(x.upper().into()), since: Some(x.since().into()), } } } /// Encodes the inline metadata for an unsealed batch into a base64 string. pub fn encode_unsealed_inline_meta(batch: &BlobUnsealedBatch, format: ProtoBatchFormat) -> String { let inline = ProtoBatchInline { batch_type: Some(proto_batch_inline::BatchType::Unsealed( ProtoUnsealedBatchInline { format: format.into(), seqno_lower: batch.desc.start.0, seqno_upper: batch.desc.end.0, }, )), }; let inline_encoded = inline.encode_to_vec(); base64::encode(inline_encoded) } /// Encodes the inline metadata for a trace batch into a base64 string. pub fn encode_trace_inline_meta(batch: &BlobTraceBatch, format: ProtoBatchFormat) -> String { let inline = ProtoBatchInline { batch_type: Some(proto_batch_inline::BatchType::Trace( ProtoTraceBatchInline { format: format.into(), desc: Some((&batch.desc).into()), }, )), }; let inline_encoded = inline.encode_to_vec(); base64::encode(inline_encoded) } /// Decodes the inline metadata for an unsealed batch from a base64 string. pub fn decode_unsealed_inline_meta( inline_base64: Option<&String>, ) -> Result<(ProtoBatchFormat, ProtoUnsealedBatchInline), Error> { let inline_base64 = inline_base64.ok_or("missing batch metadata")?; let inline_encoded = base64::decode(&inline_base64).map_err(|err| err.to_string())?; let inline = ProtoBatchInline::decode(&*inline_encoded).map_err(|err| err.to_string())?; match inline.batch_type { Some(proto_batch_inline::BatchType::Unsealed(x)) => { let format = ProtoBatchFormat::from_i32(x.format) .ok_or_else(|| Error::from(format!("unknown format: {}", x.format)))?; Ok((format, x)) } x => return Err(format!("incorrect batch type: {:?}", x).into()), } } /// Decodes the inline metadata for a trace batch from a base64 string. pub fn decode_trace_inline_meta( inline_base64: Option<&String>, ) -> Result<(ProtoBatchFormat, ProtoTraceBatchInline), Error> { let inline_base64 = inline_base64.ok_or("missing batch metadata")?; let inline_encoded = base64::decode(&inline_base64).map_err(|err| err.to_string())?; let inline = ProtoBatchInline::decode(&*inline_encoded).map_err(|err| err.to_string())?; match inline.batch_type { Some(proto_batch_inline::BatchType::Trace(x)) => { let format = ProtoBatchFormat::from_i32(x.format) .ok_or_else(|| Error::from(format!("unknown format: {}", x.format)))?; Ok((format, x)) } x => return Err(format!("incorrect batch type: {:?}", x).into()), } } #[cfg(test)] mod tests { use crate::error::Error; use crate::indexed::columnar::ColumnarRecordsVec; use crate::workload::DataGenerator; use super::*; fn update_with_ts(ts: u64) -> ((Vec<u8>, Vec<u8>), u64, isize) { (("".into(), "".into()), ts, 1) } fn update_with_key(ts: u64, key: &'static str) -> ((Vec<u8>, Vec<u8>), u64, isize) { ((key.into(), "".into()), ts, 1) } fn u64_desc(lower: u64, upper: u64) -> Description<u64> { Description::new( Antichain::from_elem(lower), Antichain::from_elem(upper), Antichain::from_elem(0), ) } fn batch_meta(lower: u64, upper: u64) -> TraceBatchMeta { TraceBatchMeta { key: "".to_string(), format: ProtoBatchFormat::Unknown, desc: u64_desc(lower, upper), level: 1, size_bytes: 0, } } fn batch_meta_full(lower: u64, upper: u64, since: u64, level: u64) -> TraceBatchMeta { TraceBatchMeta { key: "".to_string(), format: ProtoBatchFormat::Unknown, desc: u64_desc_since(lower, upper, since), level, size_bytes: 0, } } fn u64_desc_since(lower: u64, upper: u64, since: u64) -> Description<u64> { Description::new( Antichain::from_elem(lower), Antichain::from_elem(upper), Antichain::from_elem(since), ) } fn unsealed_batch_meta(lower: u64, upper: u64) -> UnsealedBatchMeta { UnsealedBatchMeta { key: "".to_string(), format: ProtoBatchFormat::Unknown, desc: SeqNo(lower)..SeqNo(upper), ts_upper: 0, ts_lower: 0, size_bytes: 0, } } fn columnar_records(updates: Vec<((Vec<u8>, Vec<u8>), u64, isize)>) -> Vec<ColumnarRecords> { updates.iter().collect::<ColumnarRecordsVec>().into_inner() } impl From<(&'_ str, Id)> for StreamRegistration { fn from(x: (&'_ str, Id)) -> Self { let (name, id) = x; StreamRegistration { name: name.to_owned(), id, key_codec_name: "".into(), val_codec_name: "".into(), } } } #[test] fn log_entry_validate() { // Normal case let b = LogEntry { updates: vec![(Id(0), vec![update_with_key(0, "0")])], }; assert_eq!(b.validate(), Ok(())); // Empty let b: LogEntry = LogEntry { updates: vec![] }; assert_eq!(b.validate(), Err("updates is empty".into())); } #[test] fn unsealed_batch_validate() { // Normal case let b = BlobUnsealedBatch { desc: SeqNo(0)..SeqNo(2), updates: columnar_records(vec![update_with_ts(0), update_with_ts(1)]), }; assert_eq!(b.validate(), Ok(())); // Empty let b: BlobUnsealedBatch = BlobUnsealedBatch { desc: SeqNo(0)..SeqNo(2), updates: vec![], }; assert_eq!(b.validate(), Err("updates is empty".into())); // Invalid desc let b: BlobUnsealedBatch = BlobUnsealedBatch { desc: SeqNo(2)..SeqNo(0), updates: vec![], }; assert_eq!( b.validate(), Err(Error::from("invalid desc: SeqNo(2)..SeqNo(0)")) ); // Empty desc let b: BlobUnsealedBatch = BlobUnsealedBatch { desc: SeqNo(0)..SeqNo(0), updates: vec![], }; assert_eq!( b.validate(), Err(Error::from("invalid desc: SeqNo(0)..SeqNo(0)")) ); } #[test] fn trace_batch_validate() { // Normal case let b = BlobTraceBatch { desc: u64_desc(0, 2), updates: columnar_records(vec![update_with_key(0, "0"), update_with_key(1, "1")]), }; assert_eq!(b.validate(), Ok(())); // Empty let b: BlobTraceBatch = BlobTraceBatch { desc: u64_desc(0, 2), updates: columnar_records(vec![]), }; assert_eq!(b.validate(), Ok(())); // Invalid desc let b: BlobTraceBatch = BlobTraceBatch { desc: u64_desc(2, 0), updates: columnar_records(vec![]), }; assert_eq!( b.validate(), Err(Error::from( "invalid desc: Description { lower: Antichain { elements: [2] }, upper: Antichain { elements: [0] }, since: Antichain { elements: [0] } }" )) ); // Empty desc let b: BlobTraceBatch = BlobTraceBatch { desc: u64_desc(0, 0), updates: columnar_records(vec![]), }; assert_eq!( b.validate(), Err(Error::from( "invalid desc: Description { lower: Antichain { elements: [0] }, upper: Antichain { elements: [0] }, since: Antichain { elements: [0] } }" )) ); // Not sorted by key let b = BlobTraceBatch { desc: u64_desc(0, 2), updates: columnar_records(vec![update_with_key(0, "1"), update_with_key(1, "0")]), }; assert_eq!( b.validate(), Err(Error::from( "unsorted: (\"1\", \"\", 0) was before (\"0\", \"\", 1)" )) ); // Not consolidated let b = BlobTraceBatch { desc: u64_desc(0, 2), updates: columnar_records(vec![update_with_key(0, "0"), update_with_key(0, "0")]), }; assert_eq!( b.validate(), Err(Error::from("unconsolidated: (\"0\", \"\", 0)")) ); // Update "before" desc let b = BlobTraceBatch { desc: u64_desc(1, 2), updates: columnar_records(vec![update_with_key(0, "0")]), }; assert_eq!(b.validate(), Err(Error::from("timestamp 0 is less than the batch lower: Description { lower: Antichain { elements: [1] }, upper: Antichain { elements: [2] }, since: Antichain { elements: [0] } }"))); // Update "after" desc let b = BlobTraceBatch { desc: u64_desc(1, 2), updates: columnar_records(vec![update_with_key(2, "0")]), }; assert_eq!(b.validate(), Err(Error::from("timestamp 2 is greater than or equal to the batch upper: Description { lower: Antichain { elements: [1] }, upper: Antichain { elements: [2] }, since: Antichain { elements: [0] } }"))); // Normal case: update "after" desc and within since let b = BlobTraceBatch { desc: u64_desc_since(1, 2, 4), updates: columnar_records(vec![update_with_key(2, "0")]), }; assert_eq!(b.validate(), Ok(())); // Normal case: update "after" desc and at since let b = BlobTraceBatch { desc: u64_desc_since(1, 2, 4), updates: columnar_records(vec![update_with_key(4, "0")]), }; assert_eq!(b.validate(), Ok(())); // Update "after" desc since let b = BlobTraceBatch { desc: u64_desc_since(1, 2, 4), updates: columnar_records(vec![update_with_key(5, "0")]), }; assert_eq!(b.validate(), Err(Error::from("timestamp 5 is greater than the batch since: Description { lower: Antichain { elements: [1] }, upper: Antichain { elements: [2] }, since: Antichain { elements: [4] } }"))); // Invalid update let b: BlobTraceBatch = BlobTraceBatch { desc: u64_desc(0, 1), updates: columnar_records(vec![(("0".into(), "0".into()), 0, 0)]), }; assert_eq!( b.validate(), Err(Error::from("update with 0 diff: ((\"0\", \"0\"), 0, 0)")) ); } #[test] fn trace_batch_meta_validate() { // Normal case let b = batch_meta(0, 1); assert_eq!(b.validate(), Ok(())); // Empty interval let b = batch_meta(0, 0); assert_eq!(b.validate(), Err(Error::from( "invalid desc: Description { lower: Antichain { elements: [0] }, upper: Antichain { elements: [0] }, since: Antichain { elements: [0] } }" )), ); // Invalid interval let b = batch_meta(2, 0); assert_eq!(b.validate(), Err(Error::from( "invalid desc: Description { lower: Antichain { elements: [2] }, upper: Antichain { elements: [0] }, since: Antichain { elements: [0] } }" )), ); } #[test] fn trace_meta_validate() { // Empty let b = ArrangementMeta { id: Id(0), trace_batches: vec![], since: Antichain::from_elem(0), seal: Antichain::from_elem(0), ..Default::default() }; assert_eq!(b.validate(), Ok(())); // Normal case let b = ArrangementMeta { id: Id(0), trace_batches: vec![batch_meta(0, 1), batch_meta(1, 2)], since: Antichain::from_elem(0), seal: Antichain::from_elem(2), ..Default::default() }; assert_eq!(b.validate(), Ok(())); // Gap let b = ArrangementMeta { id: Id(0), trace_batches: vec![batch_meta(0, 1), batch_meta(2, 3)], since: Antichain::from_elem(0), seal: Antichain::from_elem(3), ..Default::default() }; assert_eq!(b.validate(), Err(Error::from("invalid batch sequence: Description { lower: Antichain { elements: [0] }, upper: Antichain { elements: [1] }, since: Antichain { elements: [0] } } followed by Description { lower: Antichain { elements: [2] }, upper: Antichain { elements: [3] }, since: Antichain { elements: [0] } }"))); // Overlapping let b = ArrangementMeta { id: Id(0), trace_batches: vec![batch_meta(0, 2), batch_meta(1, 3)], since: Antichain::from_elem(0), seal: Antichain::from_elem(3), ..Default::default() }; assert_eq!(b.validate(), Err(Error::from("invalid batch sequence: Description { lower: Antichain { elements: [0] }, upper: Antichain { elements: [2] }, since: Antichain { elements: [0] } } followed by Description { lower: Antichain { elements: [1] }, upper: Antichain { elements: [3] }, since: Antichain { elements: [0] } }"))); // Normal case: trace since before nonzero trace upper let b = ArrangementMeta { id: Id(0), trace_batches: vec![batch_meta(0, 1), batch_meta(1, 2)], since: Antichain::from_elem(1), seal: Antichain::from_elem(2), ..Default::default() }; assert_eq!(b.validate(), Ok(())); // Trace since at nonzero trace seal let b = ArrangementMeta { id: Id(0), trace_batches: vec![batch_meta(0, 2), batch_meta(2, 3)], since: Antichain::from_elem(3), seal: Antichain::from_elem(3), ..Default::default() }; assert_eq!(b.validate(), Ok(())); // Trace since in advance of nonzero trace seal let b = ArrangementMeta { id: Id(0), trace_batches: vec![batch_meta(0, 2), batch_meta(2, 3)], since: Antichain::from_elem(4), seal: Antichain::from_elem(3), ..Default::default() }; assert_eq!(b.validate(), Ok(())); // Normal case: batch since at or before trace since let b = ArrangementMeta { id: Id(0), trace_batches: vec![batch_meta(0, 1), batch_meta_full(1, 2, 1, 1)], since: Antichain::from_elem(1), seal: Antichain::from_elem(2), ..Default::default() }; assert_eq!(b.validate(), Ok(())); // Batch since in advance of trace since let b = ArrangementMeta { id: Id(0), trace_batches: vec![batch_meta(0, 1), batch_meta_full(1, 2, 2, 1)], since: Antichain::from_elem(1), seal: Antichain::from_elem(2), ..Default::default() }; assert_eq!(b.validate(), Err(Error::from("invalid batch since: Description { lower: Antichain { elements: [1] }, upper: Antichain { elements: [2] }, since: Antichain { elements: [2] } } in advance of trace since Antichain { elements: [1] }"))); // Normal case: decreasing or constant compaction levels let b = ArrangementMeta { id: Id(0), trace_batches: vec![ batch_meta_full(0, 1, 0, 2), batch_meta_full(1, 2, 0, 2), batch_meta_full(2, 3, 0, 1), ], since: Antichain::from_elem(0), seal: Antichain::from_elem(3), ..Default::default() }; assert_eq!(b.validate(), Ok(())); // Increasing compaction level. let b = ArrangementMeta { id: Id(0), trace_batches: vec![batch_meta_full(0, 1, 0, 1), batch_meta_full(1, 2, 0, 2)], since: Antichain::from_elem(0), seal: Antichain::from_elem(2), ..Default::default() }; assert_eq!( b.validate(), Err(Error::from( "invalid batch sequence: compaction level 1 followed by 2" )) ); } #[test] fn unsealed_batch_meta_validate() { // Normal case let b = unsealed_batch_meta(0, 1); assert_eq!(b.validate(), Ok(())); // Empty interval let b = unsealed_batch_meta(0, 0); assert_eq!( b.validate(), Err(Error::from("invalid desc: SeqNo(0)..SeqNo(0)")) ); // Invalid desc let b = unsealed_batch_meta(1, 0); assert_eq!( b.validate(), Err(Error::from("invalid desc: SeqNo(1)..SeqNo(0)")) ); } #[test] fn unsealed_meta_validate() { // Empty let b = ArrangementMeta { id: Id(0), unsealed_batches: vec![], ..Default::default() }; assert_eq!(b.validate(), Ok(())); // Normal case let b = ArrangementMeta { id: Id(0), unsealed_batches: vec![unsealed_batch_meta(0, 1), unsealed_batch_meta(1, 2)], ..Default::default() }; assert_eq!(b.validate(), Ok(())); // Normal case: gap between sequence number ranges. let b = ArrangementMeta { id: Id(0), unsealed_batches: vec![unsealed_batch_meta(0, 1), unsealed_batch_meta(2, 3)], ..Default::default() }; assert_eq!(b.validate(), Ok(()),); // Overlapping let b = ArrangementMeta { id: Id(0), unsealed_batches: vec![unsealed_batch_meta(0, 2), unsealed_batch_meta(1, 3)], ..Default::default() }; assert_eq!( b.validate(), Err(Error::from( "invalid batch sequence: SeqNo(0)..SeqNo(2) followed by SeqNo(1)..SeqNo(3)" )) ); } #[test] fn blob_meta_validate() { // Empty let b = BlobMeta::default(); assert_eq!(b.validate(), Ok(())); // Normal case let b = BlobMeta { id_mapping: vec![("0", Id(0)).into(), ("1", Id(1)).into()], arrangements: vec![ArrangementMeta::new(Id(0)), ArrangementMeta::new(Id(1))], ..Default::default() }; assert_eq!(b.validate(), Ok(())); // Duplicate external stream id let b = BlobMeta { id_mapping: vec![("1", Id(0)).into(), ("1", Id(1)).into()], arrangements: vec![ArrangementMeta::new(Id(0)), ArrangementMeta::new(Id(1))], ..Default::default() }; assert_eq!( b.validate(), Err(Error::from("duplicate external stream name: 1")) ); // Duplicate internal stream id let b = BlobMeta { id_mapping: vec![("0", Id(1)).into(), ("1", Id(1)).into()], arrangements: vec![ArrangementMeta::new(Id(0)), ArrangementMeta::new(Id(1))], ..Default::default() }; assert_eq!( b.validate(), Err(Error::from("duplicate internal stream id: Id(1)")) ); // Missing arrangement let b = BlobMeta { id_mapping: vec![("0", Id(0)).into()], arrangements: vec![], ..Default::default() }; assert_eq!( b.validate(), Err(Error::from( "id_mapping id Id(0) not present in arrangements" )) ); // Extra arrangement let b = BlobMeta { id_mapping: vec![], arrangements: vec![ArrangementMeta::new(Id(0))], ..Default::default() }; assert_eq!( b.validate(), Err(Error::from( "arrangements id Id(0) not present in id_mapping" )) ); // Duplicate in arrangements let b = BlobMeta { id_mapping: vec![("0", Id(0)).into()], arrangements: vec![ArrangementMeta::new(Id(0)), ArrangementMeta::new(Id(0))], ..Default::default() }; assert_eq!( b.validate(), Err(Error::from("duplicate arrangement: Id(0)")) ); // Normal case: unsealed ts_lower < ts_upper let b = BlobMeta { id_mapping: vec![("0", Id(0)).into()], arrangements: vec![ArrangementMeta { id: Id(0), unsealed_batches: vec![], trace_batches: vec![batch_meta(0, 1)], since: Antichain::from_elem(0), seal: Antichain::from_elem(1), }], ..Default::default() }; assert_eq!(b.validate(), Ok(()),); // Normal case: unsealed ts_lower at ts_upper let b = BlobMeta { id_mapping: vec![("0", Id(0)).into()], arrangements: vec![ArrangementMeta { id: Id(0), unsealed_batches: vec![], trace_batches: vec![batch_meta(0, 1)], since: Antichain::from_elem(0), seal: Antichain::from_elem(1), }], ..Default::default() }; assert_eq!(b.validate(), Ok(()),); // seqno less than one of the unsealed seqno uppers let b = BlobMeta { id_mapping: vec![("0", Id(0)).into()], seqno: SeqNo(2), arrangements: vec![ArrangementMeta { id: Id(0), unsealed_batches: vec![unsealed_batch_meta(0, 3)], ..Default::default() }], ..Default::default() }; assert_eq!( b.validate(), Err(Error::from( "id Id(0) unsealed seqno_upper SeqNo(3) is not less or equal to the blob's seqno SeqNo(2)" )) ); // Duplicate id in graveyard. let b = BlobMeta { graveyard: vec![("deleted", Id(0)).into(), ("1", Id(0)).into()], ..Default::default() }; assert_eq!( b.validate(), Err(Error::from("duplicate deleted internal stream id: Id(0)")) ); // Duplicate stream name in graveyard. let b = BlobMeta { graveyard: vec![("deleted", Id(0)).into(), ("deleted", Id(1)).into()], ..Default::default() }; assert_eq!( b.validate(), Err(Error::from( "duplicate deleted external stream name: deleted" )) ); // Duplicate id across graveyard and id_mapping. let b = BlobMeta { id_mapping: vec![("deleted", Id(0)).into()], graveyard: vec![("1", Id(0)).into()], ..Default::default() }; assert_eq!( b.validate(), Err(Error::from( "duplicate internal stream id Id(0) across deleted and registered streams" )) ); // Duplicate stream name across graveyard and id_mapping. let b = BlobMeta { id_mapping: vec![("name", Id(1)).into()], graveyard: vec![("name", Id(0)).into()], ..Default::default() }; assert_eq!( b.validate(), Err(Error::from( "duplicate external stream name name across deleted and registered streams" )) ); // Next stream id != id_mapping + deleted let b = BlobMeta { id_mapping: vec![("name", Id(1)).into()], ..Default::default() }; assert_eq!( b.validate(), Err(Error::from( "next stream Id(2), but only registered 1 ids and deleted 0 ids" )) ); let b = BlobMeta { id_mapping: vec![("0", Id(0)).into(), ("1", Id(1)).into()], seqno: SeqNo(2), arrangements: vec![ ArrangementMeta { id: Id(0), unsealed_batches: vec![unsealed_batch_meta(0, 1)], ..Default::default() }, ArrangementMeta { id: Id(1), unsealed_batches: vec![unsealed_batch_meta(0, 1)], ..Default::default() }, ], ..Default::default() }; assert_eq!( b.validate(), Err(Error::from("duplicate batch key found in unsealed: ")) ); let b = BlobMeta { id_mapping: vec![("0", Id(0)).into(), ("1", Id(1)).into()], arrangements: vec![ ArrangementMeta { id: Id(0), trace_batches: vec![batch_meta(0, 1)], since: Antichain::from_elem(0), seal: Antichain::from_elem(1), ..Default::default() }, ArrangementMeta { id: Id(1), trace_batches: vec![batch_meta(0, 1)], since: Antichain::from_elem(0), seal: Antichain::from_elem(1), ..Default::default() }, ], ..Default::default() }; assert_eq!( b.validate(), Err(Error::from("duplicate batch key found in trace: ")) ); } #[test] fn encoded_batch_sizes() { fn sizes(data: DataGenerator) -> (usize, usize) { let unsealed = BlobUnsealedBatch { desc: SeqNo(0)..SeqNo(1), updates: data.batches().collect(), }; let trace = BlobTraceBatch { desc: Description::new( Antichain::from_elem(0), Antichain::from_elem(1), Antichain::from_elem(0), ), updates: data.batches().collect(), }; let (mut unsealed_buf, mut trace_buf) = (Vec::new(), Vec::new()); unsealed.encode(&mut unsealed_buf); trace.encode(&mut trace_buf); (unsealed_buf.len(), trace_buf.len()) } let record_size_bytes = DataGenerator::default().record_size_bytes; // Print all the sizes into one assert so we only have to update one // place if sizes change. assert_eq!( format!( "1/1={:?} 25/1={:?} 1000/1={:?} 1000/100={:?}", sizes(DataGenerator::new(1, record_size_bytes, 1)), sizes(DataGenerator::new(25, record_size_bytes, 25)), sizes(DataGenerator::new(1_000, record_size_bytes, 1_000)), sizes(DataGenerator::new(1_000, record_size_bytes, 1_000 / 100)), ), "1/1=(481, 501) 25/1=(2229, 2249) 1000/1=(72468, 72488) 1000/100=(106557, 106577)" ); } }
35.232919
336
0.543358
1d267e3266e20354df9395237a1fab49f6ff4eb7
2,596
use clap::ArgMatches; use environment::Environment; use eth2_testnet_config::Eth2TestnetConfig; use genesis::{Eth1Config, Eth1GenesisService}; use std::path::PathBuf; use std::time::Duration; use types::EthSpec; /// Interval between polling the eth1 node for genesis information. pub const ETH1_GENESIS_UPDATE_INTERVAL: Duration = Duration::from_millis(7_000); pub fn run<T: EthSpec>(mut env: Environment<T>, matches: &ArgMatches<'_>) -> Result<(), String> { let endpoint = matches .value_of("eth1-endpoint") .ok_or_else(|| "eth1-endpoint not specified")?; let testnet_dir = matches .value_of("testnet-dir") .ok_or_else(|| ()) .and_then(|dir| dir.parse::<PathBuf>().map_err(|_| ())) .unwrap_or_else(|_| { dirs::home_dir() .map(|home| home.join(".lighthouse").join("testnet")) .expect("should locate home directory") }); let mut eth2_testnet_config: Eth2TestnetConfig<T> = Eth2TestnetConfig::load(testnet_dir.clone())?; let spec = eth2_testnet_config .yaml_config .as_ref() .ok_or_else(|| "The testnet directory must contain a spec config".to_string())? .apply_to_chain_spec::<T>(&env.core_context().eth2_config.spec) .ok_or_else(|| { format!( "The loaded config is not compatible with the {} spec", &env.core_context().eth2_config.spec_constants ) })?; let mut config = Eth1Config::default(); config.endpoint = endpoint.to_string(); config.deposit_contract_address = eth2_testnet_config.deposit_contract_address.clone(); config.deposit_contract_deploy_block = eth2_testnet_config.deposit_contract_deploy_block; config.lowest_cached_block_number = eth2_testnet_config.deposit_contract_deploy_block; config.follow_distance = spec.eth1_follow_distance / 2; let genesis_service = Eth1GenesisService::new(config, env.core_context().log.clone()); env.runtime().block_on(async { let _ = genesis_service .wait_for_genesis_state(ETH1_GENESIS_UPDATE_INTERVAL, spec) .await .map(move |genesis_state| { eth2_testnet_config.genesis_state = Some(genesis_state); eth2_testnet_config.force_write_to_file(testnet_dir) }) .map_err(|e| format!("Failed to find genesis: {}", e))?; info!("Starting service to produce genesis BeaconState from eth1"); info!("Connecting to eth1 http endpoint: {}", endpoint); Ok(()) }) }
38.746269
97
0.654083
227858c57989df81851ec1f63b7e09b4a5ffa561
9,379
use futures::future::ok; use std::rc::Rc; use super::{BoxedNewPeerFuture, Peer}; use super::{ConstructParams, PeerConstructor, Specifier}; use std::io::Read; use tokio_io::AsyncRead; use std::io::Error as IoError; #[derive(Debug)] pub struct Message2Line<T: Specifier>(pub T); impl<T: Specifier> Specifier for Message2Line<T> { fn construct(&self, cp: ConstructParams) -> PeerConstructor { let inner = self.0.construct(cp.clone()); let zt = cp.program_options.linemode_zero_terminated; inner.map(move |p, _| packet2line_peer(p, zt)) } specifier_boilerplate!(noglobalstate has_subspec); self_0_is_subspecifier!(proxy_is_multiconnect); } specifier_class!( name = Message2LineClass, target = Message2Line, prefixes = ["msg2line:"], arg_handling = subspec, overlay = true, StreamOriented, MulticonnectnessDependsOnInnerType, help = r#" Line filter: Turns messages from packet stream into lines of byte stream. [A] Ensure each message (a chunk from one read call from underlying connection) contains no inner newlines (or zero bytes) and terminates with one newline. Reverse of the `line2msg:`. Unless --null-terminated, replaces both newlines (\x0A) and carriage returns (\x0D) with spaces (\x20) for each read. Does not affect writing at all. Use this specifier on both ends to get bi-directional behaviour. Automatically inserted by --line option on top of the stack containing a websocket. Example: TODO "# ); #[derive(Debug)] pub struct Line2Message<T: Specifier>(pub T); impl<T: Specifier> Specifier for Line2Message<T> { fn construct(&self, cp: ConstructParams) -> PeerConstructor { let retain_newlines = !cp.program_options.linemode_strip_newlines; let strict = cp.program_options.linemode_strict; let nullt = cp.program_options.linemode_zero_terminated; let inner = self.0.construct(cp.clone()); inner.map(move |p, _| line2packet_peer(p, retain_newlines, strict, nullt)) } specifier_boilerplate!(noglobalstate has_subspec); self_0_is_subspecifier!(proxy_is_multiconnect); } specifier_class!( name=Line2MessageClass, target=Line2Message, prefixes=["line2msg:"], arg_handling=subspec, overlay = true, MessageOriented, MulticonnectnessDependsOnInnerType, help=r#" Line filter: turn lines from byte stream into messages as delimited by '\\n' or '\\0' [A] Ensure that each message (a successful read call) is obtained from a line [A] coming from underlying specifier, buffering up or splitting content as needed. Reverse of the `msg2line:`. Does not affect writing at all. Use this specifier on both ends to get bi-directional behaviour. Automatically inserted by --line option at the top of the stack opposite to websocket-containing stack. Example: TODO "# ); pub fn packet2line_peer(inner_peer: Peer, null_terminated: bool) -> BoxedNewPeerFuture { let filtered = Packet2LineWrapper(inner_peer.0, null_terminated); let thepeer = Peer::new(filtered, inner_peer.1); Box::new(ok(thepeer)) as BoxedNewPeerFuture } struct Packet2LineWrapper(Box<dyn AsyncRead>, bool); impl Read for Packet2LineWrapper { fn read(&mut self, b: &mut [u8]) -> Result<usize, IoError> { let l = b.len(); assert!(l > 1); let mut n = match self.0.read(&mut b[..(l - 1)]) { Ok(x) => x, Err(e) => return Err(e), }; if n == 0 { return Ok(n); } if !self.1 { // newline-terminated // chomp away \n or \r\n if n > 0 && b[n - 1] == b'\n' { n -= 1; } if n > 0 && b[n - 1] == b'\r' { n -= 1; } // replace those with spaces for c in b.iter_mut().take(n) { if *c == b'\n' || *c == b'\r' { *c = b' '; } } // add back one \n b[n] = b'\n'; n += 1; } else { // null-terminated if n > 0 && b[n - 1] == b'\x00' { n -= 1; } for c in b.iter_mut().take(n) { if *c == b'\x00' { warn!("zero byte in a message in null-terminated mode"); } } b[n] = b'\x00'; n += 1; } Ok(n) } } impl AsyncRead for Packet2LineWrapper {} pub fn line2packet_peer( inner_peer: Peer, retain_newlines: bool, strict: bool, null_terminated: bool, ) -> BoxedNewPeerFuture { let filtered = Line2PacketWrapper { inner: inner_peer.0, queue: vec![], retain_newlines, allow_incomplete_lines: !strict, drop_too_long_lines: strict, eof: false, null_terminated, }; let thepeer = Peer::new(filtered, inner_peer.1); Box::new(ok(thepeer)) as BoxedNewPeerFuture } struct Line2PacketWrapper { inner: Box<dyn AsyncRead>, queue: Vec<u8>, retain_newlines: bool, allow_incomplete_lines: bool, drop_too_long_lines: bool, eof: bool, null_terminated: bool, } impl Line2PacketWrapper { #[cfg_attr(feature = "cargo-clippy", allow(collapsible_if))] fn deliver_the_line(&mut self, buf: &mut [u8], mut n: usize) -> Option<usize> { if n > buf.len() { if self.drop_too_long_lines { error!("Dropping too long line of {} bytes because of buffer (-B option) is only {} bytes", n, buf.len()); drop(self.queue.drain(0..n)); return None; } else { warn!("Splitting too long line of {} bytes because of buffer (-B option) is only {} bytes", n, buf.len()); n = buf.len(); } } else { if !self.retain_newlines && !self.null_terminated { if n > 0 && (buf[n - 1] == b'\n') { n -= 1 } if n > 0 && (buf[n - 1] == b'\r') { n -= 1 } } if self.null_terminated { if n > 0 && (buf[n - 1] == b'\x00') { n -= 1 } } } buf[0..n].copy_from_slice(&self.queue[0..n]); drop(self.queue.drain(0..n)); Some(n) } } impl Read for Line2PacketWrapper { #[cfg_attr(feature = "cargo-clippy", allow(collapsible_if))] fn read(&mut self, buf: &mut [u8]) -> Result<usize, IoError> { //eprint!("ql={} ", self.queue.len()); if self.eof { return Ok(0); } let char_to_look_at = if self.null_terminated { b'\x00' } else { b'\n' }; let mut queued_line_len = None; for i in 0..self.queue.len() { if self.queue[i] == char_to_look_at { queued_line_len = Some(i); break; } } //eprint!("qll={:?} ", queued_line_len); if let Some(mut n) = queued_line_len { n += 1; if let Some(nn) = self.deliver_the_line(buf, n) { Ok(nn) } else { // line dropped, recursing self.read(buf) } } else { let mut n = match self.inner.read(buf) { Ok(x) => x, Err(e) => return Err(e), }; if n == 0 { self.eof = true; if !self.queue.is_empty() { if self.allow_incomplete_lines { warn!("Sending possibly incomplete line."); let bl = self.queue.len(); if let Some(nn) = self.deliver_the_line(buf, bl) { return Ok(nn); } } else { warn!( "Throwing away {} bytes of incomplete line", self.queue.len() ); } } return Ok(0); } let happy_case = if !self.null_terminated { self.queue.is_empty() && (!buf[0..(n - 1)].contains(&b'\n')) && buf[n - 1] == b'\n' } else { self.queue.is_empty() && (!buf[0..(n - 1)].contains(&b'\x00')) && buf[n - 1] == b'\x00' }; if happy_case { // Specifically to avoid allocations when data is already nice if !self.retain_newlines && !self.null_terminated { if n > 0 && (buf[n - 1] == b'\n') { n -= 1 } if n > 0 && (buf[n - 1] == b'\r') { n -= 1 } } if self.null_terminated { if n > 0 && (buf[n - 1] == b'\x00') { n -= 1 } } //eprintln!("happy n={}", n); Ok(n) } else { // Just queue up and recurse self.queue.extend_from_slice(&buf[0..n]); //eprintln!(" recurse"); self.read(buf) } } } } impl AsyncRead for Line2PacketWrapper {}
32.230241
122
0.513168
3a4dd14d956e1018313ce8f87f15ce956228fbf9
2,086
use nagamochi::Config; use notify_rust::Notification; use seahorse::{App, Context}; use std::{env, path::PathBuf, time}; fn main() { let args: Vec<String> = env::args().collect(); let app = App::new(env!("CARGO_PKG_NAME")) .description(env!("CARGO_PKG_DESCRIPTION")) .author(env!("CARGO_PKG_AUTHORS")) .version(env!("CARGO_PKG_VERSION")) .usage("nagamochi") .action(default_action); app.run(args); } fn default_action(_: &Context) { println!("Nagamochi is running!"); loop { let config = nagamochi::find_config().unwrap_or_else(|e| { eprintln!("Error: Failed to load config: {:?}", e); Config::default() }); // TODO: BAT0の場合などにも対応する let path = PathBuf::from("/sys/class/power_supply/").join("BAT1/capacity"); let capa = nagamochi::read_capacity(path).unwrap(); config .triggers .iter() .filter(|trigger| trigger.is_fired(capa)) .filter(|trigger| { let is_ac = nagamochi::is_ac_connected(PathBuf::from( "/sys/class/power_supply/ACAD/online", )) .unwrap_or_else(|e| { eprintln!("Error: Failed to find AC status: {:?}", e); false }); trigger.suppressors.iter().any(|sup| !sup.is_enabled(is_ac)) }) .for_each(|trigger| { if let Some(path) = &trigger.sound_file { if let Err(e) = nagamochi::play_sound(path) { eprintln!("Error: Failed to play a sound: {}", e); } } if let Err(e) = Notification::new() .summary("nagamochi") .body(&trigger.message) .show() { eprintln!("Error: Failed to send a notification: {}", e); } }); std::thread::sleep(time::Duration::from_secs(config.check_interval)); } }
34.766667
83
0.499041
c15f29960ac8ff37ee07a28d6a93684548813079
6,665
//! A pool of data required for api tests. // Built-in uses use std::{ cmp::max, collections::{BTreeMap, HashMap, VecDeque}, sync::Arc, }; // External uses use rand::{thread_rng, Rng}; use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}; // Workspace uses use zksync_api_client::rest::v1::Pagination; use zksync_types::{tx::TxHash, AccountId, Address, BlockNumber, PriorityOp, ZkSyncPriorityOp}; // Local uses /// Maximum limit value in the requests. const MAX_REQUEST_LIMIT: usize = 100; /// The maximum number of items in queues to reduce memory consumption. const MAX_QUEUE_LEN: usize = 100; #[derive(Debug, Default, Clone)] pub struct AddressData { /// Total count of transactions related to the address. pub txs_count: usize, /// Total count of priority operations related to the address. pub ops_count: usize, /// Associated account ID. pub account_id: Option<AccountId>, } /// Generates a `(offset, limit)` pair for the corresponding API request. fn gen_offset_limit_pair(count: usize) -> (usize, usize) { let mut rng = thread_rng(); // First argument of `gen_range` should be less than the second, // so if count is zero we should return zero to create a correct pair. let offset = rng.gen_range(0, max(1, count)); // We can safely use any value in range `[0, MAX_REQUEST_LIMIT]` as the limit. let limit = rng.gen_range(1, MAX_REQUEST_LIMIT + 1); (offset, limit) } impl AddressData { /// Generates a `(offset, limit)` pair for transaction requests related to the address. pub fn gen_txs_offset_limit(&self) -> (usize, usize) { gen_offset_limit_pair(self.txs_count) } /// Generates a `(offset, limit)` pair for priority operation requests related to the address. pub fn gen_ops_offset_limit(&self) -> (usize, usize) { gen_offset_limit_pair(self.ops_count) } } // TODO: In theory, we can use a simpler, fixed size deque instead of the standard one (ZKS-104). /// API data pool contents. #[derive(Debug, Default)] pub struct ApiDataPoolInner { addresses: Vec<Address>, data_by_address: HashMap<Address, AddressData>, txs: VecDeque<TxHash>, priority_ops: VecDeque<PriorityOp>, // Blocks with the counter of known transactions in them. blocks: BTreeMap<BlockNumber, usize>, max_block_number: BlockNumber, } impl ApiDataPoolInner { pub fn store_address(&mut self, address: Address) -> &mut AddressData { self.addresses.push(address); self.data_by_address.entry(address).or_default() } pub fn set_account_id(&mut self, address: Address, account_id: AccountId) { self.store_address(address).account_id = Some(account_id); } pub fn random_address(&self) -> (Address, &AddressData) { let idx = thread_rng().gen_range(0, self.addresses.len()); let address = self.addresses[idx]; (address, &self.data_by_address[&address]) } pub fn store_tx_hash(&mut self, address: Address, tx_hash: TxHash) { self.txs.push_back(tx_hash); if self.txs.len() > MAX_QUEUE_LEN { self.txs.pop_front(); } self.store_address(address).txs_count += 1; } pub fn random_tx_hash(&self) -> TxHash { let idx = thread_rng().gen_range(0, self.txs.len()); self.txs[idx] } pub fn store_priority_op(&mut self, priority_op: PriorityOp) { if let ZkSyncPriorityOp::Deposit(deposit) = &priority_op.data { self.store_address(deposit.to).ops_count += 1; } self.priority_ops.push_back(priority_op); if self.priority_ops.len() > MAX_QUEUE_LEN { self.priority_ops.pop_front(); } } pub fn random_priority_op(&self) -> PriorityOp { let idx = thread_rng().gen_range(0, self.priority_ops.len()); self.priority_ops[idx].clone() } pub fn store_block(&mut self, number: BlockNumber) { self.max_block_number = max(self.max_block_number, number); // Update known transactions count in the block. *self.blocks.entry(number).or_default() += 1; if self.blocks.len() > MAX_QUEUE_LEN { // TODO: replace by the pop_first then the `map_first_last` becomes stable (ZKS-104). let key = *self.blocks.keys().next().unwrap(); self.blocks.remove(&key); } } /// Generates a random block number in range [0, max block number]. pub fn random_block(&self) -> BlockNumber { self.random_tx_location().0 } /// Generates a random pagination block range. pub fn random_block_range(&self) -> (Pagination, BlockNumber) { let mut rng = thread_rng(); let block_number = self.random_block(); let pagination = match rng.gen_range(0, 3) { 0 => Pagination::Before(block_number), 1 => Pagination::After(block_number), 2 => Pagination::Last, _ => unreachable!(), }; let limit = rng.gen_range(1, MAX_REQUEST_LIMIT + 1); (pagination, BlockNumber(limit as u32)) } /// Generates a random transaction identifier (block number, position in block). pub fn random_tx_location(&self) -> (BlockNumber, usize) { let from = *self.blocks.keys().next().unwrap(); let to = self.max_block_number; let mut rng = thread_rng(); // Sometimes we have gaps in the block list, so it is not always // possible to randomly generate an existing block number. for _ in 0..MAX_REQUEST_LIMIT { let number = BlockNumber(rng.gen_range(*from, *to + 1)); if let Some(&block_txs) = self.blocks.get(&number) { let tx_id = rng.gen_range(0, block_txs); return (number, tx_id); } } unreachable!( "Unable to find the appropriate block number after {} attempts.", MAX_REQUEST_LIMIT ); } } /// Provides needed data for the API load tests. #[derive(Debug, Clone, Default)] pub struct ApiDataPool { inner: Arc<RwLock<ApiDataPoolInner>>, } impl ApiDataPool { /// Max limit in the API requests with limit. pub const MAX_REQUEST_LIMIT: usize = MAX_REQUEST_LIMIT; /// Creates a new pool instance. pub fn new() -> Self { Self::default() } /// Gets readonly access to the pool content. pub async fn read(&self) -> RwLockReadGuard<'_, ApiDataPoolInner> { self.inner.read().await } /// Gets writeable access to the pool content. pub async fn write(&self) -> RwLockWriteGuard<'_, ApiDataPoolInner> { self.inner.write().await } }
33.832487
98
0.644561
5dcade81a7da89afd40616d07bb5fb159edb1448
11,254
use crate::capability::native::{normalize_link_name, NativeCapability}; use crate::control_interface::ctlactor::{ControlInterface, PublishEvent}; use crate::dispatch::{Invocation, InvocationResponse, ProviderDispatcher, WasmCloudEntity}; use crate::hlreg::HostLocalSystemService; use crate::messagebus::{EnforceLocalProviderLinks, MessageBus, Subscribe}; use crate::middleware::{run_capability_post_invoke, run_capability_pre_invoke, Middleware}; use crate::{ControlEvent, Result}; use crate::{Host, SYSTEM_ACTOR}; use actix::prelude::*; use futures::executor::block_on; use libloading::{Library, Symbol}; use std::env::temp_dir; use std::fs::File; use wascap::prelude::KeyPair; use wascc_codec::capabilities::{ CapabilityDescriptor, CapabilityProvider, OP_GET_CAPABILITY_DESCRIPTOR, }; #[derive(Message)] #[rtype(result = "Result<WasmCloudEntity>")] pub(crate) struct Initialize { pub cap: NativeCapability, pub mw_chain: Vec<Box<dyn Middleware>>, pub seed: String, pub image_ref: Option<String>, } struct State { cap: NativeCapability, mw_chain: Vec<Box<dyn Middleware>>, kp: KeyPair, library: Option<Library>, plugin: Box<dyn CapabilityProvider + 'static>, image_ref: Option<String>, } pub(crate) struct NativeCapabilityHost { state: Option<State>, } impl NativeCapabilityHost { pub fn new() -> Self { NativeCapabilityHost { state: None } } } impl Actor for NativeCapabilityHost { type Context = SyncContext<Self>; fn started(&mut self, _ctx: &mut Self::Context) { info!("Native provider host started"); } fn stopped(&mut self, _ctx: &mut Self::Context) { if self.state.is_none() { //warn!("Stopped a provider host that had no state. Something might be amiss, askew, or perchance awry"); return; } let state = self.state.as_mut().unwrap(); state.plugin.stop(); // Tell the provider to clean up, dispose of resources, stop threads, etc if let Some(l) = state.library.take() { let r = l.close(); if let Err(_e) = r { // } } } } impl Handler<Initialize> for NativeCapabilityHost { type Result = Result<WasmCloudEntity>; fn handle(&mut self, msg: Initialize, ctx: &mut Self::Context) -> Self::Result { let (library, plugin) = match extrude(&msg.cap) { Ok((l, r)) => (l, r), Err(e) => { error!("Failed to extract plugin from provider: {}", e); ctx.stop(); return Err("Failed to extract plugin from provider".into()); } }; // NOTE: used to invoke get descriptor here, but we no longer obtain that information // from the provider at runtime, it's obtained from the now-mandatory (0.15.0+) claims self.state = Some(State { cap: msg.cap, mw_chain: msg.mw_chain, kp: KeyPair::from_seed(&msg.seed)?, library, plugin, image_ref: msg.image_ref, }); let state = self.state.as_ref().unwrap(); let b = MessageBus::from_hostlocal_registry(&state.kp.public_key()); let b2 = b.clone(); let link_name = normalize_link_name(state.cap.link_name.to_string()); let entity = WasmCloudEntity::Capability { id: state.cap.claims.subject.to_string(), contract_id: state .cap .claims .metadata .as_ref() .unwrap() .capid .to_string(), link_name: link_name.to_string(), }; let nativedispatch = ProviderDispatcher::new( b.clone().recipient(), KeyPair::from_seed(&state.kp.seed().unwrap()).unwrap(), entity.clone(), ); if let Err(e) = state.plugin.configure_dispatch(Box::new(nativedispatch)) { error!( "Failed to configure provider dispatcher: {}, provider stopping.", e ); ctx.stop(); return Err(e); } let url = entity.url().to_string(); let submsg = Subscribe { interest: entity.clone(), subscriber: ctx.address().recipient(), }; let _ = block_on(async move { if let Err(e) = b.send(submsg).await { error!( "Native capability provider failed to subscribe to bus: {}", e ); ctx.stop(); } else { } }); let epl = EnforceLocalProviderLinks { provider_id: state.cap.claims.subject.to_string(), link_name: link_name.to_string(), }; let _ = block_on(async move { // If the target provider for any known links involving this provider // are present, perform the bind actor func call let _ = b2.send(epl).await; }); let cp = ControlInterface::from_hostlocal_registry(&state.kp.public_key()); cp.do_send(PublishEvent { event: ControlEvent::ProviderStarted { link_name, provider_id: state.cap.claims.subject.to_string(), contract_id: state .cap .claims .metadata .as_ref() .unwrap() .capid .to_string(), image_ref: state.image_ref.clone(), }, }); info!("Native Capability Provider '{}' ready", url); Ok(entity) } } impl Handler<Invocation> for NativeCapabilityHost { type Result = InvocationResponse; /// Receives an invocation from any source, validating the anti-forgery token /// and that the destination matches this process. If those checks pass, runs /// the capability provider pre-invoke middleware, invokes the operation on the native /// plugin, then runs the provider post-invoke middleware. fn handle(&mut self, inv: Invocation, _ctx: &mut Self::Context) -> Self::Result { let state = self.state.as_ref().unwrap(); trace!( "Provider {} handling invocation operation '{}'", state.cap.claims.subject, inv.operation ); if let WasmCloudEntity::Actor(ref s) = inv.origin { if let WasmCloudEntity::Capability { id, .. } = &inv.target { if id != &state.cap.id() { return InvocationResponse::error( &inv, "Invocation target ID did not match provider ID", ); } if let Err(e) = run_capability_pre_invoke(&inv, &state.mw_chain) { return InvocationResponse::error( &inv, &format!("Capability middleware pre-invoke failure: {}", e), ); } match state.plugin.handle_call(&s, &inv.operation, &inv.msg) { Ok(msg) => { let ir = InvocationResponse::success(&inv, msg); match run_capability_post_invoke(ir, &state.mw_chain) { Ok(r) => r, Err(e) => InvocationResponse::error( &inv, &format!("Capability middleware post-invoke failure: {}", e), ), } } Err(e) => InvocationResponse::error(&inv, &format!("{}", e)), } } else { InvocationResponse::error(&inv, "Invocation sent to the wrong target") } } else { InvocationResponse::error(&inv, "Attempt to invoke capability from non-actor origin") } } } fn extrude( cap: &NativeCapability, ) -> Result<(Option<Library>, Box<dyn CapabilityProvider + 'static>)> { use std::io::Write; if let Some(ref bytes) = cap.native_bytes { let path = temp_dir(); let path = path.join("wasmcloudcache"); let path = path.join(&cap.claims.subject); let path = path.join(format!( "{}", cap.claims.metadata.as_ref().unwrap().rev.unwrap_or(0) )); ::std::fs::create_dir_all(&path)?; let target = Host::native_target(); let path = path.join(&target); // If this file is already on disk, some other host has probably // created it so don't over-write if !path.exists() { let mut tf = File::create(&path)?; tf.write_all(&bytes)?; } type PluginCreate = unsafe fn() -> *mut dyn CapabilityProvider; let library = Library::new(&path)?; let plugin = unsafe { let constructor: Symbol<PluginCreate> = library.get(b"__capability_provider_create")?; let boxed_raw = constructor(); Box::from_raw(boxed_raw) }; Ok((Some(library), plugin)) } else { Ok((None, cap.plugin.clone().unwrap())) } } #[cfg(test)] mod test { use crate::capability::extras::{ExtrasCapabilityProvider, OP_REQUEST_GUID}; use crate::capability::native::NativeCapability; use crate::capability::native_host::NativeCapabilityHost; use crate::dispatch::{Invocation, WasmCloudEntity}; use crate::generated::extras::{GeneratorRequest, GeneratorResult}; use crate::SYSTEM_ACTOR; use actix::prelude::*; use wascap::prelude::KeyPair; #[actix_rt::test] async fn test_extras_actor() { let kp = KeyPair::new_server(); let seed = kp.seed().unwrap(); let extras = ExtrasCapabilityProvider::default(); let claims = crate::capability::extras::get_claims(); let cap = NativeCapability::from_instance(extras, Some("default".to_string()), claims).unwrap(); let extras = SyncArbiter::start(1, move || NativeCapabilityHost::new()); let init = crate::capability::native_host::Initialize { cap, mw_chain: vec![], seed, image_ref: None, }; let _ = extras.send(init).await.unwrap(); let req = GeneratorRequest { guid: true, sequence: false, random: false, min: 0, max: 0, }; let inv = Invocation::new( &kp, WasmCloudEntity::Actor(SYSTEM_ACTOR.to_string()), WasmCloudEntity::Capability { id: "VDHPKGFKDI34Y4RN4PWWZHRYZ6373HYRSNNEM4UTDLLOGO5B37TSVREP".to_string(), contract_id: "wascc:extras".to_string(), link_name: "default".to_string(), }, OP_REQUEST_GUID, crate::generated::core::serialize(&req).unwrap(), ); let ir = extras.send(inv).await.unwrap(); assert!(ir.error.is_none()); let gen_r: GeneratorResult = crate::generated::core::deserialize(&ir.msg).unwrap(); assert!(gen_r.guid.is_some()); } }
36.186495
117
0.55287
909c35d64f5486984f122ca2d1b47b6a21d26a8d
6,163
use std::cell::RefCell; use std::mem::drop; use std::ops::Deref; use std::sync::{self, Arc, Mutex}; use once_cell::sync::Lazy; use shredder::*; static TEST_MUTEX: Lazy<parking_lot::Mutex<()>> = Lazy::new(|| parking_lot::Mutex::new(())); #[derive(Debug, Scan)] struct DirectedGraphNode { label: String, edges: Vec<Gc<RefCell<DirectedGraphNode>>>, } #[test] fn alloc_u32_gc() { let _guard = TEST_MUTEX.lock(); run_with_gc_cleanup(|| { assert_eq!(number_of_tracked_allocations(), 0); let val = 7; let gc_ptr = Gc::new(val); assert_eq!(*gc_ptr.get(), val); drop(gc_ptr); collect(); assert_eq!(number_of_tracked_allocations(), 0); }); } #[test] fn alloc_directed_graph_node_gc() { let _guard = TEST_MUTEX.lock(); run_with_gc_cleanup(|| { assert_eq!(number_of_tracked_allocations(), 0); let node = DirectedGraphNode { label: "A".to_string(), edges: Vec::new(), }; let gc_ptr = Gc::new(node); assert_eq!(gc_ptr.get().label, "A"); drop(gc_ptr); collect(); assert_eq!(number_of_tracked_allocations(), 0); }); } #[test] fn clone_directed_graph_node_gc() { let _guard = TEST_MUTEX.lock(); run_with_gc_cleanup(|| { assert_eq!(number_of_tracked_allocations(), 0); assert_eq!(number_of_active_handles(), 0); let node = DirectedGraphNode { label: "A".to_string(), edges: Vec::new(), }; let gc_ptr_one = Gc::new(node); let gc_ptr_two = gc_ptr_one.clone(); assert_eq!(number_of_tracked_allocations(), 1); assert_eq!(number_of_active_handles(), 2); assert_eq!(gc_ptr_one.get().label, "A"); assert_eq!(gc_ptr_two.get().label, "A"); drop(gc_ptr_one); drop(gc_ptr_two); collect(); assert_eq!(number_of_tracked_allocations(), 0); }); } #[test] fn clone_directed_graph_chain_gc() { let _guard = TEST_MUTEX.lock(); run_with_gc_cleanup(|| { assert_eq!(number_of_tracked_allocations(), 0); assert_eq!(number_of_active_handles(), 0); let node = DirectedGraphNode { label: "A".to_string(), edges: Vec::new(), }; let gc_ptr_one = Gc::new(RefCell::new(node)); let gc_ptr_two = gc_ptr_one.clone(); assert_eq!(number_of_tracked_allocations(), 1); assert_eq!(number_of_active_handles(), 2); assert_eq!(gc_ptr_one.get().borrow().label, "A"); assert_eq!(gc_ptr_two.get().borrow().label, "A"); gc_ptr_two .get() .deref() .borrow_mut() .edges .push(gc_ptr_one.clone()); drop(gc_ptr_one); drop(gc_ptr_two); collect(); assert_eq!(number_of_tracked_allocations(), 0); }); } #[derive(Debug, Default, Scan)] struct Connection { connect: Option<Gc<sync::Mutex<Connection>>>, } #[test] fn scan_skip_problem() { let _guard = TEST_MUTEX.lock(); run_with_gc_cleanup(|| { assert_eq!(number_of_tracked_allocations(), 0); let root_con = Gc::new(sync::Mutex::new(Connection::default())); eprintln!("root {:?}", root_con); // FIXME: Use shortcut methods here let hidden = Gc::new(sync::Mutex::new(Connection::default())); eprintln!("hidden {:?}", hidden); let hider = Gc::new(sync::Mutex::new(Connection::default())); eprintln!("hider {:?}", hider); { let hidden_clone_1 = hidden.clone(); eprintln!("hidden clone 1 {:?}", hidden_clone_1); root_con.lock().unwrap().connect = Some(hidden_clone_1); let hidden_clone_2 = hidden.clone(); eprintln!("hidden clone 2 {:?}", hidden_clone_2); hider.lock().unwrap().connect = Some(hidden_clone_2); } drop(hidden); drop(hider); let root_gc_guard = root_con.get(); let root_blocker = root_gc_guard.lock().unwrap(); collect(); assert_eq!(number_of_tracked_allocations(), 2); drop(root_blocker); drop(root_gc_guard); drop(root_con); collect(); assert_eq!(number_of_tracked_allocations(), 0); }); } #[derive(Scan)] struct Finalizable<'a> { #[shredder(skip)] tracker: Arc<Mutex<String>>, _marker: R<'a, str>, } unsafe impl<'a> Finalize for Finalizable<'a> { unsafe fn finalize(&mut self) { let mut tracker = self.tracker.lock().unwrap(); *tracker = String::from("finalized"); } } impl<'a> Drop for Finalizable<'a> { fn drop(&mut self) { let mut tracker = self.tracker.lock().unwrap(); *tracker = String::from("dropped"); } } #[test] fn drop_run() { let _guard = TEST_MUTEX.lock(); let tracker = Arc::new(Mutex::new(String::from("none"))); run_with_gc_cleanup(|| { let _to_drop = Gc::new(Finalizable { tracker: tracker.clone(), _marker: R::new("a static string, safe in drop :)"), }); }); assert_eq!(&*(tracker.lock().unwrap()), "dropped"); assert_eq!(number_of_tracked_allocations(), 0); } #[test] fn finalizers_run() { let _guard = TEST_MUTEX.lock(); let tracker = Arc::new(Mutex::new(String::from("none"))); run_with_gc_cleanup(|| { let s = String::from("just a temp string"); let _to_drop = Gc::new_with_finalizer(Finalizable { tracker: tracker.clone(), _marker: R::new(&s), }); }); assert_eq!(&*(tracker.lock().unwrap()), "finalized"); assert_eq!(number_of_tracked_allocations(), 0); } #[test] fn no_drop_functional() { let _guard = TEST_MUTEX.lock(); let tracker = Arc::new(Mutex::new(String::from("none"))); run_with_gc_cleanup(|| { let s = String::from("just a temp string"); let _to_drop = Gc::new_no_drop(Finalizable { tracker: tracker.clone(), _marker: R::new(&s), }); }); assert_eq!(&*(tracker.lock().unwrap()), "none"); assert_eq!(number_of_tracked_allocations(), 0); }
27.513393
92
0.580561
eb558c5ee44b344f020d4db59fe356cae7605c80
4,237
// Copyright 2016 The pliOS Developers. See the LICENSE // file at the top-level directory of this distribution. // // Licensed under the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>. This file may not // be copied, modified, or distributed except according // to these terms. //! Page frame allocator use spin::Mutex; use core::ptr::Unique; use core::mem::size_of; #[macro_use] use arch; use utils; /// Initialize the allocator /// /// bump_start is where the page entries are allocated from /// length is the total length of the memory in the system pub fn init(bump_start: usize, length: usize) { ALLOCATOR.lock().init(bump_start, length); } /// Add a memory region to this allocator. /// /// from is the start address of the region /// length is the number of pages in this region pub fn add_memory_region(from: usize, length: usize) { ALLOCATOR.lock().add_memory_region(from, length); } static ALLOCATOR: Mutex<BuddyAlloc> = Mutex::new(BuddyAlloc::new()); pub struct Page { /// Reference count use_count: u32, /// Order (how many pages were allocated with this one) order: u8, /// Page frame number (address divided by page size) page_number: usize, /// Next page next: Option<Unique<Page>>, /// Next free page next_free: Option<Unique<Page>>, } struct BuddyMap { /// List of free pages pages: Option<Unique<Page>>, /// Length of the pages list (multiply by 2**order to get number of pages) length: usize, } struct BuddyAlloc { /// List of all pages pages: Option<Unique<Page>>, /// Length of the pages list length: usize, /// Buddy maps buddies: [BuddyMap; 6], /// Allocator info bump allocator start address bump_start: usize, /// Allocator info bump allocator current address bump_current: usize, /// Allocator info bump allocator end address bump_end: usize, } impl BuddyAlloc { const fn new() -> BuddyAlloc { BuddyAlloc { pages: None, length: 0, buddies: [ BuddyMap { pages: None, length: 0 }, BuddyMap { pages: None, length: 0 }, BuddyMap { pages: None, length: 0 }, BuddyMap { pages: None, length: 0 }, BuddyMap { pages: None, length: 0 }, BuddyMap { pages: None, length: 0 }, ], bump_start: 0, bump_current: 0, bump_end: 0, } } fn init(&mut self, bump_start: usize, length: usize) { let pages = (length / arch::PAGE_SIZE) + 1; self.bump_start = bump_start; self.bump_current = bump_start; self.bump_end = bump_start + pages * size_of::<Page>(); } fn add_memory_region(&mut self, from: usize, length: usize) { if from + length <= self.bump_end { return } let unaligned_from = if from <= self.bump_end { self.bump_end } else { from }; let adjusted_from = utils::round_up_2(unaligned_from, 0x1000); let adjusted_length = length - (adjusted_from - from); let pages = adjusted_length / arch::PAGE_SIZE; let mut page = 0; let mut buddy = 5; while buddy >= 0 { let buddy_length = 2usize.pow(buddy as u32); while page + buddy_length < pages { for _ in (0..buddy_length) { self.add_page(); } page += buddy_length; } buddy -= 1; } early_println!("{} pages from {:x}", pages, adjusted_from); early_println!("{:x} to {:x}, current {:x}", self.bump_start, self.bump_end, self.bump_current); } fn add_page(&mut self) -> *mut Page { let page_ptr: *mut Page = self.bump_current as *mut Page; self.bump_current += size_of::<Page>(); if self.bump_current > self.bump_end { panic!("More memory pages added to PFA than expected"); } let page = unsafe { page_ptr.as_mut().unwrap() }; page.use_count = 0; page.order = 0; page.page_number = 0; page.next = None; page.next_free = None; page_ptr } }
27.875
104
0.590276
f8c9659e5a6c0759653c86e6c0658e48d6a6df9a
23,817
// 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. mod longest_path; use hashbrown::{HashMap, HashSet}; use std::cmp::Ordering; use std::collections::BinaryHeap; use super::iterators::NodeIndices; use crate::{digraph, DAGHasCycle, InvalidNode}; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; use pyo3::types::PyList; use pyo3::Python; use petgraph::algo; use petgraph::graph::NodeIndex; use petgraph::prelude::*; use petgraph::visit::NodeCount; /// Find the longest path in a DAG /// /// :param PyDiGraph graph: The graph to find the longest path on. The input /// object must be a DAG without a cycle. /// :param weight_fn: A python callable that if set will be passed the 3 /// positional arguments, the source node, the target node, and the edge /// weight for each edge as the function traverses the graph. It is expected /// to return an unsigned integer weight for that edge. For example, /// ``dag_longest_path(graph, lambda: _, __, weight: weight)`` could be /// use to just use an integer edge weight. It's also worth noting that this /// function traverses in topological order and only checks incoming edges to /// each node. /// /// :returns: The node indices of the longest path on the DAG /// :rtype: NodeIndices /// /// :raises Exception: If an unexpected error occurs or a path can't be found /// :raises DAGHasCycle: If the input PyDiGraph has a cycle #[pyfunction] #[pyo3(text_signature = "(graph, /, weight_fn=None)")] pub fn dag_longest_path( py: Python, graph: &digraph::PyDiGraph, weight_fn: Option<PyObject>, ) -> PyResult<NodeIndices> { let edge_weight_callable = |source: usize, target: usize, weight: &PyObject| -> PyResult<usize> { match &weight_fn { Some(weight_fn) => { let res = weight_fn.call1(py, (source, target, weight))?; res.extract(py) } None => Ok(1), } }; Ok(NodeIndices { nodes: longest_path::longest_path(graph, edge_weight_callable)?.0, }) } /// Find the length of the longest path in a DAG /// /// :param PyDiGraph graph: The graph to find the longest path on. The input /// object must be a DAG without a cycle. /// :param weight_fn: A python callable that if set will be passed the 3 /// positional arguments, the source node, the target node, and the edge /// weight for each edge as the function traverses the graph. It is expected /// to return an unsigned integer weight for that edge. For example, /// ``dag_longest_path(graph, lambda: _, __, weight: weight)`` could be /// use to just use an integer edge weight. It's also worth noting that this /// function traverses in topological order and only checks incoming edges to /// each node. /// /// :returns: The longest path length on the DAG /// :rtype: int /// /// :raises Exception: If an unexpected error occurs or a path can't be found /// :raises DAGHasCycle: If the input PyDiGraph has a cycle #[pyfunction] #[pyo3(text_signature = "(graph, /, weight_fn=None)")] pub fn dag_longest_path_length( py: Python, graph: &digraph::PyDiGraph, weight_fn: Option<PyObject>, ) -> PyResult<usize> { let edge_weight_callable = |source: usize, target: usize, weight: &PyObject| -> PyResult<usize> { match &weight_fn { Some(weight_fn) => { let res = weight_fn.call1(py, (source, target, weight))?; res.extract(py) } None => Ok(1), } }; let (_, path_weight) = longest_path::longest_path(graph, edge_weight_callable)?; Ok(path_weight) } /// Find the weighted longest path in a DAG /// /// This function differs from :func:`retworkx.dag_longest_path` in that /// this function requires a ``weight_fn`` parameter, and the ``weight_fn`` is /// expected to return a ``float`` not an ``int``. /// /// :param PyDiGraph graph: The graph to find the longest path on. The input /// object must be a DAG without a cycle. /// :param weight_fn: A python callable that will be passed the 3 /// positional arguments, the source node, the target node, and the edge /// weight for each edge as the function traverses the graph. It is expected /// to return a float weight for that edge. For example, /// ``dag_longest_path(graph, lambda: _, __, weight: weight)`` could be /// used to just use a float edge weight. It's also worth noting that this /// function traverses in topological order and only checks incoming edges to /// each node. /// /// :returns: The node indices of the longest path on the DAG /// :rtype: NodeIndices /// /// :raises Exception: If an unexpected error occurs or a path can't be found /// :raises DAGHasCycle: If the input PyDiGraph has a cycle #[pyfunction] #[pyo3(text_signature = "(graph, weight_fn, /)")] pub fn dag_weighted_longest_path( py: Python, graph: &digraph::PyDiGraph, weight_fn: PyObject, ) -> PyResult<NodeIndices> { let edge_weight_callable = |source: usize, target: usize, weight: &PyObject| -> PyResult<f64> { let res = weight_fn.call1(py, (source, target, weight))?; let float_res: f64 = res.extract(py)?; if float_res.is_nan() { return Err(PyValueError::new_err("NaN is not a valid edge weight")); } Ok(float_res) }; Ok(NodeIndices { nodes: longest_path::longest_path(graph, edge_weight_callable)?.0, }) } /// Find the length of the weighted longest path in a DAG /// /// This function differs from :func:`retworkx.dag_longest_path_length` in that /// this function requires a ``weight_fn`` parameter, and the ``weight_fn`` is /// expected to return a ``float`` not an ``int``. /// /// :param PyDiGraph graph: The graph to find the longest path on. The input /// object must be a DAG without a cycle. /// :param weight_fn: A python callable that will be passed the 3 /// positional arguments, the source node, the target node, and the edge /// weight for each edge as the function traverses the graph. It is expected /// to return a float weight for that edge. For example, /// ``dag_longest_path(graph, lambda: _, __, weight: weight)`` could be /// used to just use a float edge weight. It's also worth noting that this /// function traverses in topological order and only checks incoming edges to /// each node. /// /// :returns: The longest path length on the DAG /// :rtype: float /// /// :raises Exception: If an unexpected error occurs or a path can't be found /// :raises DAGHasCycle: If the input PyDiGraph has a cycle #[pyfunction] #[pyo3(text_signature = "(graph, weight_fn, /)")] pub fn dag_weighted_longest_path_length( py: Python, graph: &digraph::PyDiGraph, weight_fn: PyObject, ) -> PyResult<f64> { let edge_weight_callable = |source: usize, target: usize, weight: &PyObject| -> PyResult<f64> { let res = weight_fn.call1(py, (source, target, weight))?; let float_res: f64 = res.extract(py)?; if float_res.is_nan() { return Err(PyValueError::new_err("NaN is not a valid edge weight")); } Ok(float_res) }; let (_, path_weight) = longest_path::longest_path(graph, edge_weight_callable)?; Ok(path_weight) } /// Check that the PyDiGraph or PyDAG doesn't have a cycle /// /// :param PyDiGraph graph: The graph to check for cycles /// /// :returns: ``True`` if there are no cycles in the input graph, ``False`` /// if there are cycles /// :rtype: bool #[pyfunction] #[pyo3(text_signature = "(graph, /)")] pub fn is_directed_acyclic_graph(graph: &digraph::PyDiGraph) -> bool { match algo::toposort(&graph.graph, None) { Ok(_nodes) => true, Err(_err) => false, } } /// Return a list of layers /// /// A layer is a subgraph whose nodes are disjoint, i.e., /// a layer has depth 1. The layers are constructed using a greedy algorithm. /// /// :param PyDiGraph graph: The DAG to get the layers from /// :param list first_layer: A list of node ids for the first layer. This /// will be the first layer in the output /// /// :returns: A list of layers, each layer is a list of node data /// :rtype: list /// /// :raises InvalidNode: If a node index in ``first_layer`` is not in the graph #[pyfunction] #[pyo3(text_signature = "(dag, first_layer, /)")] pub fn layers(py: Python, dag: &digraph::PyDiGraph, first_layer: Vec<usize>) -> PyResult<PyObject> { let mut output: Vec<Vec<&PyObject>> = Vec::new(); // Convert usize to NodeIndex let mut first_layer_index: Vec<NodeIndex> = Vec::new(); for index in first_layer { first_layer_index.push(NodeIndex::new(index)); } let mut cur_layer = first_layer_index; let mut next_layer: Vec<NodeIndex> = Vec::new(); let mut predecessor_count: HashMap<NodeIndex, usize> = HashMap::new(); let mut layer_node_data: Vec<&PyObject> = Vec::new(); for layer_node in &cur_layer { let node_data = match dag.graph.node_weight(*layer_node) { Some(data) => data, None => { return Err(InvalidNode::new_err(format!( "An index input in 'first_layer' {} is not a valid node index in the graph", layer_node.index() ))) } }; layer_node_data.push(node_data); } output.push(layer_node_data); // Iterate until there are no more while !cur_layer.is_empty() { for node in &cur_layer { let children = dag .graph .neighbors_directed(*node, petgraph::Direction::Outgoing); let mut used_indices: HashSet<NodeIndex> = HashSet::new(); for succ in children { // Skip duplicate successors if used_indices.contains(&succ) { continue; } used_indices.insert(succ); let mut multiplicity: usize = 0; let raw_edges = dag .graph .edges_directed(*node, petgraph::Direction::Outgoing); for edge in raw_edges { if edge.target() == succ { multiplicity += 1; } } predecessor_count .entry(succ) .and_modify(|e| *e -= multiplicity) .or_insert(dag.in_degree(succ.index()) - multiplicity); if *predecessor_count.get(&succ).unwrap() == 0 { next_layer.push(succ); predecessor_count.remove(&succ); } } } let mut layer_node_data: Vec<&PyObject> = Vec::new(); for layer_node in &next_layer { layer_node_data.push(&dag.graph[*layer_node]); } if !layer_node_data.is_empty() { output.push(layer_node_data); } cur_layer = next_layer; next_layer = Vec::new(); } Ok(PyList::new(py, output).into()) } /// Get the lexicographical topological sorted nodes from the provided DAG /// /// This function returns a list of nodes data in a graph lexicographically /// topologically sorted using the provided key function. A topological sort /// is a linear ordering of vertices such that for every directed edge from /// node :math:`u` to node :math:`v`, :math:`u` comes before :math:`v` /// in the ordering. /// /// This function differs from :func:`~retworkx.topological_sort` because /// when there are ties between nodes in the sort order this function will /// use the string returned by the ``key`` argument to determine the output /// order used. /// /// :param PyDiGraph dag: The DAG to get the topological sorted nodes from /// :param callable key: key is a python function or other callable that /// gets passed a single argument the node data from the graph and is /// expected to return a string which will be used for resolving ties /// in the sorting order. /// /// :returns: A list of node's data lexicographically topologically sorted. /// :rtype: list #[pyfunction] #[pyo3(text_signature = "(dag, key, /)")] fn lexicographical_topological_sort( py: Python, dag: &digraph::PyDiGraph, key: PyObject, ) -> PyResult<PyObject> { let key_callable = |a: &PyObject| -> PyResult<PyObject> { let res = key.call1(py, (a,))?; Ok(res.to_object(py)) }; // HashMap of node_index indegree let node_count = dag.node_count(); let mut in_degree_map: HashMap<NodeIndex, usize> = HashMap::with_capacity(node_count); for node in dag.graph.node_indices() { in_degree_map.insert(node, dag.in_degree(node.index())); } #[derive(Clone, Eq, PartialEq)] struct State { key: String, node: NodeIndex, } impl Ord for State { fn cmp(&self, other: &State) -> Ordering { // Notice that the we flip the ordering on costs. // In case of a tie we compare positions - this step is necessary // to make implementations of `PartialEq` and `Ord` consistent. other .key .cmp(&self.key) .then_with(|| other.node.index().cmp(&self.node.index())) } } // `PartialOrd` needs to be implemented as well. impl PartialOrd for State { fn partial_cmp(&self, other: &State) -> Option<Ordering> { Some(self.cmp(other)) } } let mut zero_indegree = BinaryHeap::with_capacity(node_count); for (node, degree) in in_degree_map.iter() { if *degree == 0 { let map_key_raw = key_callable(&dag.graph[*node])?; let map_key: String = map_key_raw.extract(py)?; zero_indegree.push(State { key: map_key, node: *node, }); } } let mut out_list: Vec<&PyObject> = Vec::with_capacity(node_count); let dir = petgraph::Direction::Outgoing; while let Some(State { node, .. }) = zero_indegree.pop() { let neighbors = dag.graph.neighbors_directed(node, dir); for child in neighbors { let child_degree = in_degree_map.get_mut(&child).unwrap(); *child_degree -= 1; if *child_degree == 0 { let map_key_raw = key_callable(&dag.graph[child])?; let map_key: String = map_key_raw.extract(py)?; zero_indegree.push(State { key: map_key, node: child, }); in_degree_map.remove(&child); } } out_list.push(&dag.graph[node]) } Ok(PyList::new(py, out_list).into()) } /// Return the topological sort of node indices from the provided graph /// /// :param PyDiGraph graph: The DAG to get the topological sort on /// /// :returns: A list of node indices topologically sorted. /// :rtype: NodeIndices /// /// :raises DAGHasCycle: if a cycle is encountered while sorting the graph #[pyfunction] #[pyo3(text_signature = "(graph, /)")] fn topological_sort(graph: &digraph::PyDiGraph) -> PyResult<NodeIndices> { let nodes = match algo::toposort(&graph.graph, None) { Ok(nodes) => nodes, Err(_err) => return Err(DAGHasCycle::new_err("Sort encountered a cycle")), }; Ok(NodeIndices { nodes: nodes.iter().map(|node| node.index()).collect(), }) } /// Collect runs that match a filter function /// /// A run is a path of nodes where there is only a single successor and all /// nodes in the path match the given condition. Each node in the graph can /// appear in only a single run. /// /// :param PyDiGraph graph: The graph to find runs in /// :param filter_fn: The filter function to use for matching nodes. It takes /// in one argument, the node data payload/weight object, and will return a /// boolean whether the node matches the conditions or not. If it returns /// ``False`` it will skip that node. /// /// :returns: a list of runs, where each run is a list of node data /// payload/weight for the nodes in the run /// :rtype: list #[pyfunction] #[pyo3(text_signature = "(graph, filter)")] fn collect_runs( py: Python, graph: &digraph::PyDiGraph, filter_fn: PyObject, ) -> PyResult<Vec<Vec<PyObject>>> { let mut out_list: Vec<Vec<PyObject>> = Vec::new(); let mut seen: HashSet<NodeIndex> = HashSet::with_capacity(graph.node_count()); let filter_node = |node: &PyObject| -> PyResult<bool> { let res = filter_fn.call1(py, (node,))?; res.extract(py) }; let nodes = match algo::toposort(&graph.graph, None) { Ok(nodes) => nodes, Err(_err) => return Err(DAGHasCycle::new_err("Sort encountered a cycle")), }; for node in nodes { if !filter_node(&graph.graph[node])? || seen.contains(&node) { continue; } seen.insert(node); let mut group: Vec<PyObject> = vec![graph.graph[node].clone_ref(py)]; let mut successors: Vec<NodeIndex> = graph .graph .neighbors_directed(node, petgraph::Direction::Outgoing) .collect(); successors.dedup(); while successors.len() == 1 && filter_node(&graph.graph[successors[0]])? && !seen.contains(&successors[0]) { group.push(graph.graph[successors[0]].clone_ref(py)); seen.insert(successors[0]); successors = graph .graph .neighbors_directed(successors[0], petgraph::Direction::Outgoing) .collect(); successors.dedup(); } if !group.is_empty() { out_list.push(group); } } Ok(out_list) } /// Collect runs that match a filter function given edge colors /// /// A bicolor run is a list of group of nodes connected by edges of exactly /// two colors. In addition, all nodes in the group must match the given /// condition. Each node in the graph can appear in only a single group /// in the bicolor run. /// /// :param PyDiGraph graph: The graph to find runs in /// :param filter_fn: The filter function to use for matching nodes. It takes /// in one argument, the node data payload/weight object, and will return a /// boolean whether the node matches the conditions or not. /// If it returns ``True``, it will continue the bicolor chain. /// If it returns ``False``, it will stop the bicolor chain. /// If it returns ``None`` it will skip that node. /// :param color_fn: The function that gives the color of the edge. It takes /// in one argument, the edge data payload/weight object, and will /// return a non-negative integer, the edge color. If the color is None, /// the edge is ignored. /// /// :returns: a list of groups with exactly two edge colors, where each group /// is a list of node data payload/weight for the nodes in the bicolor run /// :rtype: list #[pyfunction] #[pyo3(text_signature = "(graph, filter_fn, color_fn)")] fn collect_bicolor_runs( py: Python, graph: &digraph::PyDiGraph, filter_fn: PyObject, color_fn: PyObject, ) -> PyResult<Vec<Vec<PyObject>>> { let mut pending_list: Vec<Vec<PyObject>> = Vec::new(); let mut block_id: Vec<Option<usize>> = Vec::new(); let mut block_list: Vec<Vec<PyObject>> = Vec::new(); let filter_node = |node: &PyObject| -> PyResult<Option<bool>> { let res = filter_fn.call1(py, (node,))?; res.extract(py) }; let color_edge = |edge: &PyObject| -> PyResult<Option<usize>> { let res = color_fn.call1(py, (edge,))?; res.extract(py) }; let nodes = match algo::toposort(&graph.graph, None) { Ok(nodes) => nodes, Err(_err) => return Err(DAGHasCycle::new_err("Sort encountered a cycle")), }; // Utility for ensuring pending_list has the color index macro_rules! ensure_vector_has_index { ($pending_list: expr, $block_id: expr, $color: expr) => { if $color >= $pending_list.len() { $pending_list.resize($color + 1, Vec::new()); $block_id.resize($color + 1, None); } }; } for node in nodes { if let Some(is_match) = filter_node(&graph.graph[node])? { let raw_edges = graph .graph .edges_directed(node, petgraph::Direction::Outgoing); // Remove all edges that do not yield errors from color_fn let colors = raw_edges .map(|edge| { let edge_weight = edge.weight(); color_edge(edge_weight) }) .collect::<PyResult<Vec<Option<usize>>>>()?; // Remove null edges from color_fn let colors = colors.into_iter().flatten().collect::<Vec<usize>>(); if colors.len() <= 2 && is_match { if colors.len() == 1 { let c0 = colors[0]; ensure_vector_has_index!(pending_list, block_id, c0); if let Some(c0_block_id) = block_id[c0] { block_list[c0_block_id].push(graph.graph[node].clone_ref(py)); } else { pending_list[c0].push(graph.graph[node].clone_ref(py)); } } else if colors.len() == 2 { let c0 = colors[0]; let c1 = colors[1]; ensure_vector_has_index!(pending_list, block_id, c0); ensure_vector_has_index!(pending_list, block_id, c1); if block_id[c0].is_some() && block_id[c1].is_some() && block_id[c0] == block_id[c1] { block_list[block_id[c0].unwrap_or_default()] .push(graph.graph[node].clone_ref(py)); } else { let mut new_block: Vec<PyObject> = Vec::with_capacity(pending_list[c0].len() + pending_list[c1].len() + 1); // Clears pending lits and add to new block new_block.append(&mut pending_list[c0]); new_block.append(&mut pending_list[c1]); new_block.push(graph.graph[node].clone_ref(py)); // Create new block, assign its id to color pair block_id[c0] = Some(block_list.len()); block_id[c1] = Some(block_list.len()); block_list.push(new_block); } } } else { for color in colors { let color = color; ensure_vector_has_index!(pending_list, block_id, color); if let Some(color_block_id) = block_id[color] { block_list[color_block_id].append(&mut pending_list[color]); } block_id[color] = None; pending_list[color].clear(); } } } } Ok(block_list) }
39.237232
100
0.604694
1a0449753e6880875dfe81f8f82a08f50e944bc8
3,080
use std::fmt::Display; use shared::utils; use shared::grid::*; lazy_static! { // static ref INPUT: Vec<String> = utils::read_sample_input_lines("day04"); static ref INPUT: Vec<String> = utils::read_input_lines("day04"); } #[derive(Debug, Default)] struct BingoSquare { num: usize, marked: bool, } impl Display for BingoSquare { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if self.marked { write!(f, "[{:2}] ", self.num) } else { write!(f, " {:2} ", self.num) } } } fn parse_input() -> (Vec<usize>, Vec<Grid<BingoSquare>>) { let called_nums = INPUT[0] .to_string() .split(',') .map(|n| n.parse().unwrap()) .collect(); let boards = utils::group_lines(&INPUT[2..]) .into_iter() .map(|board| { let mut grid = Grid::new(5); for (y, row) in board.iter().enumerate() { for (x, cell) in row.split_whitespace().enumerate() { grid[GridIndex(x, y)] = BingoSquare { num: cell.parse().unwrap(), marked: false, } } } grid }) .collect(); (called_nums, boards) } fn is_done(grid: &Grid<BingoSquare>) -> bool { let mut col_count = vec![0; grid.width()]; for row in grid.rows() { let mut row_count = 0; for (x, cell) in row.iter().enumerate() { if cell.marked { col_count[x] += 1; row_count += 1; } } if row_count == grid.width() { return true; } } col_count.iter().any(|&c| c == grid.height()) } fn update_board(called_num: usize, board: &mut Grid<BingoSquare>) { for square in board.iter_mut() { if square.num == called_num { square.marked = true; return; } } } fn score_board(called_num: usize, board: &Grid<BingoSquare>) -> usize { let sum = board .iter() .filter_map(|square| { if !square.marked { return Some(square.num); } None }) .sum::<usize>(); called_num * sum } pub fn part1() -> usize { let (called_nums, mut boards) = parse_input(); for called_num in called_nums.iter() { for b in boards.iter_mut() { update_board(*called_num, b); } if let Some(b) = boards.iter().find(|b| is_done(b)) { return score_board(*called_num, b); } } unreachable!() } pub fn part2() -> usize { let (called_nums, mut boards) = parse_input(); for called_num in called_nums.iter() { for b in boards.iter_mut() { update_board(*called_num, b); } if boards.len() == 1 { if is_done(&boards[0]) { return score_board(*called_num, &boards[0]); } continue; } boards.retain(|b| !is_done(b)); } unreachable!() }
25.666667
79
0.493506
8a10699b0fcb689526e24c4ac29a9a9cedab9ffb
6,983
use crate::infrastructure::{config, graphql, repositories, security}; use actix_web::{dev, error, web, Error, FromRequest, HttpRequest, HttpResponse, Result}; use futures_util::future::{FutureExt, LocalBoxFuture}; use graphql_parser::query; use juniper::{http, DefaultScalarValue, InputValue, ScalarValue}; use serde::{Deserialize, Serialize}; pub async fn handler( db_pool: web::Data<repositories::PostgresPool>, schema: web::Data<graphql::Schema>, req: GraphQLAuthentication, ) -> Result<HttpResponse> { let config = req.config(); let viewer = req.viewer(); let ctx = graphql::Context { db_pool: db_pool.get_ref().to_owned(), config, viewer, }; let res = web::block(move || { let res = req.graphql().execute(&schema, &ctx); Ok::<_, serde_json::error::Error>(serde_json::to_string(&res)?) }) .await .map_err(Error::from)?; Ok(HttpResponse::Ok() .content_type("application/json") .body(res)) } pub async fn graphiql(config: web::Data<config::Settings>) -> HttpResponse { let html = http::graphiql::graphiql_source(&format!("{}/graphql", config.base_url())); HttpResponse::Ok() .content_type("text/html; charset=utf-8") .body(html) } pub struct GraphQLAuthentication { gql: http::GraphQLRequest, config: config::Settings, viewer: security::Viewer, } impl GraphQLAuthentication { fn new(http: HttpRequest, gql: GraphQLRequest) -> Result<Self> { let config = http .app_data::<web::Data<config::Settings>>() .expect("Couldn't extract settings") .as_ref() .clone(); graphql_parser::parse_query::<&str>(gql.query.as_str()) .map_err(error::ErrorBadRequest) .map(|ast| extract_graphql_operation(ast, gql.operation_name.clone())) .and_then(|op| { let gql = http::GraphQLRequest::new(gql.query, gql.operation_name, gql.variables); if GRAPHQL_OPERATIONS_AUTH_EXCEPTION.contains(&op.as_str()) { log::debug!("GraphQL requet - exception for {}", op); return Ok(GraphQLAuthentication { gql, config, viewer: security::Viewer::default(), }); } extract_and_check_token(&http) .map(|viewer| { log::debug!("GraphQL request - user authorized for {}", op); GraphQLAuthentication { gql, config, viewer, } }) .map_err(|e| { log::debug!("GraphQL request - user unauthorized for {}", op); e }) }) } pub fn graphql(&self) -> &http::GraphQLRequest { &self.gql } pub fn config(&self) -> config::Settings { self.config.clone() } pub fn viewer(&self) -> security::Viewer { self.viewer.clone() } } impl FromRequest for GraphQLAuthentication { type Error = Error; type Future = LocalBoxFuture<'static, Result<Self>>; type Config = (); fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future { let req = req.clone(); web::Json::<GraphQLRequest>::from_request(&req, payload) .map(|r| r.and_then(|j| GraphQLAuthentication::new(req, j.into_inner()))) .boxed_local() } } const GRAPHQL_OPERATIONS_AUTH_EXCEPTION: [&str; 3] = ["signup", "login", "__schema"]; fn extract_graphql_operation<'a>( ast: query::Document<'a, &'a str>, operation_name: Option<String>, ) -> String { ast.definitions .into_iter() .filter_map(|d| match d { query::Definition::Operation(o) => Some(o), _ => None, }) .filter_map(|o| match o { query::OperationDefinition::Query(q) => { if operation_name.is_none() || q.name.as_deref() == operation_name.as_deref() { Some(q.selection_set.items) } else { None } } query::OperationDefinition::Mutation(m) => { if operation_name.is_none() || m.name.as_deref() == operation_name.as_deref() { Some(m.selection_set.items) } else { None } } _ => None, }) .flat_map(|v| { v.into_iter().filter_map(|s| match s { query::Selection::Field(f) => Some(f.name), _ => None, }) }) .collect::<String>() } fn extract_and_check_token(req: &HttpRequest) -> Result<security::Viewer> { let secret_key = req .app_data::<web::Data<config::Settings>>() .expect("Couldn't extract settings") .as_ref() .security() .secret_key(); let extracted = req .headers() .get("Authorization") .and_then(|v| v.to_str().ok()) .and_then(|s| { let re = regex::Regex::new(r"^Bearer (.+)$").unwrap(); re.captures(s).and_then(|c| c.get(1)).map(|m| m.as_str()) }); match extracted { None => Err(error::ErrorUnauthorized("Unauthorized")), Some(t) => security::verify_token(t, secret_key).map_err(error::ErrorInternalServerError), } } // Copy of juniper's #[derive(Deserialize, Debug, Clone)] 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>>, } #[cfg(test)] mod tests { use super::*; #[test] fn should_extract_the_graphql_operation() { let ast = graphql_parser::parse_query::<&str>("query MyQuery { viewer { token } }").unwrap(); assert_eq!("viewer", extract_graphql_operation(ast, None)); let ast = graphql_parser::parse_query::<&str>("mutation MyMutation { addPerson { person } }") .unwrap(); assert_eq!( "addPerson", extract_graphql_operation(ast, Some("MyMutation".to_string())) ); let ast = graphql_parser::parse_query::<&str>( r#" query MyQuery { viewer { token } } mutation MyMutation { addPerson { person } } "#, ) .unwrap(); assert_eq!( "addPerson", extract_graphql_operation(ast, Some("MyMutation".to_string())) ); } }
31.035556
98
0.529572
8abc8e1c31622be1c0e95df2b65ae326ac3b0e57
15,012
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0>. // This file may not be copied, modified, or distributed // except according to those terms. use std::fmt; use rand::prelude::*; use rand::distributions::{Normal, Uniform, Weibull, LogNormal, Distribution}; use serde::{Serialize}; use serde::de::{self, Deserialize, Deserializer, Visitor, SeqAccess, MapAccess}; pub trait DistributionWrapper { fn sample<R: Rng>(&self, rng: &mut R) -> f64; } #[derive(Debug, Clone, Serialize)] pub struct NormalWrapper { #[serde(skip_serializing)] normal: Normal, mean: f64, std_dev: f64 } impl NormalWrapper { pub fn new(mean: f64, std_dev: f64) -> Self { NormalWrapper { mean, std_dev, normal: Normal::new(mean, std_dev) } } } impl DistributionWrapper for NormalWrapper { fn sample<R: Rng>(&self, rng: &mut R) -> f64 { self.normal.sample(rng) } } #[derive(Debug, Clone, Serialize)] pub struct UniformWrapper { #[serde(skip_serializing)] uniform: Uniform<f64>, low: f64, high: f64 } impl UniformWrapper { pub fn new_inclusive(low: f64, high: f64) -> Self { UniformWrapper { low, high, uniform: Uniform::new_inclusive(low, high) } } pub fn new(low: f64, high: f64) -> Self { UniformWrapper { low, high, uniform: Uniform::new(low, high) } } } impl DistributionWrapper for UniformWrapper { fn sample<R: Rng>(&self, rng: &mut R) -> f64 { self.uniform.sample(rng) } } #[derive(Debug, Clone, Serialize)] pub struct WeibullWrapper { #[serde(skip_serializing)] weibull: Weibull, scale: f64, shape: f64 } impl WeibullWrapper { pub fn new(scale: f64, shape: f64) -> Self { WeibullWrapper { scale, shape, weibull: Weibull::new(scale, shape) } } } impl DistributionWrapper for WeibullWrapper { fn sample<R: Rng>(&self, rng: &mut R) -> f64 { self.weibull.sample(rng) } } #[derive(Debug, Clone, Serialize)] pub struct LogNormalWrapper { #[serde(skip_serializing)] log_normal: LogNormal, mean: f64, std_dev: f64 } impl LogNormalWrapper { pub fn new(mean: f64, std_dev: f64) -> Self { LogNormalWrapper { mean, std_dev, log_normal: LogNormal::new(mean, std_dev) } } } impl DistributionWrapper for LogNormalWrapper { fn sample<R: Rng>(&self, rng: &mut R) -> f64 { self.log_normal.sample(rng) } } impl Default for UniformWrapper { fn default() -> Self { UniformWrapper::new_inclusive(-0.1, 0.1) } } impl Default for NormalWrapper { fn default() -> Self { NormalWrapper::new(0.0, 0.1) } } impl Default for WeibullWrapper { fn default() -> Self { WeibullWrapper::new(1.0, 1.5) } } impl Default for LogNormalWrapper { fn default() -> Self { LogNormalWrapper::new(0.0, 0.5) } } impl<'de> Deserialize<'de> for NormalWrapper { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { #[derive(Deserialize)] #[allow(non_camel_case_types)] #[serde(field_identifier, rename_all = "lowercase")] enum Field { Mean, Std_Dev }; struct NormalWrapperVisitor; impl<'de> Visitor<'de> for NormalWrapperVisitor { type Value = NormalWrapper; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("struct NormalWrapper") } fn visit_seq<V>(self, mut seq: V) -> Result<NormalWrapper, V::Error> where V: SeqAccess<'de>, { let mean = seq.next_element()? .ok_or_else(|| de::Error::invalid_length(0, &self))?; let std_dev = seq.next_element()? .ok_or_else(|| de::Error::invalid_length(1, &self))?; Ok(NormalWrapper::new(mean, std_dev)) } fn visit_map<V>(self, mut map: V) -> Result<NormalWrapper, V::Error> where V: MapAccess<'de>, { let mut mean = None; let mut std_dev = None; while let Some(key) = map.next_key()? { match key { Field::Mean => { if mean.is_some() { return Err(de::Error::duplicate_field("mean")); } mean = Some(map.next_value()?); } Field::Std_Dev => { if std_dev.is_some() { return Err(de::Error::duplicate_field("std_dev")); } std_dev = Some(map.next_value()?); } } } let mean = mean.ok_or_else(|| de::Error::missing_field("mean"))?; let std_dev = std_dev.ok_or_else(|| de::Error::missing_field("std_dev"))?; Ok(NormalWrapper::new(mean, std_dev)) } } const FIELDS: &'static [&'static str] = &["mean", "std_dev"]; deserializer.deserialize_struct("NormalWrapper", FIELDS, NormalWrapperVisitor) } } impl<'de> Deserialize<'de> for UniformWrapper { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { #[derive(Deserialize)] #[serde(field_identifier, rename_all = "lowercase")] enum Field { Low, High }; struct UniformWrapperVisitor; impl<'de> Visitor<'de> for UniformWrapperVisitor { type Value = UniformWrapper; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("struct UniformWrapper") } fn visit_seq<V>(self, mut seq: V) -> Result<UniformWrapper, V::Error> where V: SeqAccess<'de>, { let low = seq.next_element()? .ok_or_else(|| de::Error::invalid_length(0, &self))?; let high = seq.next_element()? .ok_or_else(|| de::Error::invalid_length(1, &self))?; Ok(UniformWrapper::new_inclusive(low, high)) } fn visit_map<V>(self, mut map: V) -> Result<UniformWrapper, V::Error> where V: MapAccess<'de>, { let mut low = None; let mut high = None; while let Some(key) = map.next_key()? { match key { Field::Low => { if low.is_some() { return Err(de::Error::duplicate_field("low")); } low = Some(map.next_value()?); } Field::High => { if high.is_some() { return Err(de::Error::duplicate_field("high")); } high = Some(map.next_value()?); } } } let low = low.ok_or_else(|| de::Error::missing_field("low"))?; let high = high.ok_or_else(|| de::Error::missing_field("high"))?; Ok(UniformWrapper::new_inclusive(low, high)) } } const FIELDS: &'static [&'static str] = &["low", "high"]; deserializer.deserialize_struct("UniformWrapper", FIELDS, UniformWrapperVisitor) } } impl<'de> Deserialize<'de> for WeibullWrapper { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { #[derive(Deserialize)] #[serde(field_identifier, rename_all = "lowercase")] enum Field { Scale, Shape }; struct WeibullWrapperVisitor; impl<'de> Visitor<'de> for WeibullWrapperVisitor { type Value = WeibullWrapper; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("struct WeibullWrapper") } fn visit_seq<V>(self, mut seq: V) -> Result<WeibullWrapper, V::Error> where V: SeqAccess<'de>, { let scale = seq.next_element()? .ok_or_else(|| de::Error::invalid_length(0, &self))?; let shape = seq.next_element()? .ok_or_else(|| de::Error::invalid_length(1, &self))?; Ok(WeibullWrapper::new(scale, shape)) } fn visit_map<V>(self, mut map: V) -> Result<WeibullWrapper, V::Error> where V: MapAccess<'de>, { let mut scale = None; let mut shape = None; while let Some(key) = map.next_key()? { match key { Field::Scale => { if scale.is_some() { return Err(de::Error::duplicate_field("scale")); } scale = Some(map.next_value()?); } Field::Shape => { if shape.is_some() { return Err(de::Error::duplicate_field("shape")); } shape = Some(map.next_value()?); } } } let scale = scale.ok_or_else(|| de::Error::missing_field("scale"))?; let shape = shape.ok_or_else(|| de::Error::missing_field("shape"))?; Ok(WeibullWrapper::new(scale, shape)) } } const FIELDS: &'static [&'static str] = &["scale", "shape"]; deserializer.deserialize_struct("WeibullWrapper", FIELDS, WeibullWrapperVisitor) } } impl<'de> Deserialize<'de> for LogNormalWrapper { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { #[derive(Deserialize)] #[allow(non_camel_case_types)] #[serde(field_identifier, rename_all = "lowercase")] enum Field { Mean, Std_Dev }; struct LogNormalWrapperVisitor; impl<'de> Visitor<'de> for LogNormalWrapperVisitor { type Value = LogNormalWrapper; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("struct LogNormalWrapper") } fn visit_seq<V>(self, mut seq: V) -> Result<LogNormalWrapper, V::Error> where V: SeqAccess<'de>, { let mean = seq.next_element()? .ok_or_else(|| de::Error::invalid_length(0, &self))?; let std_dev = seq.next_element()? .ok_or_else(|| de::Error::invalid_length(1, &self))?; Ok(LogNormalWrapper::new(mean, std_dev)) } fn visit_map<V>(self, mut map: V) -> Result<LogNormalWrapper, V::Error> where V: MapAccess<'de>, { let mut mean = None; let mut std_dev = None; while let Some(key) = map.next_key()? { match key { Field::Mean => { if mean.is_some() { return Err(de::Error::duplicate_field("mean")); } mean = Some(map.next_value()?); } Field::Std_Dev => { if std_dev.is_some() { return Err(de::Error::duplicate_field("std_dev")); } std_dev = Some(map.next_value()?); } } } let mean = mean.ok_or_else(|| de::Error::missing_field("mean"))?; let std_dev = std_dev.ok_or_else(|| de::Error::missing_field("std_dev"))?; Ok(LogNormalWrapper::new(mean, std_dev)) } } const FIELDS: &'static [&'static str] = &["mean", "std_dev"]; deserializer.deserialize_struct("LogNormalWrapper", FIELDS, LogNormalWrapperVisitor) } } #[cfg(test)] mod test { use rand::prelude::*; use crate::simulation::wrappers::{NormalWrapper, UniformWrapper, WeibullWrapper, LogNormalWrapper, DistributionWrapper}; use serde_yaml; #[test] fn test_normal_wrapper() { let distribution: NormalWrapper = Default::default(); let mut rng = StdRng::seed_from_u64(0); let random_num = distribution.sample(&mut rng); let serialized = serde_yaml::to_string(&distribution).unwrap(); let deserialized: NormalWrapper = serde_yaml::from_str(&serialized).unwrap(); let mut rng2 = StdRng::seed_from_u64(0); let random_num2 = deserialized.sample(&mut rng2); assert_eq!(random_num, random_num2); } #[test] fn test_uniform_wrapper() { let distribution: UniformWrapper = Default::default(); let mut rng = StdRng::seed_from_u64(0); let random_num = distribution.sample(&mut rng); let serialized = serde_yaml::to_string(&distribution).unwrap(); let deserialized: UniformWrapper = serde_yaml::from_str(&serialized).unwrap(); let mut rng2 = StdRng::seed_from_u64(0); let random_num2 = deserialized.sample(&mut rng2); assert_eq!(random_num, random_num2); } #[test] fn test_weibull_wrapper() { let distribution: WeibullWrapper = Default::default(); let mut rng = StdRng::seed_from_u64(0); let random_num = distribution.sample(&mut rng); let serialized = serde_yaml::to_string(&distribution).unwrap(); let deserialized: WeibullWrapper = serde_yaml::from_str(&serialized).unwrap(); let mut rng2 = StdRng::seed_from_u64(0); let random_num2 = deserialized.sample(&mut rng2); assert_eq!(random_num, random_num2); } #[test] fn test_log_normal_wrapper() { let distribution: LogNormalWrapper = Default::default(); let mut rng = StdRng::seed_from_u64(0); let random_num = distribution.sample(&mut rng); let serialized = serde_yaml::to_string(&distribution).unwrap(); let deserialized: LogNormalWrapper = serde_yaml::from_str(&serialized).unwrap(); let mut rng2 = StdRng::seed_from_u64(0); let random_num2 = deserialized.sample(&mut rng2); assert_eq!(random_num, random_num2); } }
33.810811
124
0.520983
3a64bd8494d59f0661ce8a864cf22b1357f6bbe7
63,472
//! Main module defining the lexer and parser. use crate::engine::{ Precedence, KEYWORD_DEBUG, KEYWORD_EVAL, KEYWORD_FN_PTR, KEYWORD_FN_PTR_CALL, KEYWORD_FN_PTR_CURRY, KEYWORD_IS_DEF_VAR, KEYWORD_PRINT, KEYWORD_THIS, KEYWORD_TYPE_OF, }; use crate::stdlib::{ borrow::Cow, cell::Cell, char, fmt, format, iter::{FusedIterator, Peekable}, num::NonZeroUsize, ops::{Add, AddAssign}, str::{Chars, FromStr}, string::{String, ToString}, }; use crate::{Engine, LexError, Shared, StaticVec, INT}; #[cfg(not(feature = "no_float"))] use crate::ast::FloatWrapper; #[cfg(feature = "decimal")] use rust_decimal::Decimal; #[cfg(not(feature = "no_function"))] use crate::engine::KEYWORD_IS_DEF_FN; type LERR = LexError; /// Separator character for numbers. const NUM_SEP: char = '_'; /// A stream of tokens. pub type TokenStream<'a> = Peekable<TokenIterator<'a>>; /// A location (line number + character position) in the input script. /// /// # Limitations /// /// In order to keep footprint small, both line number and character position have 16-bit resolution, /// meaning they go up to a maximum of 65,535 lines and 65,535 characters per line. /// /// Advancing beyond the maximum line length or maximum number of lines is not an error but has no effect. #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Clone, Copy)] pub struct Position { /// Line number - 0 = none line: u16, /// Character position - 0 = BOL pos: u16, } impl Position { /// A [`Position`] representing no position. pub const NONE: Self = Self { line: 0, pos: 0 }; /// A [`Position`] representing the first position. pub const START: Self = Self { line: 1, pos: 0 }; /// Create a new [`Position`]. /// /// `line` must not be zero. /// If [`Position`] is zero, then it is at the beginning of a line. /// /// # Panics /// /// Panics if `line` is zero. #[inline(always)] pub fn new(line: u16, position: u16) -> Self { assert!(line != 0, "line cannot be zero"); Self { line, pos: position, } } /// Get the line number (1-based), or [`None`] if there is no position. #[inline(always)] pub fn line(self) -> Option<usize> { if self.is_none() { None } else { Some(self.line as usize) } } /// Get the character position (1-based), or [`None`] if at beginning of a line. #[inline(always)] pub fn position(self) -> Option<usize> { if self.is_none() || self.pos == 0 { None } else { Some(self.pos as usize) } } /// Advance by one character position. #[inline(always)] pub(crate) fn advance(&mut self) { assert!(!self.is_none(), "cannot advance Position::none"); // Advance up to maximum position if self.pos < u16::MAX { self.pos += 1; } } /// Go backwards by one character position. /// /// # Panics /// /// Panics if already at beginning of a line - cannot rewind to a previous line. #[inline(always)] pub(crate) fn rewind(&mut self) { assert!(!self.is_none(), "cannot rewind Position::none"); assert!(self.pos > 0, "cannot rewind at position 0"); self.pos -= 1; } /// Advance to the next line. #[inline(always)] pub(crate) fn new_line(&mut self) { assert!(!self.is_none(), "cannot advance Position::none"); // Advance up to maximum position if self.line < u16::MAX { self.line += 1; self.pos = 0; } } /// Is this [`Position`] at the beginning of a line? #[inline(always)] pub fn is_beginning_of_line(self) -> bool { self.pos == 0 && !self.is_none() } /// Is there no [`Position`]? #[inline(always)] pub fn is_none(self) -> bool { self == Self::NONE } } impl Default for Position { #[inline(always)] fn default() -> Self { Self::START } } impl fmt::Display for Position { #[inline(always)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.is_none() { write!(f, "none") } else { write!(f, "line {}, position {}", self.line, self.pos) } } } impl fmt::Debug for Position { #[inline(always)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}:{}", self.line, self.pos) } } impl Add for Position { type Output = Self; fn add(self, rhs: Self) -> Self::Output { if rhs.is_none() { self } else { Self { line: self.line + rhs.line - 1, pos: if rhs.is_beginning_of_line() { self.pos } else { self.pos + rhs.pos - 1 }, } } } } impl AddAssign for Position { fn add_assign(&mut self, rhs: Self) { *self = *self + rhs; } } /// _(INTERNALS)_ A Rhai language token. /// Exported under the `internals` feature only. /// /// # Volatile Data Structure /// /// This type is volatile and may change. #[derive(Debug, PartialEq, Clone, Hash)] pub enum Token { /// An `INT` constant. IntegerConstant(INT), /// A `FLOAT` constant. /// /// Reserved under the `no_float` feature. #[cfg(not(feature = "no_float"))] FloatConstant(FloatWrapper), /// A [`Decimal`] constant. /// /// Requires the `decimal` feature. #[cfg(feature = "decimal")] DecimalConstant(Decimal), /// An identifier. Identifier(String), /// A character constant. CharConstant(char), /// A string constant. StringConstant(String), /// An interpolated string. InterpolatedString(String), /// `{` LeftBrace, /// `}` RightBrace, /// `(` LeftParen, /// `)` RightParen, /// `[` LeftBracket, /// `]` RightBracket, /// `+` Plus, /// `+` (unary) UnaryPlus, /// `-` Minus, /// `-` (unary) UnaryMinus, /// `*` Multiply, /// `/` Divide, /// `%` Modulo, /// `**` PowerOf, /// `<<` LeftShift, /// `>>` RightShift, /// `;` SemiColon, /// `:` Colon, /// `::` DoubleColon, /// `=>` DoubleArrow, /// `_` Underscore, /// `,` Comma, /// `.` Period, /// `#{` MapStart, /// `=` Equals, /// `true` True, /// `false` False, /// `let` Let, /// `const` Const, /// `if` If, /// `else` Else, /// `switch` Switch, /// `do` Do, /// `while` While, /// `until` Until, /// `loop` Loop, /// `for` For, /// `in` In, /// `<` LessThan, /// `>` GreaterThan, /// `<=` LessThanEqualsTo, /// `>=` GreaterThanEqualsTo, /// `==` EqualsTo, /// `!=` NotEqualsTo, /// `!` Bang, /// `|` Pipe, /// `||` Or, /// `^` XOr, /// `&` Ampersand, /// `&&` And, /// `fn` /// /// Reserved under the `no_function` feature. #[cfg(not(feature = "no_function"))] Fn, /// `continue` Continue, /// `break` Break, /// `return` Return, /// `throw` Throw, /// `try` Try, /// `catch` Catch, /// `+=` PlusAssign, /// `-=` MinusAssign, /// `*=` MultiplyAssign, /// `/=` DivideAssign, /// `<<=` LeftShiftAssign, /// `>>=` RightShiftAssign, /// `&=` AndAssign, /// `|=` OrAssign, /// `^=` XOrAssign, /// `%=` ModuloAssign, /// `**=` PowerOfAssign, /// `private` /// /// Reserved under the `no_function` feature. #[cfg(not(feature = "no_function"))] Private, /// `import` /// /// Reserved under the `no_module` feature. #[cfg(not(feature = "no_module"))] Import, /// `export` /// /// Reserved under the `no_module` feature. #[cfg(not(feature = "no_module"))] Export, /// `as` /// /// Reserved under the `no_module` feature. #[cfg(not(feature = "no_module"))] As, /// A lexer error. LexError(LexError), /// A comment block. Comment(String), /// A reserved symbol. Reserved(String), /// A custom keyword. Custom(String), /// End of the input stream. EOF, } impl Token { /// Get the syntax of the token if it is a keyword. /// /// # Panics /// /// Panics if the token is not a keyword. pub fn keyword_syntax(&self) -> &'static str { use Token::*; match self { LeftBrace => "{", RightBrace => "}", LeftParen => "(", RightParen => ")", LeftBracket => "[", RightBracket => "]", Plus => "+", UnaryPlus => "+", Minus => "-", UnaryMinus => "-", Multiply => "*", Divide => "/", SemiColon => ";", Colon => ":", DoubleColon => "::", DoubleArrow => "=>", Underscore => "_", Comma => ",", Period => ".", MapStart => "#{", Equals => "=", True => "true", False => "false", Let => "let", Const => "const", If => "if", Else => "else", Switch => "switch", Do => "do", While => "while", Until => "until", Loop => "loop", For => "for", In => "in", LessThan => "<", GreaterThan => ">", Bang => "!", LessThanEqualsTo => "<=", GreaterThanEqualsTo => ">=", EqualsTo => "==", NotEqualsTo => "!=", Pipe => "|", Or => "||", Ampersand => "&", And => "&&", Continue => "continue", Break => "break", Return => "return", Throw => "throw", Try => "try", Catch => "catch", PlusAssign => "+=", MinusAssign => "-=", MultiplyAssign => "*=", DivideAssign => "/=", LeftShiftAssign => "<<=", RightShiftAssign => ">>=", AndAssign => "&=", OrAssign => "|=", XOrAssign => "^=", LeftShift => "<<", RightShift => ">>", XOr => "^", Modulo => "%", ModuloAssign => "%=", PowerOf => "**", PowerOfAssign => "**=", #[cfg(not(feature = "no_function"))] Fn => "fn", #[cfg(not(feature = "no_function"))] Private => "private", #[cfg(not(feature = "no_module"))] Import => "import", #[cfg(not(feature = "no_module"))] Export => "export", #[cfg(not(feature = "no_module"))] As => "as", t => unreachable!("{:?} is not a keyword", t), } } /// Get the syntax of the token. pub fn syntax(&self) -> Cow<'static, str> { use Token::*; match self { IntegerConstant(i) => i.to_string().into(), #[cfg(not(feature = "no_float"))] FloatConstant(f) => f.to_string().into(), #[cfg(feature = "decimal")] DecimalConstant(d) => d.to_string().into(), StringConstant(_) => "string".into(), InterpolatedString(_) => "string".into(), CharConstant(c) => c.to_string().into(), Identifier(s) => s.clone().into(), Reserved(s) => s.clone().into(), Custom(s) => s.clone().into(), LexError(err) => err.to_string().into(), Comment(s) => s.clone().into(), EOF => "{EOF}".into(), token => token.keyword_syntax().into(), } } /// Reverse lookup a token from a piece of syntax. pub fn lookup_from_syntax(syntax: &str) -> Option<Self> { use Token::*; Some(match syntax { "{" => LeftBrace, "}" => RightBrace, "(" => LeftParen, ")" => RightParen, "[" => LeftBracket, "]" => RightBracket, "+" => Plus, "-" => Minus, "*" => Multiply, "/" => Divide, ";" => SemiColon, ":" => Colon, "::" => DoubleColon, "=>" => DoubleArrow, "_" => Underscore, "," => Comma, "." => Period, "#{" => MapStart, "=" => Equals, "true" => True, "false" => False, "let" => Let, "const" => Const, "if" => If, "else" => Else, "switch" => Switch, "do" => Do, "while" => While, "until" => Until, "loop" => Loop, "for" => For, "in" => In, "<" => LessThan, ">" => GreaterThan, "!" => Bang, "<=" => LessThanEqualsTo, ">=" => GreaterThanEqualsTo, "==" => EqualsTo, "!=" => NotEqualsTo, "|" => Pipe, "||" => Or, "&" => Ampersand, "&&" => And, "continue" => Continue, "break" => Break, "return" => Return, "throw" => Throw, "try" => Try, "catch" => Catch, "+=" => PlusAssign, "-=" => MinusAssign, "*=" => MultiplyAssign, "/=" => DivideAssign, "<<=" => LeftShiftAssign, ">>=" => RightShiftAssign, "&=" => AndAssign, "|=" => OrAssign, "^=" => XOrAssign, "<<" => LeftShift, ">>" => RightShift, "^" => XOr, "%" => Modulo, "%=" => ModuloAssign, "**" => PowerOf, "**=" => PowerOfAssign, #[cfg(not(feature = "no_function"))] "fn" => Fn, #[cfg(not(feature = "no_function"))] "private" => Private, #[cfg(not(feature = "no_module"))] "import" => Import, #[cfg(not(feature = "no_module"))] "export" => Export, #[cfg(not(feature = "no_module"))] "as" => As, #[cfg(feature = "no_function")] "fn" | "private" => Reserved(syntax.into()), #[cfg(feature = "no_module")] "import" | "export" | "as" => Reserved(syntax.into()), "===" | "!==" | "->" | "<-" | ":=" | "~" | "::<" | "(*" | "*)" | "#" | "#!" | "public" | "protected" | "super" | "new" | "use" | "module" | "package" | "var" | "static" | "begin" | "end" | "shared" | "with" | "each" | "then" | "goto" | "unless" | "exit" | "match" | "case" | "default" | "void" | "null" | "nil" | "spawn" | "thread" | "go" | "sync" | "async" | "await" | "yield" => { Reserved(syntax.into()) } KEYWORD_PRINT | KEYWORD_DEBUG | KEYWORD_TYPE_OF | KEYWORD_EVAL | KEYWORD_FN_PTR | KEYWORD_FN_PTR_CALL | KEYWORD_FN_PTR_CURRY | KEYWORD_THIS | KEYWORD_IS_DEF_VAR => { Reserved(syntax.into()) } #[cfg(not(feature = "no_function"))] KEYWORD_IS_DEF_FN => Reserved(syntax.into()), _ => return None, }) } // Is this token [`EOF`][Token::EOF]? #[inline(always)] pub fn is_eof(&self) -> bool { use Token::*; match self { EOF => true, _ => false, } } // If another operator is after these, it's probably an unary operator // (not sure about `fn` name). pub fn is_next_unary(&self) -> bool { use Token::*; match self { LexError(_) | LeftBrace | // {+expr} - is unary // RightBrace | {expr} - expr not unary & is closing LeftParen | // (-expr) - is unary // RightParen | (expr) - expr not unary & is closing LeftBracket | // [-expr] - is unary // RightBracket | [expr] - expr not unary & is closing Plus | UnaryPlus | Minus | UnaryMinus | Multiply | Divide | Comma | Period | Equals | LessThan | GreaterThan | Bang | LessThanEqualsTo | GreaterThanEqualsTo | EqualsTo | NotEqualsTo | Pipe | Or | Ampersand | And | If | Do | While | Until | PlusAssign | MinusAssign | MultiplyAssign | DivideAssign | LeftShiftAssign | RightShiftAssign | PowerOf | PowerOfAssign | AndAssign | OrAssign | XOrAssign | LeftShift | RightShift | XOr | Modulo | ModuloAssign | Return | Throw | In => true, _ => false, } } /// Get the precedence number of the token. pub fn precedence(&self) -> Option<Precedence> { use Token::*; Precedence::new(match self { // Assignments are not considered expressions - set to zero Equals | PlusAssign | MinusAssign | MultiplyAssign | DivideAssign | PowerOfAssign | LeftShiftAssign | RightShiftAssign | AndAssign | OrAssign | XOrAssign | ModuloAssign => 0, Or | XOr | Pipe => 30, And | Ampersand => 60, EqualsTo | NotEqualsTo => 90, In => 110, LessThan | LessThanEqualsTo | GreaterThan | GreaterThanEqualsTo => 130, Plus | Minus => 150, Divide | Multiply | Modulo => 180, PowerOf => 190, LeftShift | RightShift => 210, Period => 240, _ => 0, }) } /// Does an expression bind to the right (instead of left)? pub fn is_bind_right(&self) -> bool { use Token::*; match self { // Assignments bind to the right Equals | PlusAssign | MinusAssign | MultiplyAssign | DivideAssign | PowerOfAssign | LeftShiftAssign | RightShiftAssign | AndAssign | OrAssign | XOrAssign | ModuloAssign => true, // Property access binds to the right Period => true, // Exponentiation binds to the right PowerOf => true, _ => false, } } /// Is this token a standard symbol used in the language? pub fn is_symbol(&self) -> bool { use Token::*; match self { LeftBrace | RightBrace | LeftParen | RightParen | LeftBracket | RightBracket | Plus | UnaryPlus | Minus | UnaryMinus | Multiply | Divide | Modulo | PowerOf | LeftShift | RightShift | SemiColon | Colon | DoubleColon | Comma | Period | MapStart | Equals | LessThan | GreaterThan | LessThanEqualsTo | GreaterThanEqualsTo | EqualsTo | NotEqualsTo | Bang | Pipe | Or | XOr | Ampersand | And | PlusAssign | MinusAssign | MultiplyAssign | DivideAssign | LeftShiftAssign | RightShiftAssign | AndAssign | OrAssign | XOrAssign | ModuloAssign | PowerOfAssign => true, _ => false, } } /// Is this token an active standard keyword? pub fn is_keyword(&self) -> bool { use Token::*; match self { #[cfg(not(feature = "no_function"))] Fn | Private => true, #[cfg(not(feature = "no_module"))] Import | Export | As => true, True | False | Let | Const | If | Else | Do | While | Until | Loop | For | In | Continue | Break | Return | Throw | Try | Catch => true, _ => false, } } /// Is this token a reserved symbol? #[inline(always)] pub fn is_reserved(&self) -> bool { match self { Self::Reserved(_) => true, _ => false, } } /// Convert a token into a function name, if possible. #[cfg(not(feature = "no_function"))] pub(crate) fn into_function_name_for_override(self) -> Result<String, Self> { match self { Self::Custom(s) | Self::Identifier(s) if is_valid_identifier(s.chars()) => Ok(s), _ => Err(self), } } /// Is this token a custom keyword? #[inline(always)] pub fn is_custom(&self) -> bool { match self { Self::Custom(_) => true, _ => false, } } } impl From<Token> for String { #[inline(always)] fn from(token: Token) -> Self { token.syntax().into() } } /// _(INTERNALS)_ State of the tokenizer. /// Exported under the `internals` feature only. /// /// # Volatile Data Structure /// /// This type is volatile and may change. #[derive(Debug, Clone, Eq, PartialEq, Default)] pub struct TokenizeState { /// Maximum length of a string (0 = unlimited). pub max_string_size: Option<NonZeroUsize>, /// Can the next token be a unary operator? pub non_unary: bool, /// Is the tokenizer currently inside a block comment? pub comment_level: usize, /// Return [`None`] at the end of the stream instead of [`Some(Token::EOF)`][Token::EOF]? pub end_with_none: bool, /// Include comments? pub include_comments: bool, /// Disable doc-comments? pub disable_doc_comments: bool, } /// _(INTERNALS)_ Trait that encapsulates a peekable character input stream. /// Exported under the `internals` feature only. /// /// # Volatile Data Structure /// /// This trait is volatile and may change. pub trait InputStream { /// Un-get a character back into the `InputStream`. /// The next [`get_next`][InputStream::get_next] or [`peek_next`][InputStream::peek_next] /// will return this character instead. fn unget(&mut self, ch: char); /// Get the next character from the `InputStream`. fn get_next(&mut self) -> Option<char>; /// Peek the next character in the `InputStream`. fn peek_next(&mut self) -> Option<char>; } /// _(INTERNALS)_ Parse a string literal ended by `termination_char`. /// Exported under the `internals` feature only. /// /// # Volatile API /// /// This function is volatile and may change. pub fn parse_string_literal( stream: &mut impl InputStream, state: &mut TokenizeState, pos: &mut Position, termination_char: char, continuation: bool, verbatim: bool, allow_interpolation: bool, ) -> Result<(String, bool), (LexError, Position)> { let mut result: smallvec::SmallVec<[char; 16]> = Default::default(); let mut escape: smallvec::SmallVec<[char; 12]> = Default::default(); let start = *pos; let mut skip_whitespace_until = 0; let mut interpolated = false; loop { let next_char = stream.get_next().ok_or((LERR::UnterminatedString, start))?; pos.advance(); // String interpolation? if allow_interpolation && next_char == '$' && escape.is_empty() && stream.peek_next().map(|ch| ch == '{').unwrap_or(false) { interpolated = true; break; } if let Some(max) = state.max_string_size { if result.len() > max.get() { return Err((LexError::StringTooLong(max.get()), *pos)); } } match next_char { // \r - ignore if followed by \n '\r' if stream.peek_next().map(|ch| ch == '\n').unwrap_or(false) => {} // \... '\\' if escape.is_empty() && !verbatim => { escape.push('\\'); } // \\ '\\' if !escape.is_empty() => { escape.clear(); result.push('\\'); } // \t 't' if !escape.is_empty() => { escape.clear(); result.push('\t'); } // \n 'n' if !escape.is_empty() => { escape.clear(); result.push('\n'); } // \r 'r' if !escape.is_empty() => { escape.clear(); result.push('\r'); } // \x??, \u????, \U???????? ch @ 'x' | ch @ 'u' | ch @ 'U' if !escape.is_empty() => { let mut seq = escape.clone(); escape.clear(); seq.push(ch); let mut out_val: u32 = 0; let len = match ch { 'x' => 2, 'u' => 4, 'U' => 8, _ => unreachable!(), }; for _ in 0..len { let c = stream.get_next().ok_or_else(|| { ( LERR::MalformedEscapeSequence(seq.iter().cloned().collect()), *pos, ) })?; seq.push(c); pos.advance(); out_val *= 16; out_val += c.to_digit(16).ok_or_else(|| { ( LERR::MalformedEscapeSequence(seq.iter().cloned().collect()), *pos, ) })?; } result.push(char::from_u32(out_val).ok_or_else(|| { ( LERR::MalformedEscapeSequence(seq.into_iter().collect()), *pos, ) })?); } // \{termination_char} - escaped _ if termination_char == next_char && !escape.is_empty() => { escape.clear(); result.push(next_char) } // Close wrapper _ if termination_char == next_char && escape.is_empty() => break, // Line continuation '\n' if continuation && !escape.is_empty() => { escape.clear(); pos.new_line(); skip_whitespace_until = start.position().unwrap() + 1; } // New-line cannot be escaped // Cannot have new-lines inside non-multi-line string literals '\n' if !escape.is_empty() || !verbatim => { pos.rewind(); return Err((LERR::UnterminatedString, start)); } '\n' => { pos.new_line(); result.push(next_char); } // Unknown escape sequence _ if !escape.is_empty() => { escape.push(next_char); return Err(( LERR::MalformedEscapeSequence(escape.into_iter().collect()), *pos, )); } // Whitespace to skip _ if next_char.is_whitespace() && pos.position().unwrap() < skip_whitespace_until => {} // All other characters _ => { escape.clear(); result.push(next_char); skip_whitespace_until = 0; } } } let s = result.iter().collect::<String>(); if let Some(max) = state.max_string_size { if s.len() > max.get() { return Err((LexError::StringTooLong(max.get()), *pos)); } } Ok((s, interpolated)) } /// Consume the next character. #[inline(always)] fn eat_next(stream: &mut impl InputStream, pos: &mut Position) -> Option<char> { pos.advance(); stream.get_next() } /// Scan for a block comment until the end. fn scan_block_comment( stream: &mut impl InputStream, mut level: usize, pos: &mut Position, comment: &mut Option<String>, ) -> usize { while let Some(c) = stream.get_next() { pos.advance(); if let Some(ref mut comment) = comment { comment.push(c); } match c { '/' => { if let Some(c2) = stream.peek_next() { if c2 == '*' { eat_next(stream, pos); if let Some(ref mut comment) = comment { comment.push(c2); } level += 1; } } } '*' => { if let Some(c2) = stream.peek_next() { if c2 == '/' { eat_next(stream, pos); if let Some(ref mut comment) = comment { comment.push(c2); } level -= 1; } } } '\n' => pos.new_line(), _ => (), } if level == 0 { break; } } level } /// _(INTERNALS)_ Get the next token from the `stream`. /// Exported under the `internals` feature only. /// /// # Volatile API /// /// This function is volatile and may change. #[inline(always)] pub fn get_next_token( stream: &mut impl InputStream, state: &mut TokenizeState, pos: &mut Position, ) -> Option<(Token, Position)> { let result = get_next_token_inner(stream, state, pos); // Save the last token's state if let Some((ref token, _)) = result { state.non_unary = !token.is_next_unary(); } result } /// Test if the given character is a hex character. #[inline(always)] fn is_hex_digit(c: char) -> bool { match c { 'a'..='f' => true, 'A'..='F' => true, '0'..='9' => true, _ => false, } } /// Test if the given character is a numeric digit. #[inline(always)] fn is_numeric_digit(c: char) -> bool { match c { '0'..='9' => true, _ => false, } } /// Test if the comment block is a doc-comment. #[inline(always)] pub fn is_doc_comment(comment: &str) -> bool { (comment.starts_with("///") && !comment.starts_with("////")) || (comment.starts_with("/**") && !comment.starts_with("/***")) } /// Get the next token. fn get_next_token_inner( stream: &mut impl InputStream, state: &mut TokenizeState, pos: &mut Position, ) -> Option<(Token, Position)> { // Still inside a comment? if state.comment_level > 0 { let start_pos = *pos; let mut comment = if state.include_comments { Some(String::new()) } else { None }; state.comment_level = scan_block_comment(stream, state.comment_level, pos, &mut comment); if state.include_comments || (!state.disable_doc_comments && is_doc_comment(comment.as_ref().unwrap())) { return Some((Token::Comment(comment.unwrap()), start_pos)); } } let mut negated = false; while let Some(c) = stream.get_next() { pos.advance(); let start_pos = *pos; match (c, stream.peek_next().unwrap_or('\0')) { // \n ('\n', _) => pos.new_line(), // digit ... ('0'..='9', _) => { let mut result: smallvec::SmallVec<[char; 16]> = Default::default(); let mut radix_base: Option<u32> = None; let mut valid: fn(char) -> bool = is_numeric_digit; result.push(c); while let Some(next_char) = stream.peek_next() { match next_char { ch if valid(ch) || ch == NUM_SEP => { result.push(next_char); eat_next(stream, pos); } #[cfg(any(not(feature = "no_float"), feature = "decimal"))] '.' => { stream.get_next().unwrap(); // Check if followed by digits or something that cannot start a property name match stream.peek_next().unwrap_or('\0') { // digits after period - accept the period '0'..='9' => { result.push(next_char); pos.advance(); } // _ - cannot follow a decimal point '_' => { stream.unget(next_char); break; } // .. - reserved symbol, not a floating-point number '.' => { stream.unget(next_char); break; } // symbol after period - probably a float ch @ _ if !is_id_first_alphabetic(ch) => { result.push(next_char); pos.advance(); result.push('0'); } // Not a floating-point number _ => { stream.unget(next_char); break; } } } #[cfg(not(feature = "no_float"))] 'e' => { stream.get_next().unwrap(); // Check if followed by digits or +/- match stream.peek_next().unwrap_or('\0') { // digits after e - accept the e '0'..='9' => { result.push(next_char); pos.advance(); } // +/- after e - accept the e and the sign '+' | '-' => { result.push(next_char); pos.advance(); result.push(stream.get_next().unwrap()); pos.advance(); } // Not a floating-point number _ => { stream.unget(next_char); break; } } } // 0x????, 0o????, 0b???? at beginning ch @ 'x' | ch @ 'o' | ch @ 'b' | ch @ 'X' | ch @ 'O' | ch @ 'B' if c == '0' && result.len() <= 1 => { result.push(next_char); eat_next(stream, pos); valid = match ch { 'x' | 'X' => is_hex_digit, 'o' | 'O' => is_numeric_digit, 'b' | 'B' => is_numeric_digit, _ => unreachable!(), }; radix_base = Some(match ch { 'x' | 'X' => 16, 'o' | 'O' => 8, 'b' | 'B' => 2, _ => unreachable!(), }); } _ => break, } } if negated { result.insert(0, '-'); } // Parse number if let Some(radix) = radix_base { let out: String = result.iter().skip(2).filter(|&&c| c != NUM_SEP).collect(); return Some(( INT::from_str_radix(&out, radix) .map(Token::IntegerConstant) .unwrap_or_else(|_| { Token::LexError(LERR::MalformedNumber(result.into_iter().collect())) }), start_pos, )); } else { let out: String = result.iter().filter(|&&c| c != NUM_SEP).collect(); let num = INT::from_str(&out).map(Token::IntegerConstant); // If integer parsing is unnecessary, try float instead #[cfg(not(feature = "no_float"))] let num = num.or_else(|_| FloatWrapper::from_str(&out).map(Token::FloatConstant)); // Then try decimal #[cfg(feature = "decimal")] let num = num.or_else(|_| Decimal::from_str(&out).map(Token::DecimalConstant)); // Then try decimal in scientific notation #[cfg(feature = "decimal")] let num = num.or_else(|_| Decimal::from_scientific(&out).map(Token::DecimalConstant)); return Some(( num.unwrap_or_else(|_| { Token::LexError(LERR::MalformedNumber(result.into_iter().collect())) }), start_pos, )); } } // letter or underscore ... #[cfg(not(feature = "unicode-xid-ident"))] ('a'..='z', _) | ('_', _) | ('A'..='Z', _) => { return get_identifier(stream, pos, start_pos, c); } #[cfg(feature = "unicode-xid-ident")] (ch, _) if unicode_xid::UnicodeXID::is_xid_start(ch) || ch == '_' => { return get_identifier(stream, pos, start_pos, c); } // " - string literal ('"', _) => { return parse_string_literal(stream, state, pos, c, true, false, false) .map_or_else( |err| Some((Token::LexError(err.0), err.1)), |(result, _)| Some((Token::StringConstant(result), start_pos)), ); } // ` - string literal ('`', _) => { // Start from the next line if ` at the end of line match stream.peek_next() { // `\r - start from next line Some('\r') => { eat_next(stream, pos); // `\r\n if stream.peek_next().map(|ch| ch == '\n').unwrap_or(false) { eat_next(stream, pos); } } // `\n - start from next line Some('\n') => { eat_next(stream, pos); } _ => (), } return parse_string_literal(stream, state, pos, c, false, true, true).map_or_else( |err| Some((Token::LexError(err.0), err.1)), |(result, interpolated)| { if interpolated { Some((Token::InterpolatedString(result), start_pos)) } else { Some((Token::StringConstant(result), start_pos)) } }, ); } // ' - character literal ('\'', '\'') => { return Some(( Token::LexError(LERR::MalformedChar("".to_string())), start_pos, )) } ('\'', _) => { return Some( parse_string_literal(stream, state, pos, c, false, false, false).map_or_else( |err| (Token::LexError(err.0), err.1), |(result, _)| { let mut chars = result.chars(); let first = chars.next().unwrap(); if chars.next().is_some() { (Token::LexError(LERR::MalformedChar(result)), start_pos) } else { (Token::CharConstant(first), start_pos) } }, ), ) } // Braces ('{', _) => return Some((Token::LeftBrace, start_pos)), ('}', _) => return Some((Token::RightBrace, start_pos)), // Parentheses ('(', '*') => { eat_next(stream, pos); return Some((Token::Reserved("(*".into()), start_pos)); } ('(', _) => return Some((Token::LeftParen, start_pos)), (')', _) => return Some((Token::RightParen, start_pos)), // Indexing ('[', _) => return Some((Token::LeftBracket, start_pos)), (']', _) => return Some((Token::RightBracket, start_pos)), // Map literal #[cfg(not(feature = "no_object"))] ('#', '{') => { eat_next(stream, pos); return Some((Token::MapStart, start_pos)); } // Shebang ('#', '!') => return Some((Token::Reserved("#!".into()), start_pos)), ('#', _) => return Some((Token::Reserved("#".into()), start_pos)), // Operators ('+', '=') => { eat_next(stream, pos); return Some((Token::PlusAssign, start_pos)); } ('+', '+') => { eat_next(stream, pos); return Some((Token::Reserved("++".into()), start_pos)); } ('+', _) if !state.non_unary => return Some((Token::UnaryPlus, start_pos)), ('+', _) => return Some((Token::Plus, start_pos)), ('-', '0'..='9') if !state.non_unary => negated = true, ('-', '0'..='9') => return Some((Token::Minus, start_pos)), ('-', '=') => { eat_next(stream, pos); return Some((Token::MinusAssign, start_pos)); } ('-', '>') => { eat_next(stream, pos); return Some((Token::Reserved("->".into()), start_pos)); } ('-', '-') => { eat_next(stream, pos); return Some((Token::Reserved("--".into()), start_pos)); } ('-', _) if !state.non_unary => return Some((Token::UnaryMinus, start_pos)), ('-', _) => return Some((Token::Minus, start_pos)), ('*', ')') => { eat_next(stream, pos); return Some((Token::Reserved("*)".into()), start_pos)); } ('*', '=') => { eat_next(stream, pos); return Some((Token::MultiplyAssign, start_pos)); } ('*', '*') => { eat_next(stream, pos); return Some(( if stream.peek_next() == Some('=') { eat_next(stream, pos); Token::PowerOfAssign } else { Token::PowerOf }, start_pos, )); } ('*', _) => return Some((Token::Multiply, start_pos)), // Comments ('/', '/') => { eat_next(stream, pos); let mut comment = match stream.peek_next() { Some('/') if !state.disable_doc_comments => { eat_next(stream, pos); // Long streams of `///...` are not doc-comments match stream.peek_next() { Some('/') => None, _ => Some("///".to_string()), } } _ if state.include_comments => Some("//".to_string()), _ => None, }; while let Some(c) = stream.get_next() { if c == '\n' { pos.new_line(); break; } if let Some(ref mut comment) = comment { comment.push(c); } pos.advance(); } if let Some(comment) = comment { return Some((Token::Comment(comment), start_pos)); } } ('/', '*') => { state.comment_level = 1; eat_next(stream, pos); let mut comment = match stream.peek_next() { Some('*') if !state.disable_doc_comments => { eat_next(stream, pos); // Long streams of `/****...` are not doc-comments match stream.peek_next() { Some('*') => None, _ => Some("/**".to_string()), } } _ if state.include_comments => Some("/*".to_string()), _ => None, }; state.comment_level = scan_block_comment(stream, state.comment_level, pos, &mut comment); if let Some(comment) = comment { return Some((Token::Comment(comment), start_pos)); } } ('/', '=') => { eat_next(stream, pos); return Some((Token::DivideAssign, start_pos)); } ('/', _) => return Some((Token::Divide, start_pos)), (';', _) => return Some((Token::SemiColon, start_pos)), (',', _) => return Some((Token::Comma, start_pos)), ('.', '.') => { eat_next(stream, pos); if stream.peek_next() == Some('.') { eat_next(stream, pos); return Some((Token::Reserved("...".into()), start_pos)); } else { return Some((Token::Reserved("..".into()), start_pos)); } } ('.', _) => return Some((Token::Period, start_pos)), ('=', '=') => { eat_next(stream, pos); if stream.peek_next() == Some('=') { eat_next(stream, pos); return Some((Token::Reserved("===".into()), start_pos)); } return Some((Token::EqualsTo, start_pos)); } ('=', '>') => { eat_next(stream, pos); return Some((Token::DoubleArrow, start_pos)); } ('=', _) => return Some((Token::Equals, start_pos)), (':', ':') => { eat_next(stream, pos); if stream.peek_next() == Some('<') { eat_next(stream, pos); return Some((Token::Reserved("::<".into()), start_pos)); } return Some((Token::DoubleColon, start_pos)); } (':', '=') => { eat_next(stream, pos); return Some((Token::Reserved(":=".into()), start_pos)); } (':', _) => return Some((Token::Colon, start_pos)), ('<', '=') => { eat_next(stream, pos); return Some((Token::LessThanEqualsTo, start_pos)); } ('<', '-') => { eat_next(stream, pos); return Some((Token::Reserved("<-".into()), start_pos)); } ('<', '<') => { eat_next(stream, pos); return Some(( if stream.peek_next() == Some('=') { eat_next(stream, pos); Token::LeftShiftAssign } else { Token::LeftShift }, start_pos, )); } ('<', _) => return Some((Token::LessThan, start_pos)), ('>', '=') => { eat_next(stream, pos); return Some((Token::GreaterThanEqualsTo, start_pos)); } ('>', '>') => { eat_next(stream, pos); return Some(( if stream.peek_next() == Some('=') { eat_next(stream, pos); Token::RightShiftAssign } else { Token::RightShift }, start_pos, )); } ('>', _) => return Some((Token::GreaterThan, start_pos)), ('!', '=') => { eat_next(stream, pos); if stream.peek_next() == Some('=') { eat_next(stream, pos); return Some((Token::Reserved("!==".into()), start_pos)); } return Some((Token::NotEqualsTo, start_pos)); } ('!', _) => return Some((Token::Bang, start_pos)), ('|', '|') => { eat_next(stream, pos); return Some((Token::Or, start_pos)); } ('|', '=') => { eat_next(stream, pos); return Some((Token::OrAssign, start_pos)); } ('|', _) => return Some((Token::Pipe, start_pos)), ('&', '&') => { eat_next(stream, pos); return Some((Token::And, start_pos)); } ('&', '=') => { eat_next(stream, pos); return Some((Token::AndAssign, start_pos)); } ('&', _) => return Some((Token::Ampersand, start_pos)), ('^', '=') => { eat_next(stream, pos); return Some((Token::XOrAssign, start_pos)); } ('^', _) => return Some((Token::XOr, start_pos)), ('~', _) => return Some((Token::Reserved("~".into()), start_pos)), ('%', '=') => { eat_next(stream, pos); return Some((Token::ModuloAssign, start_pos)); } ('%', _) => return Some((Token::Modulo, start_pos)), ('@', _) => return Some((Token::Reserved("@".into()), start_pos)), ('$', _) => return Some((Token::Reserved("$".into()), start_pos)), (ch, _) if ch.is_whitespace() => (), (ch, _) => { return Some(( Token::LexError(LERR::UnexpectedInput(ch.to_string())), start_pos, )) } } } pos.advance(); if state.end_with_none { None } else { Some((Token::EOF, *pos)) } } /// Get the next identifier. fn get_identifier( stream: &mut impl InputStream, pos: &mut Position, start_pos: Position, first_char: char, ) -> Option<(Token, Position)> { let mut result: smallvec::SmallVec<[char; 8]> = Default::default(); result.push(first_char); while let Some(next_char) = stream.peek_next() { match next_char { x if is_id_continue(x) => { result.push(x); eat_next(stream, pos); } _ => break, } } let is_valid_identifier = is_valid_identifier(result.iter().cloned()); let identifier: String = result.into_iter().collect(); if let Some(token) = Token::lookup_from_syntax(&identifier) { return Some((token, start_pos)); } if !is_valid_identifier { return Some(( Token::LexError(LERR::MalformedIdentifier(identifier)), start_pos, )); } return Some((Token::Identifier(identifier), start_pos)); } /// Is this keyword allowed as a function? #[inline(always)] pub fn is_keyword_function(name: &str) -> bool { match name { KEYWORD_PRINT | KEYWORD_DEBUG | KEYWORD_TYPE_OF | KEYWORD_EVAL | KEYWORD_FN_PTR | KEYWORD_FN_PTR_CALL | KEYWORD_FN_PTR_CURRY | KEYWORD_IS_DEF_VAR => true, #[cfg(not(feature = "no_function"))] KEYWORD_IS_DEF_FN => true, _ => false, } } /// Is a text string a valid identifier? pub fn is_valid_identifier(name: impl Iterator<Item = char>) -> bool { let mut first_alphabetic = false; for ch in name { match ch { '_' => (), _ if is_id_first_alphabetic(ch) => first_alphabetic = true, _ if !first_alphabetic => return false, _ if char::is_ascii_alphanumeric(&ch) => (), _ => return false, } } first_alphabetic } /// Is a character valid to start an identifier? #[cfg(feature = "unicode-xid-ident")] #[inline(always)] pub fn is_id_first_alphabetic(x: char) -> bool { unicode_xid::UnicodeXID::is_xid_start(x) } /// Is a character valid for an identifier? #[cfg(feature = "unicode-xid-ident")] #[inline(always)] pub fn is_id_continue(x: char) -> bool { unicode_xid::UnicodeXID::is_xid_continue(x) } /// Is a character valid to start an identifier? #[cfg(not(feature = "unicode-xid-ident"))] #[inline(always)] pub fn is_id_first_alphabetic(x: char) -> bool { x.is_ascii_alphabetic() } /// Is a character valid for an identifier? #[cfg(not(feature = "unicode-xid-ident"))] #[inline(always)] pub fn is_id_continue(x: char) -> bool { x.is_ascii_alphanumeric() || x == '_' } /// A type that implements the [`InputStream`] trait. /// Multiple character streams are jointed together to form one single stream. pub struct MultiInputsStream<'a> { /// Buffered character, if any. buf: Option<char>, /// The current stream index. index: usize, /// The input character streams. streams: StaticVec<Peekable<Chars<'a>>>, } impl InputStream for MultiInputsStream<'_> { #[inline(always)] fn unget(&mut self, ch: char) { if self.buf.is_some() { panic!("cannot unget two characters in a row"); } self.buf = Some(ch); } fn get_next(&mut self) -> Option<char> { if let Some(ch) = self.buf.take() { return Some(ch); } loop { if self.index >= self.streams.len() { // No more streams return None; } else if let Some(ch) = self.streams[self.index].next() { // Next character in current stream return Some(ch); } else { // Jump to the next stream self.index += 1; } } } fn peek_next(&mut self) -> Option<char> { if let Some(ch) = self.buf { return Some(ch); } loop { if self.index >= self.streams.len() { // No more streams return None; } else if let Some(&ch) = self.streams[self.index].peek() { // Next character in current stream return Some(ch); } else { // Jump to the next stream self.index += 1; } } } } /// An iterator on a [`Token`] stream. pub struct TokenIterator<'a> { /// Reference to the scripting `Engine`. engine: &'a Engine, /// Current state. state: TokenizeState, /// Current position. pos: Position, /// Buffer containing the next character to read, if any. buffer: Shared<Cell<Option<char>>>, /// Input character stream. stream: MultiInputsStream<'a>, /// A processor function that maps a token to another. map: Option<fn(Token) -> Token>, } impl<'a> Iterator for TokenIterator<'a> { type Item = (Token, Position); fn next(&mut self) -> Option<Self::Item> { if let Some(ch) = self.buffer.take() { self.stream.unget(ch); self.pos.rewind(); } let (token, pos) = match get_next_token(&mut self.stream, &mut self.state, &mut self.pos) { // {EOF} None => return None, // Reserved keyword/symbol Some((Token::Reserved(s), pos)) => (match (s.as_str(), self.engine.custom_keywords.contains_key(s.as_str())) { ("===", false) => Token::LexError(LERR::ImproperSymbol(s, "'===' is not a valid operator. This is not JavaScript! Should it be '=='?".to_string(), )), ("!==", false) => Token::LexError(LERR::ImproperSymbol(s, "'!==' is not a valid operator. This is not JavaScript! Should it be '!='?".to_string(), )), ("->", false) => Token::LexError(LERR::ImproperSymbol(s, "'->' is not a valid symbol. This is not C or C++!".to_string())), ("<-", false) => Token::LexError(LERR::ImproperSymbol(s, "'<-' is not a valid symbol. This is not Go! Should it be '<='?".to_string(), )), (":=", false) => Token::LexError(LERR::ImproperSymbol(s, "':=' is not a valid assignment operator. This is not Go or Pascal! Should it be simply '='?".to_string(), )), ("::<", false) => Token::LexError(LERR::ImproperSymbol(s, "'::<>' is not a valid symbol. This is not Rust! Should it be '::'?".to_string(), )), ("(*", false) | ("*)", false) | ("begin", false) | ("end", false) => Token::LexError(LERR::ImproperSymbol(s, "'(* .. *)' is not a valid comment format. This is not Pascal! Should it be '/* .. */'?".to_string(), )), ("#", false) => Token::LexError(LERR::ImproperSymbol(s, "'#' is not a valid symbol. Should it be '#{'?".to_string(), )), // Reserved keyword/operator that is custom. (_, true) => Token::Custom(s), // Reserved operator that is not custom. (token, false) if !is_valid_identifier(token.chars()) => { let msg = format!("'{}' is a reserved symbol", token); Token::LexError(LERR::ImproperSymbol(s, msg)) }, // Reserved keyword that is not custom and disabled. (token, false) if self.engine.disabled_symbols.contains(token) => { let msg = format!("reserved symbol '{}' is disabled", token); Token::LexError(LERR::ImproperSymbol(s, msg)) }, // Reserved keyword/operator that is not custom. (_, false) => Token::Reserved(s), }, pos), // Custom keyword Some((Token::Identifier(s), pos)) if self.engine.custom_keywords.contains_key(s.as_str()) => { (Token::Custom(s), pos) } // Custom standard keyword/symbol - must be disabled Some((token, pos)) if self.engine.custom_keywords.contains_key(token.syntax().as_ref()) => { if self.engine.disabled_symbols.contains(token.syntax().as_ref()) { // Disabled standard keyword/symbol (Token::Custom(token.syntax().into()), pos) } else { // Active standard keyword - should never be a custom keyword! unreachable!("{:?} is an active keyword", token) } } // Disabled symbol Some((token, pos)) if self.engine.disabled_symbols.contains(token.syntax().as_ref()) => { (Token::Reserved(token.syntax().into()), pos) } // Normal symbol Some(r) => r, }; // Run the mapper, if any let token = if let Some(map) = self.map { map(token) } else { token }; Some((token, pos)) } } impl FusedIterator for TokenIterator<'_> {} impl Engine { /// _(INTERNALS)_ Tokenize an input text stream. /// Exported under the `internals` feature only. #[cfg(feature = "internals")] #[inline(always)] pub fn lex<'a>( &'a self, input: impl IntoIterator<Item = &'a &'a str>, ) -> (TokenIterator<'a>, Shared<Cell<Option<char>>>) { self.lex_raw(input, None) } /// _(INTERNALS)_ Tokenize an input text stream with a mapping function. /// Exported under the `internals` feature only. #[cfg(feature = "internals")] #[inline(always)] pub fn lex_with_map<'a>( &'a self, input: impl IntoIterator<Item = &'a &'a str>, map: fn(Token) -> Token, ) -> (TokenIterator<'a>, Shared<Cell<Option<char>>>) { self.lex_raw(input, Some(map)) } /// Tokenize an input text stream with an optional mapping function. #[inline(always)] pub(crate) fn lex_raw<'a>( &'a self, input: impl IntoIterator<Item = &'a &'a str>, map: Option<fn(Token) -> Token>, ) -> (TokenIterator<'a>, Shared<Cell<Option<char>>>) { let buffer: Shared<Cell<Option<char>>> = Cell::new(None).into(); let buffer2 = buffer.clone(); ( TokenIterator { engine: self, state: TokenizeState { #[cfg(not(feature = "unchecked"))] max_string_size: self.limits.max_string_size, #[cfg(feature = "unchecked")] max_string_size: None, non_unary: false, comment_level: 0, end_with_none: false, include_comments: false, disable_doc_comments: self.disable_doc_comments, }, pos: Position::new(1, 0), buffer, stream: MultiInputsStream { buf: None, streams: input.into_iter().map(|s| s.chars().peekable()).collect(), index: 0, }, map, }, buffer2, ) } }
31.751876
126
0.436807
decf53ab14090f0a1e3fbe1702b8613f55e4f694
5,124
// Copyright 2020. 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 async_trait::async_trait; use futures::{pin_mut, StreamExt}; use std::time::Duration; use tari_service_framework::{ reply_channel, reply_channel::SenderService, ServiceInitializationError, ServiceInitializer, ServiceInitializerContext, }; use tari_shutdown::ShutdownSignal; use tokio::time::delay_for; use tower::Service; pub struct ServiceB { response_msg: String, request_stream: Option<reply_channel::Receiver<String, String>>, shutdown_signal: Option<ShutdownSignal>, } impl ServiceB { pub fn new( response_msg: String, request_stream: reply_channel::Receiver<String, String>, shutdown_signal: ShutdownSignal, ) -> Self { Self { response_msg, request_stream: Some(request_stream), shutdown_signal: Some(shutdown_signal), } } pub async fn run(mut self) { println!("Starting Service B"); let mut shutdown_signal = self .shutdown_signal .take() .expect("Service B initialized without shutdown signal"); let request_stream = self .request_stream .take() .expect("Service B initialized without request_stream") .fuse(); pin_mut!(request_stream); loop { futures::select! { //Incoming request request_context = request_stream.select_next_some() => { println!("Handling Service B API Request"); let (request, reply_tx) = request_context.split(); let mut response = self.response_msg.clone(); response.push_str(request.clone().as_str()); let _ = reply_tx.send(response); }, _ = shutdown_signal => { println!("Service B shutting down because the shutdown signal was received"); break; } } } println!("Service B is shutdown"); } } #[derive(Clone)] pub struct ServiceBHandle { request_tx: SenderService<String, String>, } impl ServiceBHandle { pub fn new(request_tx: SenderService<String, String>) -> Self { Self { request_tx } } pub async fn send_msg(&mut self, msg: String) -> String { self.request_tx.call(msg).await.unwrap() } } pub struct ServiceBInitializer { response_msg: String, } impl ServiceBInitializer { pub fn new(response_msg: String) -> Self { Self { response_msg } } } #[async_trait] impl ServiceInitializer for ServiceBInitializer { async fn initialize(&mut self, context: ServiceInitializerContext) -> Result<(), ServiceInitializationError> { let (sender, receiver) = reply_channel::unbounded(); let service_b_handle = ServiceBHandle::new(sender); println!("Service B is going to wait to register its handle"); println!("Service B is registering its handle now"); context.register_handle(service_b_handle); let response_msg = self.response_msg.clone(); println!("Service B initialized waiting on Handles Future to complete"); context.spawn_when_ready(move |handles| async move { println!("Service B got the handles"); let service = ServiceB::new(response_msg, receiver, handles.get_shutdown_signal()); service.run().await; println!("Service B has shutdown and initializer spawned task is now ending"); }); delay_for(Duration::from_secs(10)).await; Ok(()) } }
36.340426
118
0.665105
33cd45328030298773d010cd42263b83856959a2
14,496
//---------------------------------------------------------------------------// // Copyright (c) 2017-2020 Ismael Gutiérrez González. All rights reserved. // // This file is part of the Rusted PackFile Manager (RPFM) project, // which can be found here: https://github.com/Frodo45127/rpfm. // // This file is licensed under the MIT license, which can be found here: // https://github.com/Frodo45127/rpfm/blob/master/LICENSE. //---------------------------------------------------------------------------// /*! Module with the code to support migration operations from Schema V2 onwards. Schema V2 was the one used by RPFM between 2.0 and 2.1. Was written in Ron, Versioned. This module contains only the code needed for reading/writing Schemas V2 and for migrating them to Schemas V3. In case it's not clear enough, this is for supporting legacy schemas, not intended to be used externally in ANY other way. The basic structure of an V2 `Schema` is: ```rust ( version: 2, versioned_files: [ DB("_kv_battle_ai_ability_usage_variables_tables", [ ( version: 0, fields: [ ( name: "key", field_type: StringU8, is_key: true, default_value: None, max_length: 0, is_filename: false, filename_relative_path: None, is_reference: None, lookup: None, description: "", ca_order: -1, ), ( name: "value", field_type: Float, is_key: false, default_value: None, max_length: 0, is_filename: false, filename_relative_path: None, is_reference: None, lookup: None, description: "", ca_order: -1, ), ], localised_fields: [], ), ]), ], ) ``` !*/ use rayon::prelude::*; use ron::de::from_reader; use ron::ser::{to_string_pretty, PrettyConfig}; use serde_derive::{Serialize, Deserialize}; use std::cmp::Ordering; use std::collections::BTreeMap; use std::fs::File; use std::io::{BufReader, Write}; use rpfm_error::Result; use crate::settings::get_config_path; use crate::schema::SCHEMA_FOLDER; use crate::SUPPORTED_GAMES; use crate::schema::Schema as SchemaV3; use crate::schema::VersionedFile as VersionedFileV3; use crate::schema::Definition as DefinitionV3; use crate::schema::FieldType as FieldTypeV3; use crate::schema::Field as FieldV3; //---------------------------------------------------------------------------// // Enum & Structs //---------------------------------------------------------------------------// /// This struct represents a Schema File in memory, ready to be used to decode versioned PackedFiles. #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] pub struct SchemaV2 { /// It stores the structural version of the Schema. version: u16, /// It stores the versioned files inside the Schema. pub versioned_files: Vec<VersionedFileV2> } /// This enum defines all types of versioned files that the schema system supports. #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] pub enum VersionedFileV2 { /// It stores the name of the table, and a `Vec<Definition>` with the definitions for each version of that table decoded. DB(String, Vec<DefinitionV2>), /// It stores a `Vec<Definition>` to decode the dependencies of a PackFile. DepManager(Vec<DefinitionV2>), /// It stores a `Vec<Definition>` with the definitions for each version of Loc files decoded (currently, only version `1`). Loc(Vec<DefinitionV2>), } /// This struct contains all the data needed to decode a specific version of a versioned PackedFile. #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] pub struct DefinitionV2 { /// The version of the PackedFile the definition is for. These versions are: /// - `-1`: for fake `Definition`, used for dependency resolving stuff. /// - `0`: for unversioned PackedFiles. /// - `1+`: for versioned PackedFiles. pub version: i32, /// This is a collection of all `Field`s the PackedFile uses, in the order it uses them. pub fields: Vec<FieldV2>, /// This is a list of all the fields from this definition that are moved to a Loc PackedFile on exporting. pub localised_fields: Vec<FieldV2>, } /// This struct holds all the relevant data do properly decode a field from a versioned PackedFile. #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] pub struct FieldV2 { /// Name of the field. Should contain no spaces, using `_` instead. pub name: String, /// Type of the field. pub field_type: FieldTypeV2, /// `True` if the field is a `Key` field of a table. `False` otherwise. pub is_key: bool, /// The default value of the field. pub default_value: Option<String>, /// The max allowed lenght for the data in the field. pub max_length: i32, /// If the field's data corresponds to a filename. pub is_filename: bool, /// Path where the file in the data of the field can be, if it's restricted to one path. pub filename_relative_path: Option<String>, /// `Some(referenced_table, referenced_column)` if the field is referencing another table/column. `None` otherwise. pub is_reference: Option<(String, String)>, /// `Some(referenced_columns)` if the field is using another column/s from the referenced table for lookup values. pub lookup: Option<Vec<String>>, /// Aclarative description of what the field is for. pub description: String, /// Visual position in CA's Table. `-1` means we don't know its position. pub ca_order: i16, } /// This enum defines every type of field the lib can encode/decode. #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] pub enum FieldTypeV2 { Boolean, Float, Integer, LongInteger, StringU8, StringU16, OptionalStringU8, OptionalStringU16, Sequence(DefinitionV2) } //---------------------------------------------------------------------------// // Enum & Structs Implementations //---------------------------------------------------------------------------// impl SchemaV2 { /// This function adds a new `VersionedFile` to the schema. This checks if the provided `VersionedFile` /// already exists, and replace it if neccesary. pub fn add_versioned_file(&mut self, versioned_file: &VersionedFileV2) { match self.versioned_files.iter().position(|x| x.conflict(versioned_file)) { Some(position) => { self.versioned_files.splice(position..=position, [versioned_file.clone()].iter().cloned()); }, None => self.versioned_files.push(versioned_file.clone()), } } /// This function loads a `Schema` to memory from a file in the `schemas/` folder. pub fn load(schema_file: &str) -> Result<Self> { let mut file_path = get_config_path()?.join(SCHEMA_FOLDER); file_path.push(schema_file); let file = BufReader::new(File::open(&file_path)?); from_reader(file).map_err(From::from) } /// This function saves a `Schema` from memory to a file in the `schemas/` folder. pub fn save(&mut self, schema_file: &str) -> Result<()> { let mut file_path = get_config_path()?.join(SCHEMA_FOLDER); file_path.push(schema_file); let mut file = File::create(&file_path)?; let config = PrettyConfig::default(); self.sort(); file.write_all(to_string_pretty(&self, config)?.as_bytes())?; Ok(()) } /// This function sorts a `Schema` alphabetically, so the schema diffs are more or less clean. pub fn sort(&mut self) { self.versioned_files.sort_by(|a, b| { match a { VersionedFileV2::DB(table_name_a, _) => { match b { VersionedFileV2::DB(table_name_b, _) => table_name_a.cmp(table_name_b), _ => Ordering::Less, } } VersionedFileV2::DepManager(_) => { match b { VersionedFileV2::DB(_,_) => Ordering::Greater, VersionedFileV2::DepManager(_) => Ordering::Equal, VersionedFileV2::Loc(_) => Ordering::Less, } } VersionedFileV2::Loc(_) => { match b { VersionedFileV2::Loc(_) => Ordering::Equal, _ => Ordering::Greater, } } } }); } pub fn update() { println!("Importing schemas from V2 to V3"); let mut legacy_schemas = SUPPORTED_GAMES.get_games().iter().map(|y| (y.get_game_key_name(), Self::load(y.get_schema_name()))).filter_map(|(x, y)| if let Ok(y) = y { Some((x, From::from(&y))) } else { None }).collect::<BTreeMap<String, SchemaV3>>(); println!("Amount of SchemasV2: {:?}", legacy_schemas.len()); legacy_schemas.par_iter_mut().for_each(|(game, legacy_schema)| { if let Some(file_name) = SUPPORTED_GAMES.get_games().iter().filter_map(|y| if &y.get_game_key_name() == game { Some(y.get_schema_name()) } else { None }).find(|_| true) { if legacy_schema.save(file_name).is_ok() { println!("SchemaV2 for game {} updated to SchemaV3.", game); } } }); } } impl VersionedFileV2 { /// This function returns true if both `VersionFile` are conflicting (they're the same, but their definitions may be different). pub fn conflict(&self, secondary: &Self) -> bool { match &self { Self::DB(table_name, _) => match &secondary { Self::DB(secondary_table_name, _) => table_name == secondary_table_name, Self::DepManager( _) => false, Self::Loc( _) => false, }, Self::Loc(_) => secondary.is_loc(), Self::DepManager( _) => secondary.is_dep_manager(), } } /// This function returns true if the provided `VersionedFile` is a Dependency Manager Definition. Otherwise, it returns false. pub fn is_dep_manager(&self) -> bool { matches!(*self, Self::DepManager(_)) } /// This function returns true if the provided `VersionedFile` is a Loc Definition. Otherwise, it returns false. pub fn is_loc(&self) -> bool { matches!(*self, Self::Loc(_)) } } impl DefinitionV2 { pub fn new(version: i32) -> DefinitionV2 { DefinitionV2 { version, fields: vec![], localised_fields: vec![], } } } impl Default for FieldV2 { fn default() -> Self { Self { name: String::from("new_field"), field_type: FieldTypeV2::StringU8, is_key: false, default_value: None, max_length: 0, is_filename: false, filename_relative_path: None, is_reference: None, lookup: None, description: String::from(""), ca_order: -1, } } } impl From<&SchemaV2> for SchemaV3 { fn from(legacy_schema: &SchemaV2) -> Self { let mut schema = Self::default(); legacy_schema.versioned_files.iter().map(From::from).for_each(|x| schema.versioned_files.push(x)); schema } } impl From<&VersionedFileV2> for VersionedFileV3 { fn from(legacy_table_definitions: &VersionedFileV2) -> Self { match legacy_table_definitions { VersionedFileV2::DB(name, definitions) => Self::DB(name.to_string(), definitions.iter().map(From::from).collect()), VersionedFileV2::DepManager(definitions) => Self::DepManager(definitions.iter().map(From::from).collect()), VersionedFileV2::Loc(definitions) => Self::Loc(definitions.iter().map(From::from).collect()), } } } impl From<&DefinitionV2> for DefinitionV3 { fn from(legacy_table_definition: &DefinitionV2) -> Self { let mut definition = Self::new(legacy_table_definition.version); legacy_table_definition.fields.iter().map(From::from).for_each(|x| definition.fields.push(x)); legacy_table_definition.localised_fields.iter().map(From::from).for_each(|x| definition.localised_fields.push(x)); definition } } impl From<&FieldV2> for FieldV3 { fn from(legacy_field: &FieldV2) -> Self { Self { name: legacy_field.name.to_owned(), field_type: From::from(&legacy_field.field_type), is_key: legacy_field.is_key, default_value: legacy_field.default_value.clone(), max_length: legacy_field.max_length, is_filename: legacy_field.is_filename, filename_relative_path: legacy_field.filename_relative_path.clone(), is_reference: legacy_field.is_reference.clone(), lookup: legacy_field.lookup.clone(), description: legacy_field.description.to_owned(), ca_order: legacy_field.ca_order, ..Default::default() } } } impl From<&FieldTypeV2> for FieldTypeV3 { fn from(legacy_field_type: &FieldTypeV2) -> Self { match legacy_field_type { FieldTypeV2::Boolean => Self::Boolean, FieldTypeV2::Float => Self::F32, FieldTypeV2::Integer => Self::I32, FieldTypeV2::LongInteger => Self::I64, FieldTypeV2::StringU8 => Self::StringU8, FieldTypeV2::StringU16 => Self::StringU16, FieldTypeV2::OptionalStringU8 => Self::OptionalStringU8, FieldTypeV2::OptionalStringU16 => Self::OptionalStringU16, FieldTypeV2::Sequence(sequence) => Self::SequenceU32(From::from(sequence)), } } } /// Default implementation of `SchemaV3`. impl Default for SchemaV2 { fn default() -> Self { Self { version: 2, versioned_files: vec![] } } }
37.457364
256
0.583126
6425e6a28ece00f03c03184302a59962925caad8
11,555
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! The compiler code necessary to implement the `#[derive(Encodable)]` //! (and `Decodable`, in decodable.rs) extension. The idea here is that //! type-defining items may be tagged with `#[derive(Encodable, Decodable)]`. //! //! For example, a type like: //! //! ```ignore //! #[derive(Encodable, Decodable)] //! struct Node { id: usize } //! ``` //! //! would generate two implementations like: //! //! ```ignore //! impl<S: Encoder<E>, E> Encodable<S, E> for Node { //! fn encode(&self, s: &mut S) -> Result<(), E> { //! s.emit_struct("Node", 1, |this| { //! this.emit_struct_field("id", 0, |this| { //! Encodable::encode(&self.id, this) //! /* this.emit_usize(self.id) can also be used */ //! }) //! }) //! } //! } //! //! impl<D: Decoder<E>, E> Decodable<D, E> for Node { //! fn decode(d: &mut D) -> Result<Node, E> { //! d.read_struct("Node", 1, |this| { //! match this.read_struct_field("id", 0, |this| Decodable::decode(this)) { //! Ok(id) => Ok(Node { id: id }), //! Err(e) => Err(e), //! } //! }) //! } //! } //! ``` //! //! Other interesting scenarios are when the item has type parameters or //! references other non-built-in types. A type definition like: //! //! ```ignore //! #[derive(Encodable, Decodable)] //! struct Spanned<T> { node: T, span: Span } //! ``` //! //! would yield functions like: //! //! ```ignore //! impl< //! S: Encoder<E>, //! E, //! T: Encodable<S, E> //! > Encodable<S, E> for Spanned<T> { //! fn encode(&self, s: &mut S) -> Result<(), E> { //! s.emit_struct("Spanned", 2, |this| { //! this.emit_struct_field("node", 0, |this| self.node.encode(this)) //! .unwrap(); //! this.emit_struct_field("span", 1, |this| self.span.encode(this)) //! }) //! } //! } //! //! impl< //! D: Decoder<E>, //! E, //! T: Decodable<D, E> //! > Decodable<D, E> for Spanned<T> { //! fn decode(d: &mut D) -> Result<Spanned<T>, E> { //! d.read_struct("Spanned", 2, |this| { //! Ok(Spanned { //! node: this.read_struct_field("node", 0, |this| Decodable::decode(this)) //! .unwrap(), //! span: this.read_struct_field("span", 1, |this| Decodable::decode(this)) //! .unwrap(), //! }) //! }) //! } //! } //! ``` use ast::{MetaItem, Item, Expr, ExprRet, MutMutable}; use codemap::Span; use ext::base::ExtCtxt; use ext::build::AstBuilder; use ext::deriving::generic::*; use ext::deriving::generic::ty::*; use parse::token; use ptr::P; pub fn expand_deriving_rustc_encodable<F>(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Item, push: F) where F: FnOnce(P<Item>), { expand_deriving_encodable_imp(cx, span, mitem, item, push, "rustc_serialize") } pub fn expand_deriving_encodable<F>(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Item, push: F) where F: FnOnce(P<Item>), { expand_deriving_encodable_imp(cx, span, mitem, item, push, "serialize") } fn expand_deriving_encodable_imp<F>(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Item, push: F, krate: &'static str) where F: FnOnce(P<Item>), { if !cx.use_std { // FIXME(#21880): lift this requirement. cx.span_err(span, "this trait cannot be derived with #![no_std]"); return; } let trait_def = TraitDef { span: span, attributes: Vec::new(), path: Path::new_(vec!(krate, "Encodable"), None, vec!(), true), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), methods: vec!( MethodDef { name: "encode", generics: LifetimeBounds { lifetimes: Vec::new(), bounds: vec!(("__S", vec!(Path::new_( vec!(krate, "Encoder"), None, vec!(), true)))) }, explicit_self: borrowed_explicit_self(), args: vec!(Ptr(box Literal(Path::new_local("__S")), Borrowed(None, MutMutable))), ret_ty: Literal(Path::new_( pathvec_std!(cx, core::result::Result), None, vec!(box Tuple(Vec::new()), box Literal(Path::new_( vec!["__S", "Error"], None, vec![], false ))), true )), attributes: Vec::new(), combine_substructure: combine_substructure(Box::new(|a, b, c| { encodable_substructure(a, b, c) })), } ), associated_types: Vec::new(), }; trait_def.expand(cx, mitem, item, push) } fn encodable_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> { let encoder = substr.nonself_args[0].clone(); // throw an underscore in front to suppress unused variable warnings let blkarg = cx.ident_of("_e"); let blkencoder = cx.expr_ident(trait_span, blkarg); let encode = cx.ident_of("encode"); return match *substr.fields { Struct(ref fields) => { let emit_struct_field = cx.ident_of("emit_struct_field"); let mut stmts = Vec::new(); for (i, &FieldInfo { name, ref self_, span, .. }) in fields.iter().enumerate() { let name = match name { Some(id) => token::get_ident(id), None => { token::intern_and_get_ident(&format!("_field{}", i)) } }; let enc = cx.expr_method_call(span, self_.clone(), encode, vec!(blkencoder.clone())); let lambda = cx.lambda_expr_1(span, enc, blkarg); let call = cx.expr_method_call(span, blkencoder.clone(), emit_struct_field, vec!(cx.expr_str(span, name), cx.expr_usize(span, i), lambda)); // last call doesn't need a try! let last = fields.len() - 1; let call = if i != last { cx.expr_try(span, call) } else { cx.expr(span, ExprRet(Some(call))) }; stmts.push(cx.stmt_expr(call)); } // unit structs have no fields and need to return Ok() if stmts.is_empty() { let ret_ok = cx.expr(trait_span, ExprRet(Some(cx.expr_ok(trait_span, cx.expr_tuple(trait_span, vec![]))))); stmts.push(cx.stmt_expr(ret_ok)); } let blk = cx.lambda_stmts_1(trait_span, stmts, blkarg); cx.expr_method_call(trait_span, encoder, cx.ident_of("emit_struct"), vec!( cx.expr_str(trait_span, token::get_ident(substr.type_ident)), cx.expr_usize(trait_span, fields.len()), blk )) } EnumMatching(idx, variant, ref fields) => { // We're not generating an AST that the borrow checker is expecting, // so we need to generate a unique local variable to take the // mutable loan out on, otherwise we get conflicts which don't // actually exist. let me = cx.stmt_let(trait_span, false, blkarg, encoder); let encoder = cx.expr_ident(trait_span, blkarg); let emit_variant_arg = cx.ident_of("emit_enum_variant_arg"); let mut stmts = Vec::new(); if !fields.is_empty() { let last = fields.len() - 1; for (i, &FieldInfo { ref self_, span, .. }) in fields.iter().enumerate() { let enc = cx.expr_method_call(span, self_.clone(), encode, vec!(blkencoder.clone())); let lambda = cx.lambda_expr_1(span, enc, blkarg); let call = cx.expr_method_call(span, blkencoder.clone(), emit_variant_arg, vec!(cx.expr_usize(span, i), lambda)); let call = if i != last { cx.expr_try(span, call) } else { cx.expr(span, ExprRet(Some(call))) }; stmts.push(cx.stmt_expr(call)); } } else { let ret_ok = cx.expr(trait_span, ExprRet(Some(cx.expr_ok(trait_span, cx.expr_tuple(trait_span, vec![]))))); stmts.push(cx.stmt_expr(ret_ok)); } let blk = cx.lambda_stmts_1(trait_span, stmts, blkarg); let name = cx.expr_str(trait_span, token::get_ident(variant.node.name)); let call = cx.expr_method_call(trait_span, blkencoder, cx.ident_of("emit_enum_variant"), vec!(name, cx.expr_usize(trait_span, idx), cx.expr_usize(trait_span, fields.len()), blk)); let blk = cx.lambda_expr_1(trait_span, call, blkarg); let ret = cx.expr_method_call(trait_span, encoder, cx.ident_of("emit_enum"), vec!( cx.expr_str(trait_span, token::get_ident(substr.type_ident)), blk )); cx.expr_block(cx.block(trait_span, vec!(me), Some(ret))) } _ => cx.bug("expected Struct or EnumMatching in derive(Encodable)") }; }
39.982699
99
0.455647
d940cc8ba897423329492be7629fee1d71e0f014
2,273
use crate::utils::utils_paths::linear_spline_path::LinearSplinePath; use crate::utils::utils_math::interpolation_utils::*; use nalgebra::DVector; #[derive(Clone, Debug)] pub struct ArclengthParameterizationUtil { _distances_to_each_waypoint: Vec<f64>, _length_ratio_to_each_waypoint: Vec<f64>, _total_dis: f64 } impl ArclengthParameterizationUtil { pub fn new(linear_spline_path: &LinearSplinePath) -> Self { let mut _distances_to_each_waypoint = Vec::new(); let mut _length_ratio_to_each_waypoint = Vec::new(); let mut _total_dis = 0.0; let waypoints_ref = &linear_spline_path.waypoints; let l = waypoints_ref.len(); if l > 0 { _distances_to_each_waypoint.push(0.0); } if l > 1 { for i in 1..l { let dis = (&waypoints_ref[i] - &waypoints_ref[i-1]).norm(); _distances_to_each_waypoint.push(dis + _distances_to_each_waypoint[i-1]); } } _total_dis = _distances_to_each_waypoint[l-1]; for i in 0..l { _length_ratio_to_each_waypoint.push( _distances_to_each_waypoint[i] / _total_dis ); } Self { _distances_to_each_waypoint, _length_ratio_to_each_waypoint, _total_dis } } pub fn get_arclength_interpolated_point(&self, linear_spline_path: &LinearSplinePath, u: f64) -> DVector<f64> { let mut u_ = u.max(0.0).min(1.0); let binary_search_res = self._length_ratio_to_each_waypoint.binary_search_by(|x| x.partial_cmp(&u_).unwrap()); return match binary_search_res { Ok(i) => { linear_spline_path.waypoints[i].clone() } Err(i) => { let upper_boundary_length_ratio = self._length_ratio_to_each_waypoint[i]; let lower_boundary_length_ratio = self._length_ratio_to_each_waypoint[i - 1]; let ratio_between_boundaries = (u - lower_boundary_length_ratio) / (upper_boundary_length_ratio - lower_boundary_length_ratio); (1.0 - ratio_between_boundaries) * &linear_spline_path.waypoints[i - 1] + (ratio_between_boundaries) * &linear_spline_path.waypoints[i] } } } }
36.079365
151
0.637923
48c4461ba938324b12dee8ea799fd10739fdee80
473
#![cfg_attr(not(with_main), no_std)] trait Tr { type Result; fn f(&self) -> Self::Result; } struct St(i32); impl Tr for St { type Result = i32; fn f(&self) -> i32 { self.0 } } pub fn f(x: i32) -> i32 { let st = St(100); let tr: &dyn Tr<Result = i32> = &st; tr.f() } pub static ARG: i32 = 1; #[cfg(with_main)] pub fn main() { println!("{:?}", f(ARG)); } #[cfg(not(with_main))] #[cfg_attr(crux, crux_test)] fn crux_test() -> i32 { f(ARG) }
18.192308
84
0.547569
69969db437d6c89da7a05f31515a43673f5a6bfb
1,466
use std::ops::Neg; #[derive(Debug, PartialOrd, PartialEq, Copy, Clone)] pub enum Number { Real(i64), Float(f64), } impl Default for Number { fn default() -> Self { Self::Real(0) } } impl Neg for Number { type Output = Number; fn neg(self) -> Self::Output { match self { Number::Float(n) => Number::Float(-n), Number::Real(n) => Number::Real(-n), } } } macro_rules! impl_float { ($t:ty) => { impl From<$t> for Number { fn from(n: $t) -> Number { Number::Float(n as f64) } } impl From<Number> for $t { fn from(n: Number) -> Self { match n { Number::Real(n) => n as $t, Number::Float(n) => n as $t, } } } }; } macro_rules! impl_real { ($t:ty) => { impl From<$t> for Number { fn from(n: $t) -> Number { Number::Real(n as i64) } } impl From<Number> for $t { fn from(n: Number) -> $t { match n { Number::Real(n) => n as $t, Number::Float(n) => n as $t, } } } }; } impl_float!(f32); impl_float!(f64); impl_real!(u8); impl_real!(i8); impl_real!(u16); impl_real!(i16); impl_real!(u32); impl_real!(i32); impl_real!(u64); impl_real!(i64);
19.546667
52
0.431105
3af9c0518924a84323d1a7c0e810b6cc0689a0db
488
// This test case makes sure that the compiler doesn't crash due to a failing // table lookup when a source file is removed. // revisions:cfail1 cfail2 // Note that we specify -g so that the SourceFiles actually get referenced by the // incr. comp. cache: // compile-flags: -Z query-dep-graph -g // compile-pass #![crate_type= "rlib"] #[cfg(cfail1)] mod auxiliary; #[cfg(cfail1)] pub fn foo() { auxiliary::print_hello(); } #[cfg(cfail2)] pub fn foo() { println!("hello"); }
19.52
81
0.680328
28d140e80846e2ce14f8f3198777a6669d32f863
3,728
use super::{Open, Sink}; use crate::config::AudioFormat; use crate::convert::Converter; use crate::decoder::AudioPacket; use crate::{NUM_CHANNELS, SAMPLE_RATE}; use sdl2::audio::{AudioQueue, AudioSpecDesired}; use std::time::Duration; use std::{io, thread}; pub enum SdlSink { F32(AudioQueue<f32>), S32(AudioQueue<i32>), S16(AudioQueue<i16>), } impl Open for SdlSink { fn open(device: Option<String>, format: AudioFormat) -> Self { info!("Using SDL sink with format: {:?}", format); if device.is_some() { warn!("SDL sink does not support specifying a device name"); } let ctx = sdl2::init().expect("could not initialize SDL"); let audio = ctx .audio() .expect("could not initialize SDL audio subsystem"); let desired_spec = AudioSpecDesired { freq: Some(SAMPLE_RATE as i32), channels: Some(NUM_CHANNELS), samples: None, }; macro_rules! open_sink { ($sink: expr, $type: ty) => {{ let queue: AudioQueue<$type> = audio .open_queue(None, &desired_spec) .expect("could not open SDL audio device"); $sink(queue) }}; } match format { AudioFormat::F32 => open_sink!(Self::F32, f32), AudioFormat::S32 => open_sink!(Self::S32, i32), AudioFormat::S16 => open_sink!(Self::S16, i16), _ => { unimplemented!("SDL currently does not support {:?} output", format) } } } } impl Sink for SdlSink { fn start(&mut self) -> io::Result<()> { macro_rules! start_sink { ($queue: expr) => {{ $queue.clear(); $queue.resume(); }}; } match self { Self::F32(queue) => start_sink!(queue), Self::S32(queue) => start_sink!(queue), Self::S16(queue) => start_sink!(queue), }; Ok(()) } fn stop(&mut self) -> io::Result<()> { macro_rules! stop_sink { ($queue: expr) => {{ $queue.pause(); $queue.clear(); }}; } match self { Self::F32(queue) => stop_sink!(queue), Self::S32(queue) => stop_sink!(queue), Self::S16(queue) => stop_sink!(queue), }; Ok(()) } fn write(&mut self, packet: &AudioPacket, converter: &mut Converter) -> io::Result<()> { macro_rules! drain_sink { ($queue: expr, $size: expr) => {{ // sleep and wait for sdl thread to drain the queue a bit while $queue.size() > (NUM_CHANNELS as u32 * $size as u32 * SAMPLE_RATE) { thread::sleep(Duration::from_millis(10)); } }}; } let samples = packet.samples(); match self { Self::F32(queue) => { let samples_f32: &[f32] = &converter.f64_to_f32(samples); drain_sink!(queue, AudioFormat::F32.size()); queue.queue(samples_f32) } Self::S32(queue) => { let samples_s32: &[i32] = &converter.f64_to_s32(samples); drain_sink!(queue, AudioFormat::S32.size()); queue.queue(samples_s32) } Self::S16(queue) => { let samples_s16: &[i16] = &converter.f64_to_s16(samples); drain_sink!(queue, AudioFormat::S16.size()); queue.queue(samples_s16) } }; Ok(()) } } impl SdlSink { pub const NAME: &'static str = "sdl"; }
31.066667
92
0.496245
091a8392780a0ee7fd25b4fd12b7729c5151fc04
6,102
use super::worker::Worker; use futures_core::ready; use std::error::Error; use std::fmt; use std::task::Poll; /// Error raised by `blocking`. pub struct BlockingError { _p: (), } /// Enter a blocking section of code. /// /// The `blocking` function annotates a section of code that performs a blocking /// operation, either by issuing a blocking syscall or by performing a long /// running CPU-bound computation. /// /// When the `blocking` function enters, it hands off the responsibility of /// processing the current work queue to another thread. Then, it calls the /// supplied closure. The closure is permitted to block indefinitely. /// /// If the maximum number of concurrent `blocking` calls has been reached, then /// `NotReady` is returned and the task is notified once existing `blocking` /// calls complete. The maximum value is specified when creating a thread pool /// using [`Builder::max_blocking`][build] /// /// NB: The entire task that called `blocking` is blocked whenever the supplied /// closure blocks, even if you have used future combinators such as `select` - /// the other futures in this task will not make progress until the closure /// returns. /// If this is not desired, ensure that `blocking` runs in its own task (e.g. /// using `futures::sync::oneshot::spawn`). /// /// [build]: struct.Builder.html#method.max_blocking /// /// # Return /// /// When the blocking closure is executed, `Ok(Ready(T))` is returned, where /// `T` is the closure's return value. /// /// If the thread pool has shutdown, `Err` is returned. /// /// If the number of concurrent `blocking` calls has reached the maximum, /// `Ok(NotReady)` is returned and the current task is notified when a call to /// `blocking` will succeed. /// /// If `blocking` is called from outside the context of a Tokio thread pool, /// `Err` is returned. /// /// # Background /// /// By default, the Tokio thread pool expects that tasks will only run for short /// periods at a time before yielding back to the thread pool. This is the basic /// premise of cooperative multitasking. /// /// However, it is common to want to perform a blocking operation while /// processing an asynchronous computation. Examples of blocking operation /// include: /// /// * Performing synchronous file operations (reading and writing). /// * Blocking on acquiring a mutex. /// * Performing a CPU bound computation, like cryptographic encryption or /// decryption. /// /// One option for dealing with blocking operations in an asynchronous context /// is to use a thread pool dedicated to performing these operations. This not /// ideal as it requires bidirectional message passing as well as a channel to /// communicate which adds a level of buffering. /// /// Instead, `blocking` hands off the responsibility of processing the work queue /// to another thread. This hand off is light compared to a channel and does not /// require buffering. /// /// # Examples /// /// Block on receiving a message from a `std` channel. This example is a little /// silly as using the non-blocking channel from the `futures` crate would make /// more sense. The blocking receive can be replaced with any blocking operation /// that needs to be performed. /// /// ```rust /// use tokio_executor::threadpool::{ThreadPool, blocking}; /// /// use futures_util::future::poll_fn; /// use std::sync::mpsc; /// use std::thread; /// use std::time::Duration; /// /// pub fn main() { /// // This is a *blocking* channel /// let (tx, rx) = mpsc::channel(); /// /// // Spawn a thread to send a message /// thread::spawn(move || { /// thread::sleep(Duration::from_millis(500)); /// tx.send("hello").unwrap(); /// }); /// /// let pool = ThreadPool::new(); /// /// pool.spawn(async move { /// // Because `blocking` returns `Poll`, it is intended to be used /// // from the context of a `Future` implementation. Since we don't /// // have a complicated requirement, we can use `poll_fn` in this /// // case. /// poll_fn(move |_| { /// blocking(|| { /// let msg = rx.recv().unwrap(); /// println!("message = {}", msg); /// }).map_err(|_| panic!("the threadpool shut down")) /// }).await; /// }); /// /// // Wait for the task we just spawned to complete. /// pool.shutdown_on_idle().wait(); /// } /// ``` pub fn blocking<F, T>(f: F) -> Poll<Result<T, BlockingError>> where F: FnOnce() -> T, { let res = Worker::with_current(|worker| { let worker = match worker { Some(worker) => worker, None => { return Poll::Ready(Err(BlockingError { _p: () })); } }; // Transition the worker state to blocking. This will exit the fn early // with `NotReady` if the pool does not have enough capacity to enter // blocking mode. worker.transition_to_blocking() }); // If the transition cannot happen, exit early ready!(res)?; // Currently in blocking mode, so call the inner closure // // "Exit" the current executor in case the blocking function wants // to call a different executor. let ret = crate::exit(move || f()); // Try to transition out of blocking mode. This is a fast path that takes // back ownership of the worker if the worker handoff didn't complete yet. Worker::with_current(|worker| { // Worker must be set since it was above. worker.unwrap().transition_from_blocking(); }); // Return the result Poll::Ready(Ok(ret)) } impl fmt::Display for BlockingError { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!( fmt, "`blocking` annotation used from outside the context of a thread pool" ) } } impl fmt::Debug for BlockingError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("BlockingError") .field("reason", &format!("{}", self)) .finish() } } impl Error for BlockingError {}
34.868571
82
0.643232
75d6234d362bf8657e2485d7485501f7fc60e774
148
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 pub mod coverage_map; pub mod source_coverage; pub mod summary;
21.142857
43
0.77027
f81acb267e5a814aaa9b29e32d1c2aca2fdcb11a
1,441
use crate::pack; use git_object::borrowed; use quick_error::quick_error; quick_error! { #[derive(Debug)] pub enum Error { Decode(err: pack::data::decode::Error) { display("Could not decode object") } } } impl pack::Bundle { /// `id` is a 20 byte SHA1 of the object to locate in the pack /// /// Note that ref deltas are automatically resolved within this pack only, which makes this implementation unusable /// for thin packs. /// For the latter, pack streams are required. pub fn locate<'a>( &self, id: borrowed::Id, out: &'a mut Vec<u8>, cache: &mut impl pack::cache::DecodeEntry, ) -> Option<Result<pack::Object<'a>, Error>> { let idx = self.index.lookup(id)?; let ofs = self.index.pack_offset_at_index(idx); let pack_entry = self.pack.entry(ofs); self.pack .decode_entry( pack_entry, out, |id, _out| { self.index.lookup(id).map(|idx| { pack::data::decode::ResolvedBase::InPack(self.pack.entry(self.index.pack_offset_at_index(idx))) }) }, cache, ) .map_err(Error::Decode) .map(move |r| pack::Object { kind: r.kind, data: out.as_slice(), }) .into() } }
30.020833
119
0.515614
5baf1b2ff17227f29c0d98e74610338b767ba3ef
1,486
// Length of the entries in `struct utsname_t` is 65. const UTSNAME_LENGTH: usize = 65; #[repr(C)] #[derive(Clone)] pub struct new_utsname_t { pub sysname: [u8; UTSNAME_LENGTH], pub nodename: [u8; UTSNAME_LENGTH], pub release: [u8; UTSNAME_LENGTH], pub version: [u8; UTSNAME_LENGTH], pub machine: [u8; UTSNAME_LENGTH], pub domainname: [u8; UTSNAME_LENGTH], } pub type utsname_t = new_utsname_t; impl core::fmt::Debug for utsname_t { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { unsafe { write!( f, "utsname_t {{ sysname: {}, nodename: {}, release: {}, \ version: {}, machine: {}, domainname: {} }}", core::str::from_utf8_unchecked(&self.sysname), core::str::from_utf8_unchecked(&self.nodename), core::str::from_utf8_unchecked(&self.release), core::str::from_utf8_unchecked(&self.version), core::str::from_utf8_unchecked(&self.machine), core::str::from_utf8_unchecked(&self.domainname) ) } } } impl Default for utsname_t { fn default() -> Self { utsname_t { sysname: [0; UTSNAME_LENGTH], nodename: [0; UTSNAME_LENGTH], release: [0; UTSNAME_LENGTH], version: [0; UTSNAME_LENGTH], machine: [0; UTSNAME_LENGTH], domainname: [0; UTSNAME_LENGTH], } } }
31.617021
71
0.562584
0989db2f376a3a6f6c20dbaaf9b356b5749a31bc
258
#![ warn( rust_2018_idioms ) ] #![ warn( missing_debug_implementations ) ] #![ warn( missing_docs ) ] // #![ feature( trace_macros ) ] use fundamental_data_type as TheModule; #[ allow( unused_imports ) ] use test_tools::*; #[ path = "./inc.rs" ] mod inc;
19.846154
43
0.658915
4bf1d0ae6ec099c4b430a9ae5b1ca7b8932f79a0
6,146
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { crate::act::ActionContext, crate::metrics::{metric_value::MetricValue, MetricState}, anyhow::{bail, Error}, injectable_time::{MonotonicTime, TimeSource}, regex::Regex, }; pub(crate) mod act; // Perform appropriate actions. pub(crate) mod config; // Read the config file(s) for metric and action specs. pub(crate) mod metrics; // Retrieve and calculate the metrics. pub(crate) mod plugins; // Plugins for additional analysis. pub(crate) mod result_format; // Formats the triage results. pub(crate) mod validate; // Check config - including that metrics/triggers work correctly. pub use act::{ActionResults, SnapshotTrigger, WarningVec}; pub use config::{ActionTagDirective, DataFetcher, DiagnosticData, ParseResult, Source}; pub use result_format::ActionResultFormatter; const DEVICE_UPTIME_KEY: &str = "device.uptime"; fn time_from_snapshot(files: &Vec<DiagnosticData>) -> Option<i64> { if let Some(file) = files.iter().find(|file| file.source == Source::Annotations) { if let DataFetcher::KeyValue(fetcher) = &file.data { if let MetricValue::String(duration) = fetcher.fetch(DEVICE_UPTIME_KEY) { let re = Regex::new(r"^(\d+)d(\d+)h(\d+)m(\d+)s$").unwrap(); if let Some(c) = re.captures(&duration) { let dhms = (c.get(1), c.get(2), c.get(3), c.get(4)); if let (Some(d), Some(h), Some(m), Some(s)) = dhms { let dhms = ( d.as_str().parse::<i64>(), h.as_str().parse::<i64>(), m.as_str().parse::<i64>(), s.as_str().parse::<i64>(), ); if let (Ok(d), Ok(h), Ok(m), Ok(s)) = dhms { return Some(1_000_000_000 * (s + 60 * (m + 60 * (h + 24 * d)))); } } } } } } None } /// Analyze all DiagnosticData against loaded configs and generate corresponding ActionResults. /// Each DiagnosticData will yield a single ActionResults instance. pub fn analyze( diagnostic_data: &Vec<DiagnosticData>, parse_result: &ParseResult, ) -> Result<ActionResults, Error> { let now = time_from_snapshot(diagnostic_data); let mut action_context = ActionContext::new(&parse_result.metrics, &parse_result.actions, diagnostic_data, now); Ok(action_context.process().clone()) } // Do not call this from WASM - WASM does not provde a monotonic clock. pub fn snapshots( data: &Vec<DiagnosticData>, parse_result: &ParseResult, ) -> (Vec<SnapshotTrigger>, act::WarningVec) { let now = Some(MonotonicTime::new().now()); let evaluator = ActionContext::new(&parse_result.metrics, &parse_result.actions, data, now); evaluator.into_snapshots() } pub fn all_selectors(parse: &ParseResult) -> Vec<String> { parse.all_selectors() } pub fn evaluate_int_math(expression: &str) -> Result<i64, Error> { match MetricState::evaluate_math(expression) { MetricValue::Int(i) => Ok(i), MetricValue::Float(f) => match metrics::safe_float_to_int(f) { Some(i) => Ok(i), None => bail!("Non-numeric float result {}", f), }, MetricValue::Missing(msg) => bail!("Eval error: {}", msg), bad_type => bail!("Non-numeric result: {:?}", bad_type), } } #[cfg(test)] mod test { use super::*; #[test] fn time_parses_correctly() { fn file(name: &str, source: Source, contents: &str) -> DiagnosticData { DiagnosticData::new(name.to_string(), source, contents.to_string()).unwrap() } assert_eq!(time_from_snapshot(&vec![]), None); // DiagnosticData can't be created with invalid JSON. let files = vec![file("foo.json", Source::Annotations, r#"{"a":"b"}"#)]; assert_eq!(time_from_snapshot(&files), None); let files = vec![file("any.name.works", Source::Annotations, r#"{"device.uptime":"b"}"#)]; assert_eq!(time_from_snapshot(&files), None); let files = vec![file("foo.json", Source::Annotations, r#"{"device.uptime":"1h1m1s"}"#)]; assert_eq!(time_from_snapshot(&files), None); let files = vec![file("foo.json", Source::Annotations, r#"{"device.uptime":"1d1h1m"}"#)]; assert_eq!(time_from_snapshot(&files), None); let files = vec![file("foo.json", Source::Annotations, r#"{"device.uptime":"0d0h0m0s"}"#)]; assert_eq!(time_from_snapshot(&files), Some(0)); let files = vec![file("a.b", Source::Annotations, r#"{"device.uptime":"2d3h4m5s"}"#)]; assert_eq!(time_from_snapshot(&files), Some(1_000_000_000 * 183845)); let files = vec![file("a.b", Source::Annotations, r#"{"device.uptime":"11d13h17m19s"}"#)]; let seconds = 19 + 17 * 60 + 13 * 3600 + 11 * 3600 * 24; assert_eq!(time_from_snapshot(&files), Some(1_000_000_000 * seconds)); let files = vec![file("", Source::Annotations, r#"{"device.uptime":"3d5h7m11s"}"#)]; let hours = 5 + 24 * 3; let minutes = 7 + 60 * hours; let seconds = 11 + 60 * minutes; assert_eq!(time_from_snapshot(&files), Some(1_000_000_000 * seconds)); let files = vec![file("foo.json", Source::Annotations, r#"{"device.uptime":"0d0h0m1s"}"#)]; assert_eq!(time_from_snapshot(&files), Some(1_000_000_000)); let files = vec![file("foo.json", Source::Annotations, r#"{"device.uptime":"0d0h1m0s"}"#)]; assert_eq!(time_from_snapshot(&files), Some(1_000_000_000 * 60)); let files = vec![file("foo.json", Source::Annotations, r#"{"device.uptime":"0d1h0m0s"}"#)]; assert_eq!(time_from_snapshot(&files), Some(1_000_000_000 * 60 * 60)); let files = vec![file("foo.json", Source::Annotations, r#"{"device.uptime":"1d0h0m0s"}"#)]; assert_eq!(time_from_snapshot(&files), Some(1_000_000_000 * 60 * 60 * 24)); } }
47.276923
99
0.6082
71703269eb1c18fd0fddfc52c497263450460899
1,126
fn main() { let number = 6; if number % 4 == 0 { println!("number is divisible by 4"); } else if number % 3 == 0 { println!("number is divisible by 3"); } else if number % 2 == 0 { println!("number is divisible by 2"); } else { println!("number is not divisible by 4, 3, or 2"); } //loop_test(); return_from_loop(); while_test(); for_test(); reverse(); } fn loop_test(){ loop { println!("again!"); } } fn return_from_loop(){ let mut counter = 0; let result = loop { counter += 1; if counter == 10 { break counter * 2; } }; println!("The result is {}", result); } fn while_test() { let mut number = 3; while number != 0 { println!("{}!", number); number -= 1; } println!("LIFTOFF!!!"); } fn for_test(){ let a = [10, 20, 30, 40, 50]; for element in a.iter() { println!("the value is: {}", element); } } fn reverse(){ for number in (1..4).rev() { println!("{}!", number); } println!("LIFTOFF!!!"); }
17.060606
58
0.478686
76d240bb89f59cfb5dce98a0913ce876046d16d8
17,418
use rustc_data_structures::graph::dominators::Dominators; use rustc_middle::mir::visit::Visitor; use rustc_middle::mir::{BasicBlock, Body, Location, Place, Rvalue}; use rustc_middle::mir::{BorrowKind, Mutability, Operand}; use rustc_middle::mir::{InlineAsmOperand, Terminator, TerminatorKind}; use rustc_middle::mir::{Statement, StatementKind}; use rustc_middle::ty::TyCtxt; use crate::{ borrow_set::BorrowSet, facts::AllFacts, location::LocationTable, path_utils::*, AccessDepth, Activation, ArtificialField, BorrowIndex, Deep, LocalMutationIsAllowed, Read, ReadKind, ReadOrWrite, Reservation, Shallow, Write, WriteKind, }; pub(super) fn generate_invalidates<'tcx>( tcx: TyCtxt<'tcx>, all_facts: &mut Option<AllFacts>, location_table: &LocationTable, body: &Body<'tcx>, borrow_set: &BorrowSet<'tcx>, ) { if all_facts.is_none() { // Nothing to do if we don't have any facts return; } if let Some(all_facts) = all_facts { let _prof_timer = tcx.prof.generic_activity("polonius_fact_generation"); let dominators = body.dominators(); let mut ig = InvalidationGenerator { all_facts, borrow_set, tcx, location_table, body: &body, dominators, }; ig.visit_body(body); } } struct InvalidationGenerator<'cx, 'tcx> { tcx: TyCtxt<'tcx>, all_facts: &'cx mut AllFacts, location_table: &'cx LocationTable, body: &'cx Body<'tcx>, dominators: Dominators<BasicBlock>, borrow_set: &'cx BorrowSet<'tcx>, } /// Visits the whole MIR and generates `invalidates()` facts. /// Most of the code implementing this was stolen from `borrow_check/mod.rs`. impl<'cx, 'tcx> Visitor<'tcx> for InvalidationGenerator<'cx, 'tcx> { fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) { self.check_activations(location); match &statement.kind { StatementKind::Assign(box (lhs, rhs)) => { self.consume_rvalue(location, rhs); self.mutate_place(location, *lhs, Shallow(None)); } StatementKind::FakeRead(box (_, _)) => { // Only relevant for initialized/liveness/safety checks. } StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping { ref src, ref dst, ref count, }) => { self.consume_operand(location, src); self.consume_operand(location, dst); self.consume_operand(location, count); } StatementKind::Nop | StatementKind::Coverage(..) | StatementKind::AscribeUserType(..) | StatementKind::Retag { .. } | StatementKind::StorageLive(..) => { // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant // to borrow check. } StatementKind::StorageDead(local) => { self.access_place( location, Place::from(*local), (Shallow(None), Write(WriteKind::StorageDeadOrDrop)), LocalMutationIsAllowed::Yes, ); } StatementKind::Deinit(..) | StatementKind::SetDiscriminant { .. } => { bug!("Statement not allowed in this MIR phase") } } self.super_statement(statement, location); } fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) { self.check_activations(location); match &terminator.kind { TerminatorKind::SwitchInt { ref discr, switch_ty: _, targets: _ } => { self.consume_operand(location, discr); } TerminatorKind::Drop { place: drop_place, target: _, unwind: _ } => { self.access_place( location, *drop_place, (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)), LocalMutationIsAllowed::Yes, ); } TerminatorKind::DropAndReplace { place: drop_place, value: ref new_value, target: _, unwind: _, } => { self.mutate_place(location, *drop_place, Deep); self.consume_operand(location, new_value); } TerminatorKind::Call { ref func, ref args, destination, cleanup: _, from_hir_call: _, fn_span: _, } => { self.consume_operand(location, func); for arg in args { self.consume_operand(location, arg); } if let Some((dest, _ /*bb*/)) = destination { self.mutate_place(location, *dest, Deep); } } TerminatorKind::Assert { ref cond, expected: _, ref msg, target: _, cleanup: _ } => { self.consume_operand(location, cond); use rustc_middle::mir::AssertKind; if let AssertKind::BoundsCheck { ref len, ref index } = *msg { self.consume_operand(location, len); self.consume_operand(location, index); } } TerminatorKind::Yield { ref value, resume, resume_arg, drop: _ } => { self.consume_operand(location, value); // Invalidate all borrows of local places let borrow_set = self.borrow_set; let resume = self.location_table.start_index(resume.start_location()); for (i, data) in borrow_set.iter_enumerated() { if borrow_of_local_data(data.borrowed_place) { self.all_facts.loan_invalidated_at.push((resume, i)); } } self.mutate_place(location, *resume_arg, Deep); } TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => { // Invalidate all borrows of local places let borrow_set = self.borrow_set; let start = self.location_table.start_index(location); for (i, data) in borrow_set.iter_enumerated() { if borrow_of_local_data(data.borrowed_place) { self.all_facts.loan_invalidated_at.push((start, i)); } } } TerminatorKind::InlineAsm { template: _, ref operands, options: _, line_spans: _, destination: _, cleanup: _, } => { for op in operands { match *op { InlineAsmOperand::In { reg: _, ref value } => { self.consume_operand(location, value); } InlineAsmOperand::Out { reg: _, late: _, place, .. } => { if let Some(place) = place { self.mutate_place(location, place, Shallow(None)); } } InlineAsmOperand::InOut { reg: _, late: _, ref in_value, out_place } => { self.consume_operand(location, in_value); if let Some(out_place) = out_place { self.mutate_place(location, out_place, Shallow(None)); } } InlineAsmOperand::Const { value: _ } | InlineAsmOperand::SymFn { value: _ } | InlineAsmOperand::SymStatic { def_id: _ } => {} } } } TerminatorKind::Goto { target: _ } | TerminatorKind::Abort | TerminatorKind::Unreachable | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ } | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => { // no data used, thus irrelevant to borrowck } } self.super_terminator(terminator, location); } } impl<'cx, 'tcx> InvalidationGenerator<'cx, 'tcx> { /// Simulates mutation of a place. fn mutate_place(&mut self, location: Location, place: Place<'tcx>, kind: AccessDepth) { self.access_place( location, place, (kind, Write(WriteKind::Mutate)), LocalMutationIsAllowed::ExceptUpvars, ); } /// Simulates consumption of an operand. fn consume_operand(&mut self, location: Location, operand: &Operand<'tcx>) { match *operand { Operand::Copy(place) => { self.access_place( location, place, (Deep, Read(ReadKind::Copy)), LocalMutationIsAllowed::No, ); } Operand::Move(place) => { self.access_place( location, place, (Deep, Write(WriteKind::Move)), LocalMutationIsAllowed::Yes, ); } Operand::Constant(_) => {} } } // Simulates consumption of an rvalue fn consume_rvalue(&mut self, location: Location, rvalue: &Rvalue<'tcx>) { match *rvalue { Rvalue::Ref(_ /*rgn*/, bk, place) => { let access_kind = match bk { BorrowKind::Shallow => { (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk))) } BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))), BorrowKind::Unique | BorrowKind::Mut { .. } => { let wk = WriteKind::MutableBorrow(bk); if allow_two_phase_borrow(bk) { (Deep, Reservation(wk)) } else { (Deep, Write(wk)) } } }; self.access_place(location, place, access_kind, LocalMutationIsAllowed::No); } Rvalue::AddressOf(mutability, place) => { let access_kind = match mutability { Mutability::Mut => ( Deep, Write(WriteKind::MutableBorrow(BorrowKind::Mut { allow_two_phase_borrow: false, })), ), Mutability::Not => (Deep, Read(ReadKind::Borrow(BorrowKind::Shared))), }; self.access_place(location, place, access_kind, LocalMutationIsAllowed::No); } Rvalue::ThreadLocalRef(_) => {} Rvalue::Use(ref operand) | Rvalue::Repeat(ref operand, _) | Rvalue::UnaryOp(_ /*un_op*/, ref operand) | Rvalue::Cast(_ /*cast_kind*/, ref operand, _ /*ty*/) | Rvalue::ShallowInitBox(ref operand, _ /*ty*/) => { self.consume_operand(location, operand) } Rvalue::Len(place) | Rvalue::Discriminant(place) => { let af = match *rvalue { Rvalue::Len(..) => Some(ArtificialField::ArrayLength), Rvalue::Discriminant(..) => None, _ => unreachable!(), }; self.access_place( location, place, (Shallow(af), Read(ReadKind::Copy)), LocalMutationIsAllowed::No, ); } Rvalue::BinaryOp(_bin_op, box (ref operand1, ref operand2)) | Rvalue::CheckedBinaryOp(_bin_op, box (ref operand1, ref operand2)) => { self.consume_operand(location, operand1); self.consume_operand(location, operand2); } Rvalue::NullaryOp(_op, _ty) => {} Rvalue::Aggregate(_, ref operands) => { for operand in operands { self.consume_operand(location, operand); } } } } /// Simulates an access to a place. fn access_place( &mut self, location: Location, place: Place<'tcx>, kind: (AccessDepth, ReadOrWrite), _is_local_mutation_allowed: LocalMutationIsAllowed, ) { let (sd, rw) = kind; // note: not doing check_access_permissions checks because they don't generate invalidates self.check_access_for_conflict(location, place, sd, rw); } fn check_access_for_conflict( &mut self, location: Location, place: Place<'tcx>, sd: AccessDepth, rw: ReadOrWrite, ) { debug!( "invalidation::check_access_for_conflict(location={:?}, place={:?}, sd={:?}, \ rw={:?})", location, place, sd, rw, ); let tcx = self.tcx; let body = self.body; let borrow_set = self.borrow_set; let indices = self.borrow_set.indices(); each_borrow_involving_path( self, tcx, body, location, (sd, place), borrow_set, indices, |this, borrow_index, borrow| { match (rw, borrow.kind) { // Obviously an activation is compatible with its own // reservation (or even prior activating uses of same // borrow); so don't check if they interfere. // // NOTE: *reservations* do conflict with themselves; // thus aren't injecting unsoundness w/ this check.) (Activation(_, activating), _) if activating == borrow_index => { // Activating a borrow doesn't generate any invalidations, since we // have already taken the reservation } (Read(_), BorrowKind::Shallow | BorrowKind::Shared) | ( Read(ReadKind::Borrow(BorrowKind::Shallow)), BorrowKind::Unique | BorrowKind::Mut { .. }, ) => { // Reads don't invalidate shared or shallow borrows } (Read(_), BorrowKind::Unique | BorrowKind::Mut { .. }) => { // Reading from mere reservations of mutable-borrows is OK. if !is_active(&this.dominators, borrow, location) { // If the borrow isn't active yet, reads don't invalidate it assert!(allow_two_phase_borrow(borrow.kind)); return Control::Continue; } // Unique and mutable borrows are invalidated by reads from any // involved path this.emit_loan_invalidated_at(borrow_index, location); } (Reservation(_) | Activation(_, _) | Write(_), _) => { // unique or mutable borrows are invalidated by writes. // Reservations count as writes since we need to check // that activating the borrow will be OK // FIXME(bob_twinkles) is this actually the right thing to do? this.emit_loan_invalidated_at(borrow_index, location); } } Control::Continue }, ); } /// Generates a new `loan_invalidated_at(L, B)` fact. fn emit_loan_invalidated_at(&mut self, b: BorrowIndex, l: Location) { let lidx = self.location_table.start_index(l); self.all_facts.loan_invalidated_at.push((lidx, b)); } fn check_activations(&mut self, location: Location) { // Two-phase borrow support: For each activation that is newly // generated at this statement, check if it interferes with // another borrow. for &borrow_index in self.borrow_set.activations_at_location(location) { let borrow = &self.borrow_set[borrow_index]; // only mutable borrows should be 2-phase assert!(match borrow.kind { BorrowKind::Shared | BorrowKind::Shallow => false, BorrowKind::Unique | BorrowKind::Mut { .. } => true, }); self.access_place( location, borrow.borrowed_place, (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)), LocalMutationIsAllowed::No, ); // We do not need to call `check_if_path_or_subpath_is_moved` // again, as we already called it when we made the // initial reservation. } } }
39.586364
99
0.501148
562fff273bf893328a1937c8ad25b56b52b72cae
10,377
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::context::LowpanCtlContext; use anyhow::{format_err, Context as _, Error}; use argh::FromArgs; use fidl::endpoints::create_endpoints; use fidl_fuchsia_lowpan::ConnectivityState; use fidl_fuchsia_lowpan_device::{ DeviceExtraMarker, DeviceExtraProxy, DeviceMarker, DeviceProxy, Protocols, }; use fidl_fuchsia_lowpan_test::{DeviceTestMarker, DeviceTestProxy}; use std::fmt; #[derive(PartialEq, Debug, Eq)] enum StatusFormat { Standard, CSV, } impl fmt::Display for StatusFormat { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(self, f) } } impl std::str::FromStr for StatusFormat { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "Standard" | "standard" | "std" => Ok(StatusFormat::Standard), "CSV" | "csv" => Ok(StatusFormat::CSV), unknown => Err(format_err!("Unknown format {:?}", unknown)), } } } impl Default for StatusFormat { fn default() -> Self { StatusFormat::Standard } } /// Contains the arguments decoded for the `status` command. #[derive(FromArgs, PartialEq, Debug)] #[argh(subcommand, name = "status")] pub struct StatusCommand { #[argh( option, long = "format", description = "output format (std, csv)", default = "Default::default()" )] format: StatusFormat, } async fn print_device_status( name: &str, device: &DeviceProxy, device_extra: &DeviceExtraProxy, device_test: &DeviceTestProxy, ) -> Result<(), Error> { println!("{}", name); if let Some(net_types) = device.get_supported_network_types().await.ok() { for (i, net_type) in net_types.iter().enumerate() { if i == 0 { print!("\ttype: "); } else { print!(", "); } print!("{}", net_type); } if !net_types.is_empty() { println!(); } } let device_state = device.watch_device_state().await?; if let Some(x) = device_state.connectivity_state.as_ref() { println!("\tstate: {:?}", x); } let identity = device_extra.watch_identity().await?; if let Some(x) = identity.raw_name { match std::str::from_utf8(&x) { Ok(x) => println!("\tnetwork_name: {:?}", x), Err(e) => println!("\tnetwork_name: {} ({:?})", hex::encode(&x), e), } } if let Some(x) = identity.xpanid { println!("\txpanid: {}", hex::encode(x)); } if let Some(x) = identity.panid { println!("\tpanid: 0x{:04x}", x); } match device_state.connectivity_state { Some(ConnectivityState::Ready) | Some(ConnectivityState::Attaching) | Some(ConnectivityState::Attached) | Some(ConnectivityState::Isolated) => { if let Some(x) = device_state.role.as_ref() { println!("\trole: {:?}", x); } } _ => (), } let current_mac = device_test.get_current_mac_address().await.ok(); let factory_mac = device_test.get_factory_mac_address().await.ok(); if let Some(current_mac) = current_mac.as_ref() { println!("\tcurr-mac: {}", hex::encode(current_mac)); } if factory_mac.is_some() && factory_mac != current_mac { println!("\tfact-mac: {}", hex::encode(factory_mac.unwrap())); } if let Some(version) = device_test.get_ncp_version().await.ok() { println!("\tncp-version: {:?}", version); } if let Some(channel) = device_test.get_current_channel().await.ok() { println!("\tchan: {}", channel); } if let Some(rssi) = device_test.get_current_rssi().await.ok() { println!("\trssi: {}", rssi); } if let Some(x) = device_test.get_thread_rloc16().await.ok() { println!("\trloc16: 0x{:04x?}", x); } Ok(()) } async fn print_device_status_csv( name: &str, device: &DeviceProxy, device_extra: &DeviceExtraProxy, device_test: &DeviceTestProxy, ) -> Result<(), Error> { if let Some(net_types) = device.get_supported_network_types().await.ok() { for net_type in net_types.iter() { println!("{}, supported_type, {:?}", name, net_type); } } let device_state = device.watch_device_state().await?; if let Some(x) = device_state.connectivity_state.as_ref() { println!("{}, state, {:?}", name, x); } if let Some(x) = device_state.role.as_ref() { println!("{}, role, {:?}", name, x); } match device_state.connectivity_state { Some(ConnectivityState::Ready) | Some(ConnectivityState::Attaching) | Some(ConnectivityState::Attached) | Some(ConnectivityState::Isolated) => { let identity = device_extra.watch_identity().await?; if let Some(x) = identity.raw_name { println!("{}, net_raw_name, {}", name, hex::encode(&x)); match std::str::from_utf8(&x) { Ok(x) => println!("{}, net_name, {:?}", name, x), Err(e) => println!("{}, net_name_err, {:?}", name, e), } } if let Some(x) = identity.xpanid { println!("{}, net_xpanid, {:?}", name, x); } if let Some(x) = identity.channel { println!("{}, net_channel, {:?}", name, x); } if let Some(x) = identity.panid { println!("{}, net_panid, {:?}", name, x); } } _ => (), } let current_mac = device_test.get_current_mac_address().await.ok(); let factory_mac = device_test.get_factory_mac_address().await.ok(); if let Some(x) = current_mac.as_ref() { println!("{}, curr_mac, {}", name, hex::encode(x)); } if let Some(x) = factory_mac.as_ref() { println!("{}, fact_mac, {}", name, hex::encode(x)); } if let Some(x) = device_test.get_ncp_version().await.ok() { println!("{}, ncp_version, {:?}", name, x); } if let Some(x) = device_test.get_current_channel().await.ok() { println!("{}, channel, {:?}", name, x); } if let Some(x) = device_test.get_current_rssi().await.ok() { println!("{}, rssi, {:?}", name, x); } Ok(()) } impl StatusCommand { fn report_interface_error<E: ToString>(&self, name: &str, err: E) { match self.format { StatusFormat::Standard => { println!("{}", &name); println!("\terror: {:?}", err.to_string()); } StatusFormat::CSV => { println!("{}, error, {:?}", name, err.to_string()); } } } pub async fn exec(&self, context: &mut LowpanCtlContext) -> Result<(), Error> { let lookup = &context.lookup; let device_names: Vec<String> = lookup .get_devices() .await .map_err(std::convert::Into::<Error>::into) .context("Unable to list LoWPAN devices")?; if device_names.is_empty() { Err(format_err!("No LoWPAN interfaces present")) } else { if self.format == StatusFormat::CSV { println!("ifname, field, value"); } for name in device_names { let (client, server) = create_endpoints::<DeviceMarker>()?; let (client_extra, server_extra) = create_endpoints::<DeviceExtraMarker>()?; let (client_test, server_test) = create_endpoints::<DeviceTestMarker>()?; if let Some(e) = lookup .lookup_device( &name, Protocols { device: Some(server), device_extra: Some(server_extra), device_test: Some(server_test), ..Protocols::EMPTY }, ) .await .err() { self.report_interface_error(&name, e); } else { let device = client.into_proxy(); if device.is_err() { self.report_interface_error(&name, device.unwrap_err()); continue; } let device_extra = client_extra.into_proxy(); if device_extra.is_err() { self.report_interface_error(&name, device_extra.unwrap_err()); continue; } let device_diags = client_test.into_proxy(); if device_diags.is_err() { self.report_interface_error(&name, device_diags.unwrap_err()); continue; } match self.format { StatusFormat::Standard => { if let Some(e) = print_device_status( &name, &device.unwrap(), &device_extra.unwrap(), &device_diags.unwrap(), ) .await .err() { println!("\terror: {}", e); } } StatusFormat::CSV => { if let Some(e) = print_device_status_csv( &name, &device.unwrap(), &device_extra.unwrap(), &device_diags.unwrap(), ) .await .err() { self.report_interface_error(&name, e); } } } } println!(); } Ok(()) } } }
31.929231
92
0.490026
71873bdd9db5122255129d818220b07358b48359
5,966
//! This is a lightweight crate for verifying NUBAN numbers //! for all Nigerian bank accounts as was directed by the CBN. use std::{cell::Cell, collections::HashMap, fmt, sync::Once}; pub const BANKS: [(&'static str, &'static str); 24] = [ ("044", "Access Bank"), ("014", "Afribank"), ("023", "Citibank"), ("063", "Diamond Bank"), ("050", "Ecobank"), ("040", "Equitorial Trust Bank"), ("011", "First Bank"), ("214", "FCMB"), ("070", "Fidelity"), ("085", "FinBank"), ("058", "Guaranty Trust Bank"), ("069", "Intercontinentl Bank"), ("056", "Oceanic Bank"), ("082", "BankPhb"), ("076", "Skye Bank"), ("084", "SpringBank"), ("221", "StanbicIBTC"), ("068", "Standard Chartered Bank"), ("232", "Sterling Bank"), ("033", "United Bank For Africa"), ("032", "Union Bank"), ("035", "Wema Bank"), ("057", "Zenith Bank"), ("215", "Unity Bank"), ]; struct LazyBanks(Once, Cell<Option<HashMap<&'static str, &'static str>>>); unsafe impl Sync for LazyBanks {} static LAZY_BANKS: LazyBanks = LazyBanks(Once::new(), Cell::new(None)); #[derive(Eq, Clone, Debug, PartialEq)] pub struct Nuban<'a>(&'a str, &'a str, &'a str); #[derive(Eq, Copy, Clone, Debug, PartialEq)] pub enum Error { InvalidBankCode, InvalidAccountNumber, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let reason = match self { Error::InvalidBankCode => "invalid bank code", Error::InvalidAccountNumber => "invalid account number", }; write!(f, "{}", reason) } } impl<'a> Nuban<'a> { pub fn new(bank_code: &'a str, account_number: &'a str) -> Result<Self, Error> { #[rustfmt::skip] { if !Self::is_valid_bank(bank_code) { Err(Error::InvalidBankCode)? } if account_number.len() != 10 { Err(Error::InvalidAccountNumber)? } }; let (_, check_digit) = Self::account_number_parts(bank_code, account_number)?; Ok(Nuban(bank_code, account_number, check_digit)) } fn account_number_parts( bank_code: &'a str, account_number: &'a str, ) -> Result<(&'a str, &'a str), Error> { let (account_number, check_digit) = account_number.split_at(9); match ( check_digit.chars().next().unwrap().to_digit(10), Self::calculate_check_digit(bank_code, account_number), ) { (Some(l), r) if l != r => Err(Error::InvalidAccountNumber), _ => Ok((account_number, check_digit)), } } pub fn is_valid_bank(bank_code: &str) -> bool { bank_code.len() == 3 && Self::banks().contains_key(bank_code) } pub fn is_valid_account(bank_code: &str, account_number: &str) -> bool { Nuban::new(bank_code, account_number).is_err() } pub fn bank_code(&self) -> &str { self.0 } pub fn bank_name(&self) -> &str { Self::banks().get(self.0).unwrap() } pub fn account_number(&self) -> &str { self.1 } pub fn check_digit(&self) -> &str { self.2 } fn calculate_check_digit(bank_code: &'a str, account_number: &'a str) -> u32 { // The Approved NUBAN format: [ABC][DEFGHIJKL][M], where // - ABC : 3-digit Bank Code // - DEFGHIJKL : NUBAN Account Serial Number // - M : NUBAN Check Digit // https://www.cbn.gov.ng/OUT/2011/CIRCULARS/BSPD/NUBAN%20PROPOSALS%20V%200%204-%2003%2009%202010.PDF let nuban_chars = bank_code.chars().chain(account_number.chars()); let nuban_digits = nuban_chars.map(|num| num.to_digit(10).unwrap()); let seed = [3, 7, 3, 3, 7, 3, 3, 7, 3, 3, 7, 3].iter(); let check_sum: u32 = seed.zip(nuban_digits).map(|(l, r)| l * r).sum(); match 10 - (check_sum % 10) { 10 => 0, x => x, } } pub fn banks() -> &'static HashMap<&'static str, &'static str> { LAZY_BANKS .0 .call_once(|| LAZY_BANKS.1.set(Some(BANKS.iter().copied().collect()))); unsafe { if let Some(ref banks) = *LAZY_BANKS.1.as_ptr() { return banks; } unreachable!() } } pub fn bank_matches(account_number: &str) -> Result<impl Iterator<Item = (&str, &str)>, Error> { #[rustfmt::skip] if account_number.len() != 10 { Err(Error::InvalidAccountNumber)? }; Ok(BANKS .iter() .copied() .filter(move |(code, _)| Self::account_number_parts(code, account_number).is_ok())) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_returns_new_nuban_instance() { let account = Nuban::new("058", "0152792740"); assert_eq!(account.unwrap(), Nuban("058", "0152792740", "0")); } #[test] fn test_returns_false_for_invalid_account() { let account = Nuban::new("058", "0982736625"); assert!(account.is_err()); } #[test] fn test_returns_true_for_valid_account() { let account = Nuban::new("058", "0152792740"); assert!(account.is_ok()); } #[test] fn test_calculate_check_digit() { let correct_check_digit = Nuban::calculate_check_digit("058", "0152792740"); assert_eq!(correct_check_digit, 0); } #[test] fn test_get_bank_name() { let account = Nuban::new("058", "0152792740").unwrap(); assert_eq!(account.bank_name(), String::from("Guaranty Trust Bank")); } #[test] fn bank_matches() { let matches = Nuban::bank_matches("2209514399") .unwrap() .map(|(code, _)| code) .collect::<Vec<_>>(); let map = [ "068", // Standard Chartered Bank "035", // Wema Bank "057", // Zenith Bank ]; assert!(map.iter().all(|code| matches.contains(code))); } }
30.911917
109
0.556487
28254dd3ecb983308ffdb33291b5f89348e33043
2,262
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use crate::errors::Result; use crate::properties::DecodeProperties; use crate::range::Range; use crate::CFHandleExt; use std::ops::Deref; pub trait TablePropertiesExt: CFHandleExt { type TablePropertiesCollection: TablePropertiesCollection< Self::TablePropertiesCollectionIter, Self::TablePropertiesKey, Self::TableProperties, Self::UserCollectedProperties, >; type TablePropertiesCollectionIter: TablePropertiesCollectionIter< Self::TablePropertiesKey, Self::TableProperties, Self::UserCollectedProperties, >; type TablePropertiesKey: TablePropertiesKey; type TableProperties: TableProperties<Self::UserCollectedProperties>; type UserCollectedProperties: UserCollectedProperties; fn get_properties_of_tables_in_range( &self, cf: &Self::CFHandle, ranges: &[Range], ) -> Result<Self::TablePropertiesCollection>; fn get_range_properties_cf( &self, cfname: &str, start_key: &[u8], end_key: &[u8], ) -> Result<Self::TablePropertiesCollection> { let cf = self.cf_handle(cfname)?; let range = Range::new(start_key, end_key); Ok(self.get_properties_of_tables_in_range(cf, &[range])?) } } pub trait TablePropertiesCollection<I, PKey, P, UCP> where I: TablePropertiesCollectionIter<PKey, P, UCP>, PKey: TablePropertiesKey, P: TableProperties<UCP>, UCP: UserCollectedProperties, { fn iter(&self) -> I; fn len(&self) -> usize; fn is_empty(&self) -> bool { self.len() == 0 } } pub trait TablePropertiesCollectionIter<PKey, P, UCP>: Iterator<Item = (PKey, P)> where PKey: TablePropertiesKey, P: TableProperties<UCP>, UCP: UserCollectedProperties, { } pub trait TablePropertiesKey: Deref<Target = str> {} pub trait TableProperties<UCP> where UCP: UserCollectedProperties, { fn num_entries(&self) -> u64; fn user_collected_properties(&self) -> UCP; } pub trait UserCollectedProperties: DecodeProperties { fn get(&self, index: &[u8]) -> Option<&[u8]>; fn len(&self) -> usize; fn is_empty(&self) -> bool { self.len() == 0 } }
26
81
0.673298
d98e37bcf0cfa6d8a737b022b7095f6df6a8a63e
5,197
use std::{ fs::create_dir_all, panic::{catch_unwind, resume_unwind, AssertUnwindSafe}, path::{Path, PathBuf}, }; use serde::de::DeserializeOwned; use swc::{ config::{Config, IsModule, JscConfig, Options, SourceMapsConfig}, Compiler, }; use swc_ecma_ast::EsVersion; use swc_ecma_parser::{Syntax, TsConfig}; use testing::{NormalizedOutput, Tester}; #[testing::fixture( "../swc_ecma_parser/tests/tsc/**/*.ts", exclude( "privateNameFieldDestructuredBinding.ts", "restPropertyWithBindingPattern.ts", "elementAccessChain\\.3.ts", "propertyAccessChain\\.3.ts", "objectRestNegative.ts", "objectRestPropertyMustBeLast.ts", "privateNameAndAny.ts", "privateNameAndIndexSignature.ts", "privateNameImplicitDeclaration.ts", "privateNameStaticAccessorsDerivedClasses.ts", "privateNameErrorsOnNotUseDefineForClassFieldsInEsNext.ts", "enumConstantMembers.ts", "jsDeclarationsDocCommentsOnConsts.ts", "jsDeclarationsReexportedCjsAlias.ts", ) )] #[testing::fixture( "../swc_ecma_parser/tests/tsc/**/*.tsx", exclude("checkJsxNamespaceNamesQuestionableForms.tsx") )] fn fixture(input: PathBuf) { if input.to_string_lossy().contains("jsdoc") { return; } let panics = matrix() .into_iter() .filter_map(|(name, opts)| { // catch_unwind(AssertUnwindSafe(|| { let output_dir = Path::new("tests").join("tsc-references"); let _ = create_dir_all(&output_dir); let output_path = output_dir.join(format!( "{}_{}.js", input.file_stem().unwrap().to_str().unwrap(), name )); compile(&input, &output_path, opts); })) .err() }) .collect::<Vec<_>>(); if panics.is_empty() { return; } resume_unwind(panics.into_iter().next().unwrap()); } fn from_json<T>(s: &str) -> T where T: DeserializeOwned, { serde_json::from_str(s).unwrap() } fn matrix() -> Vec<(String, Options)> { // If we use `es5` as target, we can also verify es2015+ transforms. // But we test using es2015 to verify hygiene pass. let targets = vec![EsVersion::Es5, EsVersion::Es2015]; let mut res = vec![]; for target in targets { for minify in [true, false] { let opts = Options { config: Config { jsc: JscConfig { target: Some(target), minify: if minify { Some(from_json( "{ \"compress\": { \"toplevel\": true, \"module\": true, \ \"passes\": 0 }, \"mangle\": false, \"toplevel\": true }", )) } else { None }, ..Default::default() }, ..Default::default() }, ..Default::default() }; let s = serde_json::to_string(&target).unwrap().replace('"', ""); if minify { res.push((format!("{}.2.minified", s), opts)); } else { res.push((format!("{}.1.normal", s), opts)); } } } res } fn compile(input: &Path, output: &Path, opts: Options) { Tester::new() .print_errors(|cm, handler| { let c = Compiler::new(cm.clone()); let fm = cm.load_file(input).expect("failed to load file"); match c.process_js_file( fm, &handler, &Options { is_module: IsModule::Bool(true), config: Config { jsc: JscConfig { syntax: Some(Syntax::Typescript(TsConfig { tsx: input.to_string_lossy().ends_with(".tsx"), decorators: true, dts: false, no_early_errors: false, })), external_helpers: true.into(), ..opts.config.jsc }, source_maps: Some(SourceMapsConfig::Bool( !input.to_string_lossy().contains("Unicode"), )), ..opts.config }, ..opts }, ) { Ok(res) => { NormalizedOutput::from(res.code) .compare_to_file(output) .unwrap(); } Err(ref err) if format!("{:?}", err).contains("Syntax Error") => {} Err(ref err) if format!("{:?}", err).contains("not matched") => {} Err(err) => panic!("Error: {:?}", err), } Ok(()) }) .map(|_| ()) .expect("failed"); }
30.934524
91
0.460843
64220b633e2581c655f60dcc2d646633cb035ab2
1,829
use std::convert::Infallible; use std::error::Error as StdError; use std::fmt; type BoxError = Box<dyn std::error::Error + Send + Sync>; /// Errors that can happen inside warp. pub struct Error { inner: BoxError, } impl Error { pub(crate) fn new<E: Into<BoxError>>(err: E) -> Error { Error { inner: err.into() } } } impl fmt::Debug for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // Skip showing worthless `Error { .. }` wrapper. fmt::Debug::fmt(&self.inner, f) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.inner, f) } } impl StdError for Error { fn source(&self) -> Option<&(dyn StdError + 'static)> { Some(self.inner.as_ref()) } } impl From<Infallible> for Error { fn from(infallible: Infallible) -> Error { match infallible {} } } #[test] fn error_size_of() { assert_eq!( ::std::mem::size_of::<Error>(), ::std::mem::size_of::<usize>() * 2 ); } #[test] fn error_source() { let e = Error::new(std::fmt::Error {}); assert!(e.source().unwrap().is::<std::fmt::Error>()); } macro_rules! unit_error { ( $(#[$docs:meta])* $pub:vis $typ:ident: $display:literal ) => ( $(#[$docs])* $pub struct $typ { _p: (), } impl ::std::fmt::Debug for $typ { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { f.debug_struct(stringify!($typ)).finish() } } impl ::std::fmt::Display for $typ { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { f.write_str($display) } } impl ::std::error::Error for $typ {} ) }
22.8625
84
0.523783
1e4f9f98e3dc2ca7dfb4562f0cc0074d0e7346d2
30,909
use crate::{ paint::{text::cursor::*, *}, util::undoer::Undoer, *, }; #[derive(Clone, Debug, Default)] #[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "persistence", serde(default))] pub(crate) struct State { cursorp: Option<CursorPair>, #[cfg_attr(feature = "persistence", serde(skip))] undoer: Undoer<(CCursorPair, String)>, } #[derive(Clone, Copy, Debug, Default)] #[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))] struct CursorPair { /// When selecting with a mouse, this is where the mouse was released. /// When moving with e.g. shift+arrows, this is what moves. /// Note that the two ends can come in any order, and also be equal (no selection). pub primary: Cursor, /// When selecting with a mouse, this is where the mouse was first pressed. /// This part of the cursor does not move when shift is down. pub secondary: Cursor, } impl CursorPair { fn one(cursor: Cursor) -> Self { Self { primary: cursor, secondary: cursor, } } fn two(min: Cursor, max: Cursor) -> Self { Self { primary: max, secondary: min, } } fn as_ccursorp(&self) -> CCursorPair { CCursorPair { primary: self.primary.ccursor, secondary: self.secondary.ccursor, } } fn is_empty(&self) -> bool { self.primary.ccursor == self.secondary.ccursor } /// If there is a selection, None is returned. /// If the two ends is the same, that is returned. fn single(&self) -> Option<Cursor> { if self.is_empty() { Some(self.primary) } else { None } } fn primary_is_first(&self) -> bool { let p = self.primary.ccursor; let s = self.secondary.ccursor; (p.index, p.prefer_next_row) <= (s.index, s.prefer_next_row) } fn sorted(&self) -> [Cursor; 2] { if self.primary_is_first() { [self.primary, self.secondary] } else { [self.secondary, self.primary] } } } #[derive(Clone, Copy, Debug, Default, PartialEq)] #[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))] struct CCursorPair { /// When selecting with a mouse, this is where the mouse was released. /// When moving with e.g. shift+arrows, this is what moves. /// Note that the two ends can come in any order, and also be equal (no selection). pub primary: CCursor, /// When selecting with a mouse, this is where the mouse was first pressed. /// This part of the cursor does not move when shift is down. pub secondary: CCursor, } impl CCursorPair { fn one(ccursor: CCursor) -> Self { Self { primary: ccursor, secondary: ccursor, } } fn two(min: CCursor, max: CCursor) -> Self { Self { primary: max, secondary: min, } } } /// A text region that the user can edit the contents of. /// /// Example: /// /// ``` /// # let mut ui = egui::Ui::__test(); /// # let mut my_string = String::new(); /// let response = ui.add(egui::TextEdit::singleline(&mut my_string)); /// if response.lost_kb_focus { /// // use my_string /// } /// ``` #[derive(Debug)] pub struct TextEdit<'t> { text: &'t mut String, id: Option<Id>, id_source: Option<Id>, text_style: Option<TextStyle>, text_color: Option<Color32>, multiline: bool, enabled: bool, desired_width: Option<f32>, desired_height_rows: usize, } impl<'t> TextEdit<'t> { #[deprecated = "Use `TextEdit::singleline` or `TextEdit::multiline` (or the helper `ui.text_edit_singleline`, `ui.text_edit_multiline`) instead"] pub fn new(text: &'t mut String) -> Self { Self::multiline(text) } /// Now newlines (`\n`) allowed. Pressing enter key will result in the `TextEdit` loosing focus (`response.lost_kb_focus`). pub fn singleline(text: &'t mut String) -> Self { TextEdit { text, id: None, id_source: None, text_style: None, text_color: None, multiline: false, enabled: true, desired_width: None, desired_height_rows: 1, } } /// A `TextEdit` for multiple lines. Pressing enter key will create a new line. pub fn multiline(text: &'t mut String) -> Self { TextEdit { text, id: None, id_source: None, text_style: None, text_color: None, multiline: true, enabled: true, desired_width: None, desired_height_rows: 4, } } pub fn id(mut self, id: Id) -> Self { self.id = Some(id); self } /// A source for the unique `Id`, e.g. `.id_source("second_text_edit_field")` or `.id_source(loop_index)`. pub fn id_source(mut self, id_source: impl std::hash::Hash) -> Self { self.id_source = Some(Id::new(id_source)); self } pub fn text_style(mut self, text_style: TextStyle) -> Self { self.text_style = Some(text_style); self } pub fn text_color(mut self, text_color: Color32) -> Self { self.text_color = Some(text_color); self } pub fn text_color_opt(mut self, text_color: Option<Color32>) -> Self { self.text_color = text_color; self } /// Default is `true`. If set to `false` then you cannot edit the text. pub fn enabled(mut self, enabled: bool) -> Self { self.enabled = enabled; self } /// Set to 0.0 to keep as small as possible pub fn desired_width(mut self, desired_width: f32) -> Self { self.desired_width = Some(desired_width); self } /// Set the number of rows to show by default. /// The default for singleline text is `1`. /// The default for multiline text is `4`. pub fn desired_rows(mut self, desired_height_rows: usize) -> Self { self.desired_height_rows = desired_height_rows; self } } impl<'t> Widget for TextEdit<'t> { fn ui(self, ui: &mut Ui) -> Response { let margin = Vec2::splat(2.0); let frame_rect = ui.available_rect_before_wrap(); let content_rect = frame_rect.shrink2(margin); let where_to_put_background = ui.painter().add(Shape::Noop); let mut content_ui = ui.child_ui(content_rect, *ui.layout()); let response = self.content_ui(&mut content_ui); let frame_rect = Rect::from_min_max(frame_rect.min, content_ui.min_rect().max + margin); let response = response | ui.allocate_response(frame_rect.size(), Sense::click()); let visuals = ui.style().interact(&response); let frame_rect = response.rect; ui.painter().set( where_to_put_background, Shape::Rect { rect: frame_rect, corner_radius: visuals.corner_radius, fill: ui.style().visuals.dark_bg_color, stroke: visuals.bg_stroke, }, ); response } } impl<'t> TextEdit<'t> { fn content_ui(self, ui: &mut Ui) -> Response { let TextEdit { text, id, id_source, text_style, text_color, multiline, enabled, desired_width, desired_height_rows, } = self; let text_style = text_style.unwrap_or_else(|| ui.style().body_text_style); let font = &ui.fonts()[text_style]; let line_spacing = font.row_height(); let available_width = ui.available_width(); let mut galley = if multiline { font.layout_multiline(text.clone(), available_width) } else { font.layout_single_line(text.clone()) }; let desired_width = desired_width.unwrap_or_else(|| ui.style().spacing.text_edit_width); let desired_height = (desired_height_rows.at_least(1) as f32) * line_spacing; let desired_size = vec2( galley.size.x.max(desired_width.min(available_width)), galley.size.y.max(desired_height), ); let (auto_id, rect) = ui.allocate_space(desired_size); let id = id.unwrap_or_else(|| { if let Some(id_source) = id_source { ui.make_persistent_id(id_source) } else { auto_id // Since we are only storing the cursor a persistent Id is not super important } }); let mut state = ui.memory().text_edit.get(&id).cloned().unwrap_or_default(); let sense = if enabled { Sense::click_and_drag() } else { Sense::hover() }; let response = ui.interact(rect, id, sense); if enabled { ui.memory().interested_in_kb_focus(id); } if enabled { if let Some(mouse_pos) = ui.input().mouse.pos { // TODO: triple-click to select whole paragraph // TODO: drag selected text to either move or clone (ctrl on windows, alt on mac) let cursor_at_mouse = galley.cursor_from_pos(mouse_pos - response.rect.min); if response.hovered { // preview: paint_cursor_end(ui, response.rect.min, &galley, &cursor_at_mouse); } if response.hovered && response.double_clicked { // Select word: let center = cursor_at_mouse; let ccursorp = select_word_at(text, center.ccursor); state.cursorp = Some(CursorPair { primary: galley.from_ccursor(ccursorp.primary), secondary: galley.from_ccursor(ccursorp.secondary), }); } else if response.hovered && ui.input().mouse.pressed { ui.memory().request_kb_focus(id); if ui.input().modifiers.shift { if let Some(cursorp) = &mut state.cursorp { cursorp.primary = cursor_at_mouse; } else { state.cursorp = Some(CursorPair::one(cursor_at_mouse)); } } else { state.cursorp = Some(CursorPair::one(cursor_at_mouse)); } } else if ui.input().mouse.down && response.active { if let Some(cursorp) = &mut state.cursorp { cursorp.primary = cursor_at_mouse; } } } } if ui.input().mouse.pressed && !response.hovered { // User clicked somewhere else ui.memory().surrender_kb_focus(id); } if !enabled { ui.memory().surrender_kb_focus(id); } if response.hovered && enabled { ui.output().cursor_icon = CursorIcon::Text; } if ui.memory().has_kb_focus(id) && enabled { let mut cursorp = state .cursorp .map(|cursorp| { // We only keep the PCursor (paragraph number, and character offset within that paragraph). // This is so what if we resize the `TextEdit` region, and text wrapping changes, // we keep the same byte character offset from the beginning of the text, // even though the number of rows changes // (each paragraph can be several rows, due to word wrapping). // The column (character offset) should be able to extend beyond the last word so that we can // go down and still end up on the same column when we return. CursorPair { primary: galley.from_pcursor(cursorp.primary.pcursor), secondary: galley.from_pcursor(cursorp.secondary.pcursor), } }) .unwrap_or_else(|| CursorPair::one(galley.end())); // We feed state to the undoer both before and after handling input // so that the undoer creates automatic saves even when there are no events for a while. state .undoer .feed_state(ui.input().time, &(cursorp.as_ccursorp(), text.clone())); for event in &ui.input().events { let did_mutate_text = match event { Event::Copy => { if cursorp.is_empty() { ui.ctx().output().copied_text = text.clone(); } else { ui.ctx().output().copied_text = selected_str(text, &cursorp).to_owned(); } None } Event::Cut => { if cursorp.is_empty() { ui.ctx().output().copied_text = std::mem::take(text); Some(CCursorPair::default()) } else { ui.ctx().output().copied_text = selected_str(text, &cursorp).to_owned(); Some(CCursorPair::one(delete_selected(text, &cursorp))) } } Event::Text(text_to_insert) => { // Newlines are handled by `Key::Enter`. if !text_to_insert.is_empty() && text_to_insert != "\n" && text_to_insert != "\r" { let mut ccursor = delete_selected(text, &cursorp); insert_text(&mut ccursor, text, text_to_insert); Some(CCursorPair::one(ccursor)) } else { None } } Event::Key { key: Key::Enter, pressed: true, .. } => { if multiline { let mut ccursor = delete_selected(text, &cursorp); insert_text(&mut ccursor, text, "\n"); Some(CCursorPair::one(ccursor)) } else { // Common to end input with enter ui.memory().surrender_kb_focus(id); break; } } Event::Key { key: Key::Escape, pressed: true, .. } => { ui.memory().surrender_kb_focus(id); break; } Event::Key { key: Key::Z, pressed: true, modifiers, } if modifiers.command && !modifiers.shift => { // TODO: redo if let Some((undo_ccursorp, undo_txt)) = state.undoer.undo(&(cursorp.as_ccursorp(), text.clone())) { *text = undo_txt.clone(); Some(*undo_ccursorp) } else { None } } Event::Key { key, pressed: true, modifiers, } => on_key_press(&mut cursorp, text, &galley, *key, modifiers), Event::Key { .. } => None, }; if let Some(new_ccursorp) = did_mutate_text { // Layout again to avoid frame delay, and to keep `text` and `galley` in sync. let font = &ui.fonts()[text_style]; galley = if multiline { font.layout_multiline(text.clone(), available_width) } else { font.layout_single_line(text.clone()) }; // Set cursorp using new galley: cursorp = CursorPair { primary: galley.from_ccursor(new_ccursorp.primary), secondary: galley.from_ccursor(new_ccursorp.secondary), }; } } state.cursorp = Some(cursorp); state .undoer .feed_state(ui.input().time, &(cursorp.as_ccursorp(), text.clone())); } if ui.memory().has_kb_focus(id) { if let Some(cursorp) = state.cursorp { paint_cursor_selection(ui, response.rect.min, &galley, &cursorp); paint_cursor_end(ui, response.rect.min, &galley, &cursorp.primary); } } let text_color = text_color .or(ui.style().visuals.override_text_color) // .unwrap_or_else(|| ui.style().interact(&response).text_color()); // too bright .unwrap_or_else(|| ui.style().visuals.widgets.inactive.text_color()); ui.painter() .galley(response.rect.min, galley, text_style, text_color); ui.memory().text_edit.insert(id, state); Response { lost_kb_focus: ui.memory().lost_kb_focus(id), // we may have lost it during the course of this function ..response } } } // ---------------------------------------------------------------------------- fn paint_cursor_selection(ui: &mut Ui, pos: Pos2, galley: &Galley, cursorp: &CursorPair) { let color = ui.style().visuals.selection.bg_fill; if cursorp.is_empty() { return; } let [min, max] = cursorp.sorted(); let min = min.rcursor; let max = max.rcursor; for ri in min.row..=max.row { let row = &galley.rows[ri]; let left = if ri == min.row { row.x_offset(min.column) } else { row.min_x() }; let right = if ri == max.row { row.x_offset(max.column) } else { let newline_size = if row.ends_with_newline { row.height() / 2.0 // visualize that we select the newline } else { 0.0 }; row.max_x() + newline_size }; let rect = Rect::from_min_max(pos + vec2(left, row.y_min), pos + vec2(right, row.y_max)); ui.painter().rect_filled(rect, 0.0, color); } } fn paint_cursor_end(ui: &mut Ui, pos: Pos2, galley: &Galley, cursor: &Cursor) { let stroke = ui.style().visuals.selection.stroke; let cursor_pos = galley.pos_from_cursor(cursor).translate(pos.to_vec2()); let cursor_pos = cursor_pos.expand(1.5); // slightly above/below row let top = cursor_pos.center_top(); let bottom = cursor_pos.center_bottom(); ui.painter().line_segment( [top, bottom], (ui.style().visuals.text_cursor_width, stroke.color), ); if false { // Roof/floor: let extrusion = 3.0; let width = 1.0; ui.painter().line_segment( [top - vec2(extrusion, 0.0), top + vec2(extrusion, 0.0)], (width, stroke.color), ); ui.painter().line_segment( [bottom - vec2(extrusion, 0.0), bottom + vec2(extrusion, 0.0)], (width, stroke.color), ); } } // ---------------------------------------------------------------------------- fn selected_str<'s>(text: &'s str, cursorp: &CursorPair) -> &'s str { let [min, max] = cursorp.sorted(); let byte_begin = byte_index_from_char_index(text, min.ccursor.index); let byte_end = byte_index_from_char_index(text, max.ccursor.index); &text[byte_begin..byte_end] } fn byte_index_from_char_index(s: &str, char_index: usize) -> usize { for (ci, (bi, _)) in s.char_indices().enumerate() { if ci == char_index { return bi; } } s.len() } fn insert_text(ccursor: &mut CCursor, text: &mut String, text_to_insert: &str) { let mut char_it = text.chars(); let mut new_text = String::with_capacity(text.len() + text_to_insert.len()); for _ in 0..ccursor.index { let c = char_it.next().unwrap(); new_text.push(c); } ccursor.index += text_to_insert.chars().count(); new_text += text_to_insert; new_text.extend(char_it); *text = new_text; } // ---------------------------------------------------------------------------- fn delete_selected(text: &mut String, cursorp: &CursorPair) -> CCursor { let [min, max] = cursorp.sorted(); delete_selected_ccursor_range(text, [min.ccursor, max.ccursor]) } fn delete_selected_ccursor_range(text: &mut String, [min, max]: [CCursor; 2]) -> CCursor { let [min, max] = [min.index, max.index]; assert!(min <= max); if min < max { let mut char_it = text.chars(); let mut new_text = String::with_capacity(text.len()); for _ in 0..min { new_text.push(char_it.next().unwrap()) } new_text.extend(char_it.skip(max - min)); *text = new_text; } CCursor { index: min, prefer_next_row: true, } } fn delete_previous_char(text: &mut String, ccursor: CCursor) -> CCursor { if ccursor.index > 0 { let max_ccursor = ccursor; let min_ccursor = max_ccursor - 1; delete_selected_ccursor_range(text, [min_ccursor, max_ccursor]) } else { ccursor } } fn delete_next_char(text: &mut String, ccursor: CCursor) -> CCursor { delete_selected_ccursor_range(text, [ccursor, ccursor + 1]) } fn delete_previous_word(text: &mut String, max_ccursor: CCursor) -> CCursor { let min_ccursor = ccursor_previous_word(text, max_ccursor); delete_selected_ccursor_range(text, [min_ccursor, max_ccursor]) } fn delete_next_word(text: &mut String, min_ccursor: CCursor) -> CCursor { let max_ccursor = ccursor_next_word(text, min_ccursor); delete_selected_ccursor_range(text, [min_ccursor, max_ccursor]) } fn delete_paragraph_before_cursor( text: &mut String, galley: &Galley, cursorp: &CursorPair, ) -> CCursor { let [min, max] = cursorp.sorted(); let min = galley.from_pcursor(PCursor { paragraph: min.pcursor.paragraph, offset: 0, prefer_next_row: true, }); if min.ccursor == max.ccursor { delete_previous_char(text, min.ccursor) } else { delete_selected(text, &CursorPair::two(min, max)) } } fn delete_paragraph_after_cursor( text: &mut String, galley: &Galley, cursorp: &CursorPair, ) -> CCursor { let [min, max] = cursorp.sorted(); let max = galley.from_pcursor(PCursor { paragraph: max.pcursor.paragraph, offset: usize::MAX, // end of paragraph prefer_next_row: false, }); if min.ccursor == max.ccursor { delete_next_char(text, min.ccursor) } else { delete_selected(text, &CursorPair::two(min, max)) } } // ---------------------------------------------------------------------------- /// Returns `Some(new_cursor)` if we did mutate `text`. fn on_key_press( cursorp: &mut CursorPair, text: &mut String, galley: &Galley, key: Key, modifiers: &Modifiers, ) -> Option<CCursorPair> { match key { Key::Backspace => { let ccursor = if modifiers.mac_cmd { delete_paragraph_before_cursor(text, galley, cursorp) } else if let Some(cursor) = cursorp.single() { if modifiers.alt || modifiers.ctrl { // alt on mac, ctrl on windows delete_previous_word(text, cursor.ccursor) } else { delete_previous_char(text, cursor.ccursor) } } else { delete_selected(text, cursorp) }; Some(CCursorPair::one(ccursor)) } Key::Delete => { let ccursor = if modifiers.mac_cmd { delete_paragraph_after_cursor(text, galley, cursorp) } else if let Some(cursor) = cursorp.single() { if modifiers.alt || modifiers.ctrl { // alt on mac, ctrl on windows delete_next_word(text, cursor.ccursor) } else { delete_next_char(text, cursor.ccursor) } } else { delete_selected(text, cursorp) }; let ccursor = CCursor { prefer_next_row: true, ..ccursor }; Some(CCursorPair::one(ccursor)) } Key::A if modifiers.command => { // select all *cursorp = CursorPair::two(Cursor::default(), galley.end()); None } Key::K if modifiers.ctrl => { let ccursor = delete_paragraph_after_cursor(text, galley, cursorp); Some(CCursorPair::one(ccursor)) } Key::U if modifiers.ctrl => { let ccursor = delete_paragraph_before_cursor(text, galley, cursorp); Some(CCursorPair::one(ccursor)) } Key::W if modifiers.ctrl => { let ccursor = if let Some(cursor) = cursorp.single() { delete_previous_word(text, cursor.ccursor) } else { delete_selected(text, cursorp) }; Some(CCursorPair::one(ccursor)) } Key::ArrowLeft | Key::ArrowRight | Key::ArrowUp | Key::ArrowDown | Key::Home | Key::End => { move_single_cursor(&mut cursorp.primary, galley, key, modifiers); if !modifiers.shift { cursorp.secondary = cursorp.primary; } None } _ => None, } } fn move_single_cursor(cursor: &mut Cursor, galley: &Galley, key: Key, modifiers: &Modifiers) { match key { Key::ArrowLeft => { if modifiers.alt || modifiers.ctrl { // alt on mac, ctrl on windows *cursor = galley.from_ccursor(ccursor_previous_word(&galley.text, cursor.ccursor)); } else if modifiers.mac_cmd { *cursor = galley.cursor_begin_of_row(cursor); } else { *cursor = galley.cursor_left_one_character(cursor); } } Key::ArrowRight => { if modifiers.alt || modifiers.ctrl { // alt on mac, ctrl on windows *cursor = galley.from_ccursor(ccursor_next_word(&galley.text, cursor.ccursor)); } else if modifiers.mac_cmd { *cursor = galley.cursor_end_of_row(cursor); } else { *cursor = galley.cursor_right_one_character(cursor); } } Key::ArrowUp => { if modifiers.command { // mac and windows behavior *cursor = Cursor::default(); } else { *cursor = galley.cursor_up_one_row(cursor); } } Key::ArrowDown => { if modifiers.command { // mac and windows behavior *cursor = galley.end(); } else { *cursor = galley.cursor_down_one_row(cursor); } } Key::Home => { if modifiers.ctrl { // windows behavior *cursor = Cursor::default(); } else { *cursor = galley.cursor_begin_of_row(cursor); } } Key::End => { if modifiers.ctrl { // windows behavior *cursor = galley.end(); } else { *cursor = galley.cursor_end_of_row(cursor); } } _ => unreachable!(), } } // ---------------------------------------------------------------------------- fn select_word_at(text: &str, ccursor: CCursor) -> CCursorPair { if ccursor.index == 0 { CCursorPair::two(ccursor, ccursor_next_word(text, ccursor)) } else { let it = text.chars(); let mut it = it.skip(ccursor.index - 1); if let Some(char_before_cursor) = it.next() { if let Some(char_after_cursor) = it.next() { if is_word_char(char_before_cursor) && is_word_char(char_after_cursor) { let min = ccursor_previous_word(text, ccursor + 1); let max = ccursor_next_word(text, min); CCursorPair::two(min, max) } else if is_word_char(char_before_cursor) { let min = ccursor_previous_word(text, ccursor); let max = ccursor_next_word(text, min); CCursorPair::two(min, max) } else if is_word_char(char_after_cursor) { let max = ccursor_next_word(text, ccursor); CCursorPair::two(ccursor, max) } else { let min = ccursor_previous_word(text, ccursor); let max = ccursor_next_word(text, ccursor); CCursorPair::two(min, max) } } else { let min = ccursor_previous_word(text, ccursor); CCursorPair::two(min, ccursor) } } else { let max = ccursor_next_word(text, ccursor); CCursorPair::two(ccursor, max) } } } fn ccursor_next_word(text: &str, ccursor: CCursor) -> CCursor { CCursor { index: next_word_boundary_char_index(text.chars(), ccursor.index), prefer_next_row: false, } } fn ccursor_previous_word(text: &str, ccursor: CCursor) -> CCursor { let num_chars = text.chars().count(); CCursor { index: num_chars - next_word_boundary_char_index(text.chars().rev(), num_chars - ccursor.index), prefer_next_row: true, } } fn next_word_boundary_char_index(it: impl Iterator<Item = char>, mut index: usize) -> usize { let mut it = it.skip(index); if let Some(_first) = it.next() { index += 1; if let Some(second) = it.next() { index += 1; for next in it { if is_word_char(next) != is_word_char(second) { break; } index += 1; } } } index } fn is_word_char(c: char) -> bool { c.is_ascii_alphanumeric() || c == '_' }
34.535196
149
0.518393
efae4fc9ca226e2bdd4042a0fe472b12060a8d0e
43,297
//! This module provides translations of unary and binary operator expressions. use super::*; fn neg_expr(arg: P<Expr>) -> P<Expr> { mk().unary_expr(ast::UnOp::Neg, arg) } fn wrapping_neg_expr(arg: P<Expr>) -> P<Expr> { mk().method_call_expr(arg, "wrapping_neg", vec![] as Vec<P<Expr>>) } impl From<c_ast::BinOp> for BinOpKind { fn from(op: c_ast::BinOp) -> Self { match op { c_ast::BinOp::Multiply => BinOpKind::Mul, c_ast::BinOp::Divide => BinOpKind::Div, c_ast::BinOp::Modulus => BinOpKind::Rem, c_ast::BinOp::Add => BinOpKind::Add, c_ast::BinOp::Subtract => BinOpKind::Sub, c_ast::BinOp::ShiftLeft => BinOpKind::Shl, c_ast::BinOp::ShiftRight => BinOpKind::Shr, c_ast::BinOp::Less => BinOpKind::Lt, c_ast::BinOp::Greater => BinOpKind::Gt, c_ast::BinOp::LessEqual => BinOpKind::Le, c_ast::BinOp::GreaterEqual => BinOpKind::Ge, c_ast::BinOp::EqualEqual => BinOpKind::Eq, c_ast::BinOp::NotEqual => BinOpKind::Ne, c_ast::BinOp::BitAnd => BinOpKind::BitAnd, c_ast::BinOp::BitXor => BinOpKind::BitXor, c_ast::BinOp::BitOr => BinOpKind::BitOr, c_ast::BinOp::And => BinOpKind::And, c_ast::BinOp::Or => BinOpKind::Or, _ => panic!("C BinOp {:?} is not a valid Rust BinOpKind"), } } } impl<'c> Translation<'c> { pub fn convert_binary_expr( &self, mut ctx: ExprContext, type_id: CQualTypeId, op: c_ast::BinOp, lhs: CExprId, rhs: CExprId, opt_lhs_type_id: Option<CQualTypeId>, opt_res_type_id: Option<CQualTypeId>, ) -> Result<WithStmts<P<Expr>>, TranslationError> { // If we're not making an assignment, a binop will require parens // applied to ternary conditionals if !op.is_assignment() { ctx.ternary_needs_parens = true; } let lhs_loc = &self.ast_context[lhs].loc; let rhs_loc = &self.ast_context[rhs].loc; match op { c_ast::BinOp::Comma => { // The value of the LHS of a comma expression is always discarded self.convert_expr(ctx.unused(), lhs)? .and_then(|_| self.convert_expr(ctx, rhs)) } c_ast::BinOp::And | c_ast::BinOp::Or => { let lhs = self.convert_condition(ctx, true, lhs)?; let rhs = self.convert_condition(ctx, true, rhs)?; lhs .map(|x| bool_to_int(mk().binary_expr(BinOpKind::from(op), x, rhs.to_expr()))) .and_then(|out| { if ctx.is_unused() { Ok(WithStmts::new( vec![mk().semi_stmt(out)], self.panic_or_err("Binary expression is not supposed to be used"), )) } else { Ok(WithStmts::new_val(out)) } }) } // No sequence-point cases c_ast::BinOp::AssignAdd | c_ast::BinOp::AssignSubtract | c_ast::BinOp::AssignMultiply | c_ast::BinOp::AssignDivide | c_ast::BinOp::AssignModulus | c_ast::BinOp::AssignBitXor | c_ast::BinOp::AssignShiftLeft | c_ast::BinOp::AssignShiftRight | c_ast::BinOp::AssignBitOr | c_ast::BinOp::AssignBitAnd | c_ast::BinOp::Assign => self.convert_assignment_operator( ctx, op, type_id, lhs, rhs, opt_lhs_type_id, opt_res_type_id, ), _ => { // Comparing references to pointers isn't consistently supported by rust // and so we need to decay references to pointers to do so. See // https://github.com/rust-lang/rust/issues/53772. This might be removable // once the above issue is resolved. if op == c_ast::BinOp::EqualEqual || op == c_ast::BinOp::NotEqual { ctx = ctx.decay_ref(); } let ty = self.convert_type(type_id.ctype)?; let lhs_type_id = self .ast_context .index(lhs) .kind .get_qual_type() .ok_or_else(|| { format_translation_err!(self.ast_context.display_loc(lhs_loc), "bad lhs type for assignment") })?; let rhs_kind = &self .ast_context .index(rhs) .kind; let rhs_type_id = rhs_kind .get_qual_type() .ok_or_else(|| { format_translation_err!(self.ast_context.display_loc(rhs_loc), "bad rhs type for assignment") })?; if ctx.is_unused() { Ok(self.convert_expr(ctx, lhs)? .and_then(|_| self.convert_expr(ctx, rhs))? .map(|_| self.panic_or_err("Binary expression is not supposed to be used"))) } else { let rhs_ctx = ctx; // When we use methods on pointers (ie wrapping_offset_from or offset) // we must ensure we have an explicit raw ptr for the self param, as // self references do not decay if op == c_ast::BinOp::Subtract || op == c_ast::BinOp::Add { let ty_kind = &self.ast_context.resolve_type(lhs_type_id.ctype).kind; if let CTypeKind::Pointer(_) = ty_kind { ctx = ctx.decay_ref(); } } self.convert_expr(ctx, lhs)?.and_then(|lhs_val| { self.convert_expr(rhs_ctx, rhs)?.result_map(|rhs_val| { let expr_ids = Some((lhs, rhs)); self.convert_binary_operator( ctx, op, ty, type_id.ctype, lhs_type_id, rhs_type_id, lhs_val, rhs_val, expr_ids, ) }) }) } } } } fn convert_assignment_operator_aux( &self, ctx: ExprContext, bin_op_kind: BinOpKind, bin_op: c_ast::BinOp, read: P<Expr>, write: P<Expr>, rhs: P<Expr>, compute_lhs_ty: Option<CQualTypeId>, compute_res_ty: Option<CQualTypeId>, lhs_ty: CQualTypeId, rhs_ty: CQualTypeId, ) -> Result<WithStmts<P<Expr>>, TranslationError> { let compute_lhs_ty = compute_lhs_ty.unwrap(); let compute_res_ty = compute_res_ty.unwrap(); if self.ast_context.resolve_type_id(compute_lhs_ty.ctype) == self.ast_context.resolve_type_id(lhs_ty.ctype) { Ok(WithStmts::new_val(mk().assign_op_expr(bin_op_kind, write, rhs))) } else { let resolved_computed_kind = &self.ast_context.resolve_type(compute_lhs_ty.ctype).kind; let lhs_type = self.convert_type(compute_lhs_ty.ctype)?; // We can't simply as-cast into a non primitive like f128 let lhs = if *resolved_computed_kind == CTypeKind::LongDouble { self.extern_crates.borrow_mut().insert("f128"); let fn_path = mk().path_expr(vec!["f128", "f128", "from"]); let args = vec![read]; mk().call_expr(fn_path, args) } else { mk().cast_expr(read, lhs_type.clone()) }; let ty = self.convert_type(compute_res_ty.ctype)?; let val = self.convert_binary_operator( ctx, bin_op, ty, compute_res_ty.ctype, compute_lhs_ty, rhs_ty, lhs, rhs, None, )?; let is_enum_result = self.ast_context[self.ast_context.resolve_type_id(lhs_ty.ctype)] .kind .is_enum(); let result_type = self.convert_type(lhs_ty.ctype)?; let val = if is_enum_result { if ctx.is_const { self.use_feature("const_transmute"); } WithStmts::new_unsafe_val(transmute_expr(lhs_type, result_type, val, self.tcfg.emit_no_std)) } else { // We can't as-cast from a non primitive like f128 back to the result_type if *resolved_computed_kind == CTypeKind::LongDouble { let resolved_lhs_kind = &self.ast_context.resolve_type(lhs_ty.ctype).kind; let val = WithStmts::new_val(val); self.f128_cast_to(val, resolved_lhs_kind)? } else { WithStmts::new_val(mk().cast_expr(val, result_type)) } }; Ok(val.map(|val| mk().assign_expr(write.clone(), val))) } } fn convert_assignment_operator( &self, ctx: ExprContext, op: c_ast::BinOp, qtype: CQualTypeId, lhs: CExprId, rhs: CExprId, compute_type: Option<CQualTypeId>, result_type: Option<CQualTypeId>, ) -> Result<WithStmts<P<Expr>>, TranslationError> { let rhs_type_id = self .ast_context .index(rhs) .kind .get_qual_type() .ok_or_else(|| format_err!("bad assignment rhs type"))?; let rhs_translation = self.convert_expr(ctx.used(), rhs)?; self.convert_assignment_operator_with_rhs( ctx, op, qtype, lhs, rhs_type_id, rhs_translation, compute_type, result_type, ) } /// Translate an assignment binary operator fn convert_assignment_operator_with_rhs( &self, ctx: ExprContext, op: c_ast::BinOp, qtype: CQualTypeId, lhs: CExprId, rhs_type_id: CQualTypeId, rhs_translation: WithStmts<P<Expr>>, compute_type: Option<CQualTypeId>, result_type: Option<CQualTypeId>, ) -> Result<WithStmts<P<Expr>>, TranslationError> { let ty = self.convert_type(qtype.ctype)?; let result_type_id = result_type.unwrap_or(qtype); let compute_lhs_type_id = compute_type.unwrap_or(qtype); let initial_lhs = &self.ast_context.index(lhs).kind; let initial_lhs_type_id = initial_lhs .get_qual_type() .ok_or_else(|| format_err!("bad initial lhs type"))?; let bitfield_id = match initial_lhs { CExprKind::Member(_, _, decl_id, _, _) => { let kind = &self.ast_context[*decl_id].kind; if let CDeclKind::Field { bitfield_width: Some(_), .. } = kind { Some(decl_id) } else { None } } _ => None, }; if let Some(field_id) = bitfield_id { let rhs_expr = if compute_lhs_type_id.ctype == initial_lhs_type_id.ctype { rhs_translation.to_expr() } else { mk().cast_expr(rhs_translation.to_expr(), ty) }; return self.convert_bitfield_assignment_op_with_rhs(ctx, op, lhs, rhs_expr, *field_id); } let is_volatile = initial_lhs_type_id.qualifiers.is_volatile; let is_volatile_compound_assign = op.underlying_assignment().is_some() && is_volatile; let qtype_kind = &self.ast_context.resolve_type(qtype.ctype).kind; let compute_type_kind = &self .ast_context .resolve_type(compute_lhs_type_id.ctype) .kind; let pointer_lhs = match qtype_kind { &CTypeKind::Pointer(pointee) => Some(pointee), _ => None, }; let is_unsigned_arith = match op { c_ast::BinOp::AssignAdd | c_ast::BinOp::AssignSubtract | c_ast::BinOp::AssignMultiply | c_ast::BinOp::AssignDivide | c_ast::BinOp::AssignModulus => compute_type_kind.is_unsigned_integral_type(), _ => false, }; let lhs_translation = if initial_lhs_type_id.ctype != compute_lhs_type_id.ctype || ctx.is_used() || pointer_lhs.is_some() || is_volatile_compound_assign || is_unsigned_arith { self.name_reference_write_read(ctx, lhs)? } else { self.name_reference_write(ctx, lhs)? .map(|write| ( write, self.panic_or_err("Volatile value is not supposed to be read"), )) }; rhs_translation.and_then(|rhs| { lhs_translation.and_then(|(write, read)| { // Assignment expression itself let assign_stmt = match op { // Regular (possibly volatile) assignment c_ast::BinOp::Assign if !is_volatile => { WithStmts::new_val(mk().assign_expr(&write, rhs)) } c_ast::BinOp::Assign => { WithStmts::new_val(self.volatile_write(&write, initial_lhs_type_id, rhs)?) } // Anything volatile needs to be desugared into explicit reads and writes op if is_volatile || is_unsigned_arith => { let mut is_unsafe = false; let op = op .underlying_assignment() .expect("Cannot convert non-assignment operator"); let val = if compute_lhs_type_id.ctype == initial_lhs_type_id.ctype { self.convert_binary_operator( ctx, op, ty, qtype.ctype, initial_lhs_type_id, rhs_type_id, read.clone(), rhs, None, )? } else { let lhs_type = self.convert_type(compute_type.unwrap().ctype)?; let write_type = self.convert_type(qtype.ctype)?; let lhs = mk().cast_expr(read.clone(), lhs_type.clone()); let ty = self.convert_type(result_type_id.ctype)?; let val = self.convert_binary_operator( ctx, op, ty, result_type_id.ctype, compute_lhs_type_id, rhs_type_id, lhs, rhs, None, )?; let is_enum_result = self.ast_context [self.ast_context.resolve_type_id(qtype.ctype)] .kind .is_enum(); let result_type = self.convert_type(qtype.ctype)?; let val = if is_enum_result { is_unsafe = true; if ctx.is_const { self.use_feature("const_transmute"); } transmute_expr(lhs_type, result_type, val, self.tcfg.emit_no_std) } else { mk().cast_expr(val, result_type) }; mk().cast_expr(val, write_type) }; let write = if is_volatile { self.volatile_write(&write, initial_lhs_type_id, val)? } else { mk().assign_expr(write, val) }; if is_unsafe { WithStmts::new_unsafe_val(write) } else { WithStmts::new_val(write) } } // Everything else c_ast::BinOp::AssignAdd if pointer_lhs.is_some() => { let mul = self.compute_size_of_expr(pointer_lhs.unwrap().ctype); let ptr = pointer_offset(write.clone(), rhs, mul, false, false); WithStmts::new_val(mk().assign_expr(&write, ptr)) } c_ast::BinOp::AssignSubtract if pointer_lhs.is_some() => { let mul = self.compute_size_of_expr(pointer_lhs.unwrap().ctype); let ptr = pointer_offset(write.clone(), rhs, mul, true, false); WithStmts::new_val(mk().assign_expr(&write, ptr)) } c_ast::BinOp::AssignAdd => self.convert_assignment_operator_aux( ctx, BinOpKind::Add, c_ast::BinOp::Add, read.clone(), write, rhs, compute_type, result_type, qtype, rhs_type_id, )?, c_ast::BinOp::AssignSubtract => self.convert_assignment_operator_aux( ctx, BinOpKind::Sub, c_ast::BinOp::Subtract, read.clone(), write, rhs, compute_type, result_type, qtype, rhs_type_id, )?, c_ast::BinOp::AssignMultiply => self.convert_assignment_operator_aux( ctx, BinOpKind::Mul, c_ast::BinOp::Multiply, read.clone(), write, rhs, compute_type, result_type, qtype, rhs_type_id, )?, c_ast::BinOp::AssignDivide => self.convert_assignment_operator_aux( ctx, BinOpKind::Div, c_ast::BinOp::Divide, read.clone(), write, rhs, compute_type, result_type, qtype, rhs_type_id, )?, c_ast::BinOp::AssignModulus => self.convert_assignment_operator_aux( ctx, BinOpKind::Rem, c_ast::BinOp::Modulus, read.clone(), write, rhs, compute_type, result_type, qtype, rhs_type_id, )?, c_ast::BinOp::AssignBitXor => self.convert_assignment_operator_aux( ctx, BinOpKind::BitXor, c_ast::BinOp::BitXor, read.clone(), write, rhs, compute_type, result_type, qtype, rhs_type_id, )?, c_ast::BinOp::AssignShiftLeft => self.convert_assignment_operator_aux( ctx, BinOpKind::Shl, c_ast::BinOp::ShiftLeft, read.clone(), write, rhs, compute_type, result_type, qtype, rhs_type_id, )?, c_ast::BinOp::AssignShiftRight => self.convert_assignment_operator_aux( ctx, BinOpKind::Shr, c_ast::BinOp::ShiftRight, read.clone(), write, rhs, compute_type, result_type, qtype, rhs_type_id, )?, c_ast::BinOp::AssignBitOr => self.convert_assignment_operator_aux( ctx, BinOpKind::BitOr, c_ast::BinOp::BitOr, read.clone(), write, rhs, compute_type, result_type, qtype, rhs_type_id, )?, c_ast::BinOp::AssignBitAnd => self.convert_assignment_operator_aux( ctx, BinOpKind::BitAnd, c_ast::BinOp::BitAnd, read.clone(), write, rhs, compute_type, result_type, qtype, rhs_type_id, )?, _ => panic!("Cannot convert non-assignment operator"), }; assign_stmt.and_then(|assign_stmt| { Ok(WithStmts::new( vec![mk().expr_stmt(assign_stmt)], read, )) }) }) }) } /// Translate a non-assignment binary operator. It is expected that the `lhs` and `rhs` /// arguments be usable as rvalues. fn convert_binary_operator( &self, ctx: ExprContext, op: c_ast::BinOp, ty: P<Ty>, ctype: CTypeId, lhs_type: CQualTypeId, rhs_type: CQualTypeId, lhs: P<Expr>, rhs: P<Expr>, lhs_rhs_ids: Option<(CExprId, CExprId)>, ) -> Result<P<Expr>, TranslationError> { let is_unsigned_integral_type = self .ast_context .index(ctype) .kind .is_unsigned_integral_type(); match op { c_ast::BinOp::Add => self.convert_addition(ctx, lhs_type, rhs_type, lhs, rhs), c_ast::BinOp::Subtract => self.convert_subtraction(ctx, ty, lhs_type, rhs_type, lhs, rhs), c_ast::BinOp::Multiply if is_unsigned_integral_type => { if ctx.is_const { return Err(TranslationError::generic( "Cannot use wrapping multiply in a const expression", )); } Ok(mk().method_call_expr(lhs, mk().path_segment("wrapping_mul"), vec![rhs])) } c_ast::BinOp::Multiply => Ok(mk().binary_expr(BinOpKind::Mul, lhs, rhs)), c_ast::BinOp::Divide if is_unsigned_integral_type => { if ctx.is_const { return Err(TranslationError::generic( "Cannot use wrapping division in a const expression", )); } Ok(mk().method_call_expr(lhs, mk().path_segment("wrapping_div"), vec![rhs])) } c_ast::BinOp::Divide => Ok(mk().binary_expr(BinOpKind::Div, lhs, rhs)), c_ast::BinOp::Modulus if is_unsigned_integral_type => { if ctx.is_const { return Err(TranslationError::generic( "Cannot use wrapping remainder in a const expression", )); } Ok(mk().method_call_expr(lhs, mk().path_segment("wrapping_rem"), vec![rhs])) } c_ast::BinOp::Modulus => Ok(mk().binary_expr(BinOpKind::Rem, lhs, rhs)), c_ast::BinOp::BitXor => Ok(mk().binary_expr(BinOpKind::BitXor, lhs, rhs)), c_ast::BinOp::ShiftRight => Ok(mk().binary_expr(BinOpKind::Shr, lhs, rhs)), c_ast::BinOp::ShiftLeft => Ok(mk().binary_expr(BinOpKind::Shl, lhs, rhs)), c_ast::BinOp::EqualEqual => { // Using is_none method for null comparison means we don't have to // rely on the PartialEq trait as much and is also more idiomatic let expr = if let Some((lhs_expr_id, rhs_expr_id)) = lhs_rhs_ids { let fn_eq_null = self.ast_context.is_function_pointer(lhs_type.ctype) && self.ast_context.is_null_expr(rhs_expr_id); let null_eq_fn = self.ast_context.is_function_pointer(rhs_type.ctype) && self.ast_context.is_null_expr(lhs_expr_id); if fn_eq_null { mk().method_call_expr(lhs, "is_none", vec![] as Vec<P<Expr>>) } else if null_eq_fn { mk().method_call_expr(rhs, "is_none", vec![] as Vec<P<Expr>>) } else { mk().binary_expr(BinOpKind::Eq, lhs, rhs) } } else { mk().binary_expr(BinOpKind::Eq, lhs, rhs) }; Ok(bool_to_int(expr)) } c_ast::BinOp::NotEqual => { // Using is_some method for null comparison means we don't have to // rely on the PartialEq trait as much and is also more idiomatic let expr = if let Some((lhs_expr_id, rhs_expr_id)) = lhs_rhs_ids { let fn_eq_null = self.ast_context.is_function_pointer(lhs_type.ctype) && self.ast_context.is_null_expr(rhs_expr_id); let null_eq_fn = self.ast_context.is_function_pointer(rhs_type.ctype) && self.ast_context.is_null_expr(lhs_expr_id); if fn_eq_null { mk().method_call_expr(lhs, "is_some", vec![] as Vec<P<Expr>>) } else if null_eq_fn { mk().method_call_expr(rhs, "is_some", vec![] as Vec<P<Expr>>) } else { mk().binary_expr(BinOpKind::Ne, lhs, rhs) } } else { mk().binary_expr(BinOpKind::Ne, lhs, rhs) }; Ok(bool_to_int(expr)) } c_ast::BinOp::Less => Ok(bool_to_int(mk().binary_expr(BinOpKind::Lt, lhs, rhs))), c_ast::BinOp::Greater => Ok(bool_to_int(mk().binary_expr(BinOpKind::Gt, lhs, rhs))), c_ast::BinOp::GreaterEqual => Ok(bool_to_int(mk().binary_expr(BinOpKind::Ge, lhs, rhs))), c_ast::BinOp::LessEqual => Ok(bool_to_int(mk().binary_expr(BinOpKind::Le, lhs, rhs))), c_ast::BinOp::BitAnd => Ok(mk().binary_expr(BinOpKind::BitAnd, lhs, rhs)), c_ast::BinOp::BitOr => Ok(mk().binary_expr(BinOpKind::BitOr, lhs, rhs)), op => unimplemented!("Translation of binary operator {:?}", op), } } fn convert_addition( &self, ctx: ExprContext, lhs_type_id: CQualTypeId, rhs_type_id: CQualTypeId, lhs: P<Expr>, rhs: P<Expr>, ) -> Result<P<Expr>, TranslationError> { let lhs_type = &self.ast_context.resolve_type(lhs_type_id.ctype).kind; let rhs_type = &self.ast_context.resolve_type(rhs_type_id.ctype).kind; if let &CTypeKind::Pointer(pointee) = lhs_type { let mul = self.compute_size_of_expr(pointee.ctype); Ok(pointer_offset(lhs, rhs, mul, false, false)) } else if let &CTypeKind::Pointer(pointee) = rhs_type { let mul = self.compute_size_of_expr(pointee.ctype); Ok(pointer_offset(rhs, lhs, mul, false, false)) } else if lhs_type.is_unsigned_integral_type() { if ctx.is_const { return Err(TranslationError::generic( "Cannot use wrapping add in a const expression", )); } Ok(mk().method_call_expr(lhs, mk().path_segment("wrapping_add"), vec![rhs])) } else { Ok(mk().binary_expr(BinOpKind::Add, lhs, rhs)) } } fn convert_subtraction( &self, ctx: ExprContext, ty: P<Ty>, lhs_type_id: CQualTypeId, rhs_type_id: CQualTypeId, lhs: P<Expr>, rhs: P<Expr>, ) -> Result<P<Expr>, TranslationError> { let lhs_type = &self.ast_context.resolve_type(lhs_type_id.ctype).kind; let rhs_type = &self.ast_context.resolve_type(rhs_type_id.ctype).kind; if let &CTypeKind::Pointer(pointee) = rhs_type { if ctx.is_const { return Err(TranslationError::generic( "Cannot use wrapping offset from in a const expression", )); } // The wrapping_offset_from method is locked behind a feature gate // and replaces the now deprecated offset_to (opposite argument order) // wrapping_offset_from panics when the pointee is a ZST self.use_feature("ptr_wrapping_offset_from"); let mut offset = mk().method_call_expr(lhs, "wrapping_offset_from", vec![rhs]); if let Some(sz) = self.compute_size_of_expr(pointee.ctype) { let div = cast_int(sz, "isize", false); offset = mk().binary_expr(BinOpKind::Div, offset, div); } Ok(mk().cast_expr(offset, ty)) } else if let &CTypeKind::Pointer(pointee) = lhs_type { let mul = self.compute_size_of_expr(pointee.ctype); Ok(pointer_offset(lhs, rhs, mul, true, false)) } else if lhs_type.is_unsigned_integral_type() { if ctx.is_const { return Err(TranslationError::generic( "Cannot use wrapping subtract in a const expression", )); } Ok(mk().method_call_expr(lhs, mk().path_segment("wrapping_sub"), vec![rhs])) } else { Ok(mk().binary_expr(BinOpKind::Sub, lhs, rhs)) } } fn convert_pre_increment( &self, ctx: ExprContext, ty: CQualTypeId, up: bool, arg: CExprId, ) -> Result<WithStmts<P<Expr>>, TranslationError> { let op = if up { c_ast::BinOp::AssignAdd } else { c_ast::BinOp::AssignSubtract }; let one = match self.ast_context.resolve_type(ty.ctype).kind { // TODO: If rust gets f16 support: // CTypeKind::Half | CTypeKind::Float | CTypeKind::Double => mk().lit_expr(mk().float_unsuffixed_lit("1.")), CTypeKind::LongDouble => { self.extern_crates.borrow_mut().insert("f128"); let fn_path = mk().path_expr(vec!["f128", "f128", "new"]); let args = vec![mk().ident_expr("1.")]; mk().call_expr(fn_path, args) } _ => mk().lit_expr(mk().int_lit(1, LitIntType::Unsuffixed)), }; let arg_type = self.ast_context[arg] .kind .get_qual_type() .ok_or_else(|| format_err!("bad arg type"))?; self.convert_assignment_operator_with_rhs( ctx.used(), op, arg_type, arg, ty, WithStmts::new_val(one), Some(arg_type), Some(arg_type), ) } fn convert_post_increment( &self, ctx: ExprContext, ty: CQualTypeId, up: bool, arg: CExprId, ) -> Result<WithStmts<P<Expr>>, TranslationError> { // If we aren't going to be using the result, may as well do a simple pre-increment if ctx.is_unused() { return self.convert_pre_increment(ctx, ty, up, arg); } let ty = self .ast_context .index(arg) .kind .get_qual_type() .ok_or_else(|| format_err!("bad post inc type"))?; self.name_reference_write_read(ctx, arg)? .and_then(|(write, read)| { let val_name = self.renamer.borrow_mut().fresh(); let save_old_val = mk().local_stmt(P(mk().local( mk().ident_pat(&val_name), None as Option<P<Ty>>, Some(read.clone()), ))); let mut one = match self.ast_context[ty.ctype].kind { // TODO: If rust gets f16 support: // CTypeKind::Half | CTypeKind::Float | CTypeKind::Double => mk().lit_expr(mk().float_unsuffixed_lit("1.")), CTypeKind::LongDouble => { self.extern_crates.borrow_mut().insert("f128"); let fn_path = mk().path_expr(vec!["f128", "f128", "new"]); let args = vec![mk().ident_expr("1.")]; mk().call_expr(fn_path, args) } _ => mk().lit_expr(mk().int_lit(1, LitIntType::Unsuffixed)), }; // *p + 1 let val = if let &CTypeKind::Pointer(pointee) = &self.ast_context.resolve_type(ty.ctype).kind { if let Some(n) = self.compute_size_of_expr(pointee.ctype) { one = n } let n = if up { one } else { mk().unary_expr(ast::UnOp::Neg, one) }; mk().method_call_expr(read.clone(), "offset", vec![n]) } else { if self .ast_context .resolve_type(ty.ctype) .kind .is_unsigned_integral_type() { if ctx.is_const { return Err(TranslationError::generic( "Cannot use wrapping add or sub in a const expression", )); } let m = if up { "wrapping_add" } else { "wrapping_sub" }; mk().method_call_expr(read.clone(), m, vec![one]) } else { let k = if up { BinOpKind::Add } else { BinOpKind::Sub }; mk().binary_expr(k, read.clone(), one) } }; // *p = *p + rhs let assign_stmt = if ty.qualifiers.is_volatile { self.volatile_write(&write, ty, val)? } else { mk().assign_expr(&write, val) }; Ok(WithStmts::new( vec![save_old_val, mk().expr_stmt(assign_stmt)], mk().ident_expr(val_name), )) }) } pub fn convert_unary_operator( &self, mut ctx: ExprContext, name: c_ast::UnOp, cqual_type: CQualTypeId, arg: CExprId, lrvalue: LRValue, ) -> Result<WithStmts<P<Expr>>, TranslationError> { let CQualTypeId { ctype, .. } = cqual_type; let ty = self.convert_type(ctype)?; let resolved_ctype = self.ast_context.resolve_type(ctype); match name { c_ast::UnOp::AddressOf => { let arg_kind = &self.ast_context[arg].kind; match arg_kind { // C99 6.5.3.2 para 4 CExprKind::Unary(_, c_ast::UnOp::Deref, target, _) => { return self.convert_expr(ctx, *target) } // An AddrOf DeclRef/Member is safe to not decay if the translator isn't already giving a hard // yes to decaying (ie, BitCasts). So we only convert default to no decay. CExprKind::DeclRef(..) | CExprKind::Member(..) => { ctx.decay_ref.set_default_to_no() } _ => (), }; // In this translation, there are only pointers to functions and // & becomes a no-op when applied to a function. let arg = self.convert_expr(ctx.used().set_needs_address(true), arg)?; if self.ast_context.is_function_pointer(ctype) { Ok(arg.map(|x| mk().call_expr(mk().ident_expr("Some"), vec![x]))) } else { let pointee_ty = self.ast_context.get_pointee_qual_type(ctype) .ok_or_else(|| TranslationError::generic( "Address-of should return a pointer", ))?; let mutbl = if pointee_ty.qualifiers.is_const { Mutability::Immutable } else { Mutability::Mutable }; arg.result_map(|a| { let mut addr_of_arg: P<Expr>; if ctx.is_static { // static variable initializers aren't able to use &mut, // so we work around that by using & and an extra cast // through & to *const to *mut addr_of_arg = mk().addr_of_expr(a); if mutbl == Mutability::Mutable { let mut qtype = pointee_ty; qtype.qualifiers.is_const = true; let ty_ = self .type_converter .borrow_mut() .convert_pointer(&self.ast_context, qtype)?; addr_of_arg = mk().cast_expr(addr_of_arg, ty_); } } else { // Normal case is allowed to use &mut if needed addr_of_arg = mk().set_mutbl(mutbl).addr_of_expr(a); // Avoid unnecessary reference to pointer decay in fn call args: if ctx.decay_ref.is_no() { return Ok(addr_of_arg); } } Ok(mk().cast_expr(addr_of_arg, ty)) }) } } c_ast::UnOp::PreIncrement => self.convert_pre_increment(ctx, cqual_type, true, arg), c_ast::UnOp::PreDecrement => self.convert_pre_increment(ctx, cqual_type, false, arg), c_ast::UnOp::PostIncrement => self.convert_post_increment(ctx, cqual_type, true, arg), c_ast::UnOp::PostDecrement => self.convert_post_increment(ctx, cqual_type, false, arg), c_ast::UnOp::Deref => { match self.ast_context[arg].kind { CExprKind::Unary(_, c_ast::UnOp::AddressOf, arg_, _) => { self.convert_expr(ctx.used(), arg_) } _ => { self.convert_expr(ctx.used(), arg)? .result_map(|val: P<Expr>| { if let CTypeKind::Function(..) = self.ast_context.resolve_type(ctype).kind { Ok(unwrap_function_pointer(val)) } else if let Some(_vla) = self.compute_size_of_expr(ctype) { Ok(val) } else { let mut val = mk().unary_expr(ast::UnOp::Deref, val); // If the type on the other side of the pointer we are dereferencing is volatile and // this whole expression is not an LValue, we should make this a volatile read if lrvalue.is_rvalue() && cqual_type.qualifiers.is_volatile { val = self.volatile_read(&val, cqual_type)? } Ok(val) } }) } } } c_ast::UnOp::Plus => self.convert_expr(ctx.used(), arg), // promotion is explicit in the clang AST c_ast::UnOp::Negate => { let val = self.convert_expr(ctx.used(), arg)?; if resolved_ctype.kind.is_unsigned_integral_type() { if ctx.is_const { return Err(TranslationError::generic( "Cannot use wrapping negate in a const expression", )); } Ok(val.map(wrapping_neg_expr)) } else { Ok(val.map(neg_expr)) } } c_ast::UnOp::Complement => Ok(self .convert_expr(ctx.used(), arg)? .map(|a| mk().unary_expr(ast::UnOp::Not, a))), c_ast::UnOp::Not => { let val = self.convert_condition(ctx, false, arg)?; Ok(val.map(|x| mk().cast_expr(x, mk().path_ty(vec!["libc", "c_int"])))) } c_ast::UnOp::Extension => { let arg = self.convert_expr(ctx, arg)?; Ok(arg) } c_ast::UnOp::Real | c_ast::UnOp::Imag | c_ast::UnOp::Coawait => { panic!("Unsupported extension operator") } } } }
41.392925
120
0.457584
2897c8ac0001e021ad2de73f51779264010dff17
8,155
use crate::finder::structures::{Opts as FinderOpts, SuggestionType}; use crate::hash::fnv; use crate::structures::cheat::VariableMap; use crate::structures::item::Item; use crate::writer::{self, Writer}; use anyhow::{Context, Error}; use regex::Regex; use std::collections::HashSet; use std::io::Write; lazy_static! { pub static ref VAR_LINE_REGEX: Regex = Regex::new(r"^\$\s*([^:]+):(.*)").expect("Invalid regex"); } fn parse_opts(text: &str) -> Result<FinderOpts, Error> { let mut multi = false; let mut prevent_extra = false; let mut opts = FinderOpts::default(); let parts = shellwords::split(text).map_err(|_| anyhow!("Given options are missing a closing quote"))?; parts .into_iter() .filter(|part| { // We'll take parts in pairs of 2: (argument, value). Flags don't have a value tho, so we filter and handle them beforehand. match part.as_str() { "--multi" => { multi = true; false } "--prevent-extra" => { prevent_extra = true; false } _ => true, } }) .collect::<Vec<_>>() .chunks(2) .try_for_each(|flag_and_value| { if let [flag, value] = flag_and_value { match flag.as_str() { "--headers" | "--header-lines" => { opts.header_lines = value .parse::<u8>() .context("Value for `--headers` is invalid u8")? } "--column" => { opts.column = Some( value .parse::<u8>() .context("Value for `--column` is invalid u8")?, ) } "--map" => opts.map = Some(value.to_string()), "--delimiter" => opts.delimiter = Some(value.to_string()), "--query" => opts.query = Some(value.to_string()), "--filter" => opts.filter = Some(value.to_string()), "--preview" => opts.preview = Some(value.to_string()), "--preview-window" => opts.preview_window = Some(value.to_string()), "--header" => opts.header = Some(value.to_string()), "--overrides" => opts.overrides = Some(value.to_string()), _ => (), } Ok(()) } else if let [flag] = flag_and_value { Err(anyhow!("No value provided for the flag `{}`", flag)) } else { unreachable!() // Chunking by 2 allows only for tuples of 1 or 2 items... } }) .context("Failed to parse finder options")?; let suggestion_type = match (multi, prevent_extra) { (true, _) => SuggestionType::MultipleSelections, // multi wins over prevent-extra (false, false) => SuggestionType::SingleRecommendation, (false, true) => SuggestionType::SingleSelection, }; opts.suggestion_type = suggestion_type; Ok(opts) } fn parse_variable_line(line: &str) -> Result<(&str, &str, Option<FinderOpts>), Error> { let caps = VAR_LINE_REGEX .captures(line) .ok_or_else(|| anyhow!("No variables, command, and options found in the line `{}`", line))?; let variable = caps .get(1) .ok_or_else(|| anyhow!("No variable captured in the line `{}`", line))? .as_str() .trim(); let mut command_plus_opts = caps .get(2) .ok_or_else(|| anyhow!("No command and options captured in the line `{}`", line))? .as_str() .split("---"); let command = command_plus_opts .next() .ok_or_else(|| anyhow!("No command captured in the line `{}`", line))?; let command_options = command_plus_opts.next().map(parse_opts).transpose()?; Ok((variable, command, command_options)) } fn write_cmd( tags: &str, comment: &str, snippet: &str, file_index: &usize, writer: &mut dyn Writer, stdin: &mut std::process::ChildStdin, ) -> Result<(), Error> { if snippet.len() <= 1 { Ok(()) } else { let item = Item { tags: &tags, comment: &comment, snippet: &snippet, file_index: &file_index, }; stdin .write_all(writer.write(item).as_bytes()) .context("Failed to write command to finder's stdin") } } fn without_prefix(line: &str) -> String { if line.len() > 2 { String::from(line[2..].trim()) } else { String::from("") } } pub fn read_lines( lines: impl Iterator<Item = Result<String, Error>>, id: &str, file_index: usize, variables: &mut VariableMap, visited_lines: &mut HashSet<u64>, writer: &mut dyn Writer, stdin: &mut std::process::ChildStdin, ) -> Result<(), Error> { let mut tags = String::from(""); let mut comment = String::from(""); let mut snippet = String::from(""); let mut should_break = false; for (line_nr, line_result) in lines.enumerate() { let line = line_result .with_context(|| format!("Failed to read line number {} in cheatsheet `{}`", line_nr, id))?; if should_break { break; } // duplicate if !tags.is_empty() && !comment.is_empty() {} // blank if line.is_empty() { } // tag else if line.starts_with('%') { should_break = write_cmd(&tags, &comment, &snippet, &file_index, writer, stdin).is_err(); snippet = String::from(""); tags = without_prefix(&line); } // dependency else if line.starts_with('@') { let tags_dependency = without_prefix(&line); variables.insert_dependency(&tags, &tags_dependency); } // metacomment else if line.starts_with(';') { } // comment else if line.starts_with('#') { should_break = write_cmd(&tags, &comment, &snippet, &file_index, writer, stdin).is_err(); snippet = String::from(""); comment = without_prefix(&line); } // variable else if line.starts_with('$') { should_break = write_cmd(&tags, &comment, &snippet, &file_index, writer, stdin).is_err(); snippet = String::from(""); let (variable, command, opts) = parse_variable_line(&line).with_context(|| { format!( "Failed to parse variable line. See line number {} in cheatsheet `{}`", line_nr + 1, id ) })?; variables.insert_suggestion(&tags, &variable, (String::from(command), opts)); } // snippet else { let hash = fnv(&format!("{}{}", &comment, &line)); if visited_lines.contains(&hash) { continue; } visited_lines.insert(hash); if !(&snippet).is_empty() { snippet.push_str(writer::LINE_SEPARATOR); } snippet.push_str(&line); } } if !should_break { let _ = write_cmd(&tags, &comment, &snippet, &file_index, writer, stdin); } Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_variable_line() { let (variable, command, command_options) = parse_variable_line("$ user : echo -e \"$(whoami)\\nroot\" --- --prevent-extra").unwrap(); assert_eq!(command, " echo -e \"$(whoami)\\nroot\" "); assert_eq!(variable, "user"); assert_eq!( command_options, Some(FinderOpts { header_lines: 0, column: None, delimiter: None, suggestion_type: SuggestionType::SingleSelection, ..Default::default() }) ); } }
33.979167
136
0.507909
bf6d8ebec5095ef675d8c5384eee86ce708318d3
8,630
use std::marker::PhantomData; use crate::drgraph::Graph; use crate::hasher::Hasher; use crate::layered_drgporep::Layers; use crate::parameter_cache::ParameterSetIdentifier; use crate::zigzag_graph::{ZigZag, ZigZagBucketGraph}; /// ZigZagDrgPorep is a layered PoRep which replicates layer by layer. /// Between layers, the graph is 'reversed' in such a way that the dependencies expand with each iteration. /// This reversal is not a straightforward inversion -- so we coin the term 'zigzag' to describe the transformation. /// Each graph can be divided into base and expansion components. /// The 'base' component is an ordinary DRG. The expansion component attempts to add a target (expansion_degree) number of connections /// between nodes in a reversible way. Expansion connections are therefore simply inverted at each layer. /// Because of how DRG-sampled parents are calculated on demand, the base components are not. Instead, a same-degree /// DRG with connections in the opposite direction (and using the same random seed) is used when calculating parents on demand. /// For the algorithm to have the desired properties, it is important that the expansion components are directly inverted at each layer. /// However, it is fortunately not necessary that the base DRG components also have this property. #[derive(Debug)] pub struct ZigZagDrgPoRep<'a, H: 'a + Hasher> { _a: PhantomData<&'a H>, } impl<'a, H: 'static + Hasher> Layers for ZigZagDrgPoRep<'a, H> where { type Hasher = <ZigZagBucketGraph<H> as ZigZag>::BaseHasher; type Graph = ZigZagBucketGraph<Self::Hasher>; fn transform(graph: &Self::Graph) -> Self::Graph { zigzag::<Self::Hasher, Self::Graph>(graph) } fn invert_transform(graph: &Self::Graph) -> Self::Graph { zigzag::<Self::Hasher, Self::Graph>(graph) } } fn zigzag<H, Z>(graph: &Z) -> Z where H: Hasher, Z: ZigZag + Graph<H> + ParameterSetIdentifier, { graph.zigzag() } #[cfg(test)] mod tests { use super::*; use paired::bls12_381::Bls12; use rand::{Rng, SeedableRng, XorShiftRng}; use crate::drgporep; use crate::drgraph::new_seed; use crate::fr32::fr_into_bytes; use crate::hasher::{Blake2sHasher, PedersenHasher, Sha256Hasher}; use crate::layered_drgporep::{ LayerChallenges, PrivateInputs, PublicInputs, PublicParams, SetupParams, }; use crate::porep::PoRep; use crate::proof::ProofScheme; const DEFAULT_ZIGZAG_LAYERS: usize = 10; #[test] fn extract_all_pedersen() { test_extract_all::<PedersenHasher>(); } #[test] fn extract_all_sha256() { test_extract_all::<Sha256Hasher>(); } #[test] fn extract_all_blake2s() { test_extract_all::<Blake2sHasher>(); } fn test_extract_all<H: 'static + Hasher>() { let rng = &mut XorShiftRng::from_seed([0x3dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); let sloth_iter = 1; let replica_id: H::Domain = rng.gen(); let data = vec![2u8; 32 * 3]; let challenges = LayerChallenges::new_fixed(DEFAULT_ZIGZAG_LAYERS, 5); // create a copy, so we can compare roundtrips let mut data_copy = data.clone(); let sp = SetupParams { drg: drgporep::DrgParams { nodes: data.len() / 32, degree: 5, expansion_degree: 8, seed: new_seed(), }, sloth_iter, layer_challenges: challenges.clone(), }; let mut pp = ZigZagDrgPoRep::<H>::setup(&sp).expect("setup failed"); // Get the graph for the last layer. // In reality, this is a no-op with an even number of layers. for _ in 0..pp.layer_challenges.layers() { pp.graph = zigzag(&pp.graph); } ZigZagDrgPoRep::<H>::replicate(&pp, &replica_id, data_copy.as_mut_slice(), None) .expect("replication failed"); let transformed_params = PublicParams::new(pp.graph, pp.sloth_iter, challenges.clone()); assert_ne!(data, data_copy); let decoded_data = ZigZagDrgPoRep::<H>::extract_all( &transformed_params, &replica_id, data_copy.as_mut_slice(), ) .expect("failed to extract data"); assert_eq!(data, decoded_data); } fn prove_verify_fixed(n: usize, i: usize) { let challenges = LayerChallenges::new_fixed(DEFAULT_ZIGZAG_LAYERS, 5); test_prove_verify::<PedersenHasher>(n, i, challenges.clone()); test_prove_verify::<Sha256Hasher>(n, i, challenges.clone()); test_prove_verify::<Blake2sHasher>(n, i, challenges.clone()); } fn prove_verify_tapered(n: usize, i: usize) { let challenges = LayerChallenges::new_tapered(5, 10, 5, 0.9); test_prove_verify::<PedersenHasher>(n, i, challenges.clone()); test_prove_verify::<Sha256Hasher>(n, i, challenges.clone()); test_prove_verify::<Blake2sHasher>(n, i, challenges.clone()); } fn test_prove_verify<H: 'static + Hasher>(n: usize, i: usize, challenges: LayerChallenges) { let rng = &mut XorShiftRng::from_seed([0x3dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); let degree = 1 + i; let expansion_degree = i; let sloth_iter = 1; let replica_id: H::Domain = rng.gen(); let data: Vec<u8> = (0..n) .flat_map(|_| fr_into_bytes::<Bls12>(&rng.gen())) .collect(); // create a copy, so we can compare roundtrips let mut data_copy = data.clone(); let partitions = 2; let sp = SetupParams { drg: drgporep::DrgParams { nodes: n, degree, expansion_degree, seed: new_seed(), }, sloth_iter, layer_challenges: challenges.clone(), }; let pp = ZigZagDrgPoRep::<H>::setup(&sp).expect("setup failed"); let (tau, aux) = ZigZagDrgPoRep::<H>::replicate(&pp, &replica_id, data_copy.as_mut_slice(), None) .expect("replication failed"); assert_ne!(data, data_copy); let pub_inputs = PublicInputs::<H::Domain> { replica_id, tau: Some(tau.simplify().into()), comm_r_star: tau.comm_r_star, k: None, }; let priv_inputs = PrivateInputs { aux, tau: tau.layer_taus, }; let all_partition_proofs = &ZigZagDrgPoRep::<H>::prove_all_partitions(&pp, &pub_inputs, &priv_inputs, partitions) .expect("failed to generate partition proofs"); let proofs_are_valid = ZigZagDrgPoRep::<H>::verify_all_partitions(&pp, &pub_inputs, all_partition_proofs) .expect("failed to verify partition proofs"); assert!(proofs_are_valid); } table_tests! { prove_verify_fixed{ // TODO: figure out why this was failing // prove_verify_32_2_1(32, 2, 1); // prove_verify_32_2_2(32, 2, 2); // TODO: why u fail??? // prove_verify_32_3_1(32, 3, 1); // prove_verify_32_3_2(32, 3, 2); prove_verify_fixed_32_5_1(5, 1); prove_verify_fixed_32_5_2(5, 2); prove_verify_fixed_32_5_3(5, 3); } } table_tests! { prove_verify_tapered{ prove_verify_tapered_32_5_1(5, 1); prove_verify_tapered_32_5_2(5, 2); prove_verify_tapered_32_5_3(5, 3); } } #[test] // We are seeing a bug, in which setup never terminates for some sector sizes. // This test is to debug that and should remain as a regression teset. fn setup_terminates() { let degree = 5; let expansion_degree = 8; let nodes = 1024 * 1024 * 32 * 8; // This corresponds to 8GiB sectors (32-byte nodes) let sloth_iter = 0; let layer_challenges = LayerChallenges::new_tapered(10, 333, 7, 0.3); let sp = SetupParams { drg: drgporep::DrgParams { nodes, degree, expansion_degree, seed: new_seed(), }, sloth_iter, layer_challenges: layer_challenges.clone(), }; // When this fails, the call to setup should panic, but seems to actually hang (i.e. neither return nor panic) for some reason. // When working as designed, the call to setup returns without error. let _pp = ZigZagDrgPoRep::<PedersenHasher>::setup(&sp).expect("setup failed"); } }
35.514403
136
0.613441
69a230e2572d087c69664f8b20456656ba9e14ac
2,986
use std::ops::Range; use lasso::Spur; use crate::{source_file::SourceLocation, FileId}; #[derive(Debug, Copy, Clone, PartialEq)] pub enum TokenKind { // Single-character tokens LeftParen, RightParen, LeftBrace, RightBrace, Comma, Dot, Minus, Plus, Percent, SemiColon, Slash, Star, // One- or two-character tokens Bang, BangEqual, Equal, EqualEqual, Greater, GreaterEqual, Less, LessEqual, Identifier, // Literals StringLiteral(Spur), NumberLiteral(f64), BooleanLiteral(bool), NilLiteral, // Keywords And, Class, Else, Fun, For, If, Or, Print, Return, Super, This, Var, While, Eof, } // Saves having a bunch of borrows in the parser. Looks dumb. impl PartialEq<TokenKind> for &'_ TokenKind { #[inline(always)] fn eq(&self, other: &TokenKind) -> bool { **self == *other } } impl TokenKind { #[inline(always)] pub fn is_literal(self) -> bool { use TokenKind::*; matches!( self, StringLiteral(_) | NumberLiteral(_) | BooleanLiteral(_) | NilLiteral ) } #[inline(always)] pub fn is_binary(self) -> bool { use TokenKind::*; matches!( self, Minus | Plus | Star | Slash | Percent | BangEqual | Equal | EqualEqual | Greater | GreaterEqual | Less | LessEqual ) } #[inline(always)] pub fn is_logical(self) -> bool { use TokenKind::*; matches!(self, And | Or) } #[inline(always)] pub fn is_unary(self) -> bool { use TokenKind::*; matches!(self, Bang | Minus) } #[inline(always)] pub fn is_statement_start(self) -> bool { use TokenKind::*; matches!(self, Class | Fun | Var | For | If | While | Print | Return) } #[inline(always)] pub fn is_keyword(self) -> bool { use TokenKind::*; matches!( self, And | Class | Else | Fun | For | If | Or | Print | Return | Super | This | Var | While ) } } #[derive(Debug, Copy, Clone, PartialEq)] pub struct Token { pub kind: TokenKind, pub lexeme: Spur, pub location: SourceLocation, } impl Token { #[inline(always)] pub fn make_ident(lexeme: Spur, source_id: FileId, range: Range<usize>) -> Self { Self { kind: TokenKind::Identifier, lexeme, location: SourceLocation { file_id: source_id, source_start: range.start, len: range.end - range.start, }, } } } impl Token { #[inline(always)] pub fn source_range(self) -> Range<usize> { self.location.range() } }
19.38961
98
0.508372
5debbddbdc57bfece511afc95d4f417b4868070e
23,552
// 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. use crate::handler::{IdentifyHandler, IdentifyHandlerEvent, IdentifyPush}; use crate::protocol::{IdentifyInfo, ReplySubstream}; use futures::prelude::*; use libp2p_core::{ ConnectedPoint, Multiaddr, PeerId, PublicKey, connection::{ConnectionId, ListenerId}, upgrade::UpgradeError }; use libp2p_swarm::{ AddressScore, DialPeerCondition, NegotiatedSubstream, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, ProtocolsHandler, ProtocolsHandlerUpgrErr }; use std::{ collections::{HashSet, HashMap, VecDeque}, io, pin::Pin, task::Context, task::Poll, time::Duration, }; /// Network behaviour that automatically identifies nodes periodically, returns information /// about them, and answers identify queries from other nodes. /// /// All external addresses of the local node supposedly observed by remotes /// are reported via [`NetworkBehaviourAction::ReportObservedAddr`] with a /// [score](AddressScore) of `1`. pub struct Identify { config: IdentifyConfig, /// For each peer we're connected to, the observed address to send back to it. connected: HashMap<PeerId, HashMap<ConnectionId, Multiaddr>>, /// Pending replies to send. pending_replies: VecDeque<Reply>, /// Pending events to be emitted when polled. events: VecDeque<NetworkBehaviourAction<IdentifyPush, IdentifyEvent>>, /// Peers to which an active push with current information about /// the local peer should be sent. pending_push: HashSet<PeerId>, } /// A pending reply to an inbound identification request. enum Reply { /// The reply is queued for sending. Queued { peer: PeerId, io: ReplySubstream<NegotiatedSubstream>, observed: Multiaddr }, /// The reply is being sent. Sending { peer: PeerId, io: Pin<Box<dyn Future<Output = Result<(), io::Error>> + Send>>, } } /// Configuration for the [`Identify`] [`NetworkBehaviour`]. #[non_exhaustive] #[derive(Debug)] pub struct IdentifyConfig { /// Application-specific version of the protocol family used by the peer, /// e.g. `ipfs/1.0.0` or `polkadot/1.0.0`. pub protocol_version: String, /// The public key of the local node. To report on the wire. pub local_public_key: PublicKey, /// Name and version of the local peer implementation, similar to the /// `User-Agent` header in the HTTP protocol. /// /// Defaults to `rust-libp2p/<libp2p-identify-version>`. pub agent_version: String, /// The initial delay before the first identification request /// is sent to a remote on a newly established connection. /// /// Defaults to 500ms. pub initial_delay: Duration, /// The interval at which identification requests are sent to /// the remote on established connections after the first request, /// i.e. the delay between identification requests. /// /// Defaults to 5 minutes. pub interval: Duration, /// Whether new or expired listen addresses of the local node should /// trigger an active push of an identify message to all connected peers. /// /// Enabling this option can result in connected peers being informed /// earlier about new or expired listen addresses of the local node, /// i.e. before the next periodic identify request with each peer. /// /// Disabled by default. pub push_listen_addr_updates: bool, } impl IdentifyConfig { /// Creates a new configuration for the `Identify` behaviour that /// advertises the given protocol version and public key. pub fn new(protocol_version: String, local_public_key: PublicKey) -> Self { IdentifyConfig { protocol_version, agent_version: format!("rust-libp2p/{}", env!("CARGO_PKG_VERSION")), local_public_key, initial_delay: Duration::from_millis(500), interval: Duration::from_secs(5 * 60), push_listen_addr_updates: false, } } /// Configures the agent version sent to peers. pub fn with_agent_version(mut self, v: String) -> Self { self.agent_version = v; self } /// Configures the initial delay before the first identification /// request is sent on a newly established connection to a peer. pub fn with_initial_delay(mut self, d: Duration) -> Self { self.initial_delay = d; self } /// Configures the interval at which identification requests are /// sent to peers after the initial request. pub fn with_interval(mut self, d: Duration) -> Self { self.interval = d; self } /// Configures whether new or expired listen addresses of the local /// node should trigger an active push of an identify message to all /// connected peers. pub fn with_push_listen_addr_updates(mut self, b: bool) -> Self { self.push_listen_addr_updates = b; self } } impl Identify { /// Creates a new `Identify` network behaviour. pub fn new(config: IdentifyConfig) -> Self { Identify { config, connected: HashMap::new(), pending_replies: VecDeque::new(), events: VecDeque::new(), pending_push: HashSet::new(), } } /// Initiates an active push of the local peer information to the given peers. pub fn push<I>(&mut self, peers: I) where I: IntoIterator<Item = PeerId> { for p in peers { if self.pending_push.insert(p) { if !self.connected.contains_key(&p) { self.events.push_back(NetworkBehaviourAction::DialPeer { peer_id: p, condition: DialPeerCondition::Disconnected }); } } } } } impl NetworkBehaviour for Identify { type ProtocolsHandler = IdentifyHandler; type OutEvent = IdentifyEvent; fn new_handler(&mut self) -> Self::ProtocolsHandler { IdentifyHandler::new(self.config.initial_delay, self.config.interval) } fn addresses_of_peer(&mut self, _: &PeerId) -> Vec<Multiaddr> { Vec::new() } fn inject_connected(&mut self, _: &PeerId) { } fn inject_connection_established(&mut self, peer_id: &PeerId, conn: &ConnectionId, endpoint: &ConnectedPoint) { let addr = match endpoint { ConnectedPoint::Dialer { address } => address.clone(), ConnectedPoint::Listener { send_back_addr, .. } => send_back_addr.clone(), }; self.connected.entry(*peer_id).or_default().insert(*conn, addr); } fn inject_connection_closed(&mut self, peer_id: &PeerId, conn: &ConnectionId, _: &ConnectedPoint) { if let Some(addrs) = self.connected.get_mut(peer_id) { addrs.remove(conn); } } fn inject_dial_failure(&mut self, peer_id: &PeerId) { if !self.connected.contains_key(peer_id) { self.pending_push.remove(peer_id); } } fn inject_disconnected(&mut self, peer_id: &PeerId) { self.connected.remove(peer_id); self.pending_push.remove(peer_id); } fn inject_new_listen_addr(&mut self, _id: ListenerId, _addr: &Multiaddr) { if self.config.push_listen_addr_updates { self.pending_push.extend(self.connected.keys()); } } fn inject_expired_listen_addr(&mut self, _id: ListenerId, _addr: &Multiaddr) { if self.config.push_listen_addr_updates { self.pending_push.extend(self.connected.keys()); } } fn inject_event( &mut self, peer_id: PeerId, connection: ConnectionId, event: <Self::ProtocolsHandler as ProtocolsHandler>::OutEvent, ) { match event { IdentifyHandlerEvent::Identified(info) => { let observed = info.observed_addr.clone(); self.events.push_back( NetworkBehaviourAction::GenerateEvent( IdentifyEvent::Received { peer_id, info, })); self.events.push_back( NetworkBehaviourAction::ReportObservedAddr { address: observed, score: AddressScore::Finite(1), }); } IdentifyHandlerEvent::IdentificationPushed => { self.events.push_back( NetworkBehaviourAction::GenerateEvent( IdentifyEvent::Pushed { peer_id, })); } IdentifyHandlerEvent::Identify(sender) => { let observed = self.connected.get(&peer_id) .and_then(|addrs| addrs.get(&connection)) .expect("`inject_event` is only called with an established connection \ and `inject_connection_established` ensures there is an entry; qed"); self.pending_replies.push_back( Reply::Queued { peer: peer_id, io: sender, observed: observed.clone() }); } IdentifyHandlerEvent::IdentificationError(error) => { self.events.push_back( NetworkBehaviourAction::GenerateEvent( IdentifyEvent::Error { peer_id, error })); } } } fn poll( &mut self, cx: &mut Context<'_>, params: &mut impl PollParameters, ) -> Poll< NetworkBehaviourAction< <Self::ProtocolsHandler as ProtocolsHandler>::InEvent, Self::OutEvent, >, > { if let Some(event) = self.events.pop_front() { return Poll::Ready(event); } // Check for a pending active push to perform. let peer_push = self.pending_push.iter().find_map(|peer| { self.connected.get(peer).map(|conns| { let observed_addr = conns .values() .next() .expect("connected peer has a connection") .clone(); let listen_addrs = listen_addrs(params); let protocols = supported_protocols(params); let info = IdentifyInfo { public_key: self.config.local_public_key.clone(), protocol_version: self.config.protocol_version.clone(), agent_version: self.config.agent_version.clone(), listen_addrs, protocols, observed_addr, }; (*peer, IdentifyPush(info)) }) }); if let Some((peer_id, push)) = peer_push { self.pending_push.remove(&peer_id); return Poll::Ready(NetworkBehaviourAction::NotifyHandler { peer_id, event: push, handler: NotifyHandler::Any, }) } // Check for pending replies to send. if let Some(r) = self.pending_replies.pop_front() { let mut sending = 0; let to_send = self.pending_replies.len() + 1; let mut reply = Some(r); loop { match reply { Some(Reply::Queued { peer, io, observed }) => { let info = IdentifyInfo { listen_addrs: listen_addrs(params), protocols: supported_protocols(params), public_key: self.config.local_public_key.clone(), protocol_version: self.config.protocol_version.clone(), agent_version: self.config.agent_version.clone(), observed_addr: observed, }; let io = Box::pin(io.send(info)); reply = Some(Reply::Sending { peer, io }); } Some(Reply::Sending { peer, mut io }) => { sending += 1; match Future::poll(Pin::new(&mut io), cx) { Poll::Ready(Ok(())) => { let event = IdentifyEvent::Sent { peer_id: peer }; return Poll::Ready(NetworkBehaviourAction::GenerateEvent(event)); }, Poll::Pending => { self.pending_replies.push_back(Reply::Sending { peer, io }); if sending == to_send { // All remaining futures are NotReady break } else { reply = self.pending_replies.pop_front(); } } Poll::Ready(Err(err)) => { let event = IdentifyEvent::Error { peer_id: peer, error: ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(err)) }; return Poll::Ready(NetworkBehaviourAction::GenerateEvent(event)); }, } } None => unreachable!() } } } Poll::Pending } } /// Event emitted by the `Identify` behaviour. #[derive(Debug)] pub enum IdentifyEvent { /// Identification information has been received from a peer. Received { /// The peer that has been identified. peer_id: PeerId, /// The information provided by the peer. info: IdentifyInfo, }, /// Identification information of the local node has been sent to a peer in /// response to an identification request. Sent { /// The peer that the information has been sent to. peer_id: PeerId, }, /// Identification information of the local node has been actively pushed to /// a peer. Pushed { /// The peer that the information has been sent to. peer_id: PeerId, }, /// Error while attempting to identify the remote. Error { /// The peer with whom the error originated. peer_id: PeerId, /// The error that occurred. error: ProtocolsHandlerUpgrErr<io::Error>, }, } fn supported_protocols(params: &impl PollParameters) -> Vec<String> { // The protocol names can be bytes, but the identify protocol except UTF-8 strings. // There's not much we can do to solve this conflict except strip non-UTF-8 characters. params .supported_protocols() .map(|p| String::from_utf8_lossy(&p).to_string()) .collect() } fn listen_addrs(params: &impl PollParameters) -> Vec<Multiaddr> { let mut listen_addrs: Vec<_> = params.external_addresses().map(|r| r.addr).collect(); listen_addrs.extend(params.listened_addresses()); listen_addrs } #[cfg(test)] mod tests { use super::*; use futures::pin_mut; use libp2p_core::{ identity, PeerId, muxing::StreamMuxerBox, transport, Transport, upgrade }; use libp2p_noise as noise; use libp2p_tcp::TcpConfig; use libp2p_swarm::{Swarm, SwarmEvent}; use libp2p_mplex::MplexConfig; fn transport() -> (identity::PublicKey, transport::Boxed<(PeerId, StreamMuxerBox)>) { let id_keys = identity::Keypair::generate_ed25519(); let noise_keys = noise::Keypair::<noise::X25519Spec>::new().into_authentic(&id_keys).unwrap(); let pubkey = id_keys.public(); let transport = TcpConfig::new() .nodelay(true) .upgrade(upgrade::Version::V1) .authenticate(noise::NoiseConfig::xx(noise_keys).into_authenticated()) .multiplex(MplexConfig::new()) .boxed(); (pubkey, transport) } #[test] fn periodic_identify() { let (mut swarm1, pubkey1) = { let (pubkey, transport) = transport(); let protocol = Identify::new( IdentifyConfig::new("a".to_string(), pubkey.clone()) .with_agent_version("b".to_string())); let swarm = Swarm::new(transport, protocol, pubkey.clone().into_peer_id()); (swarm, pubkey) }; let (mut swarm2, pubkey2) = { let (pubkey, transport) = transport(); let protocol = Identify::new( IdentifyConfig::new("c".to_string(), pubkey.clone()) .with_agent_version("d".to_string())); let swarm = Swarm::new(transport, protocol, pubkey.clone().into_peer_id()); (swarm, pubkey) }; swarm1.listen_on("/ip4/127.0.0.1/tcp/0".parse().unwrap()).unwrap(); let listen_addr = async_std::task::block_on(async { loop { let swarm1_fut = swarm1.select_next_some(); pin_mut!(swarm1_fut); match swarm1_fut.await { SwarmEvent::NewListenAddr(addr) => return addr, _ => {} } } }); swarm2.dial_addr(listen_addr).unwrap(); // nb. Either swarm may receive the `Identified` event first, upon which // it will permit the connection to be closed, as defined by // `IdentifyHandler::connection_keep_alive`. Hence the test succeeds if // either `Identified` event arrives correctly. async_std::task::block_on(async move { loop { let swarm1_fut = swarm1.select_next_some(); pin_mut!(swarm1_fut); let swarm2_fut = swarm2.select_next_some(); pin_mut!(swarm2_fut); match future::select(swarm1_fut, swarm2_fut).await.factor_second().0 { future::Either::Left(SwarmEvent::Behaviour(IdentifyEvent::Received { info, .. })) => { assert_eq!(info.public_key, pubkey2); assert_eq!(info.protocol_version, "c"); assert_eq!(info.agent_version, "d"); assert!(!info.protocols.is_empty()); assert!(info.listen_addrs.is_empty()); return; } future::Either::Right(SwarmEvent::Behaviour(IdentifyEvent::Received { info, .. })) => { assert_eq!(info.public_key, pubkey1); assert_eq!(info.protocol_version, "a"); assert_eq!(info.agent_version, "b"); assert!(!info.protocols.is_empty()); assert_eq!(info.listen_addrs.len(), 1); return; } _ => {} } } }) } #[test] fn identify_push() { let _ = env_logger::try_init(); let (mut swarm1, pubkey1) = { let (pubkey, transport) = transport(); let protocol = Identify::new( IdentifyConfig::new("a".to_string(), pubkey.clone()) // Delay identification requests so we can test the push protocol. .with_initial_delay(Duration::from_secs(u32::MAX as u64))); let swarm = Swarm::new(transport, protocol, pubkey.clone().into_peer_id()); (swarm, pubkey) }; let (mut swarm2, pubkey2) = { let (pubkey, transport) = transport(); let protocol = Identify::new( IdentifyConfig::new("a".to_string(), pubkey.clone()) .with_agent_version("b".to_string()) // Delay identification requests so we can test the push protocol. .with_initial_delay(Duration::from_secs(u32::MAX as u64))); let swarm = Swarm::new(transport, protocol, pubkey.clone().into_peer_id()); (swarm, pubkey) }; Swarm::listen_on(&mut swarm1, "/ip4/127.0.0.1/tcp/0".parse().unwrap()).unwrap(); let listen_addr = async_std::task::block_on(async { loop { let swarm1_fut = swarm1.select_next_some(); pin_mut!(swarm1_fut); match swarm1_fut.await { SwarmEvent::NewListenAddr(addr) => return addr, _ => {} } } }); Swarm::dial_addr(&mut swarm2, listen_addr).unwrap(); async_std::task::block_on(async move { loop { let swarm1_fut = swarm1.select_next_some(); let swarm2_fut = swarm2.select_next_some(); { pin_mut!(swarm1_fut); pin_mut!(swarm2_fut); match future::select(swarm1_fut, swarm2_fut).await.factor_second().0 { future::Either::Left(SwarmEvent::Behaviour( IdentifyEvent::Received { info, .. } )) => { assert_eq!(info.public_key, pubkey2); assert_eq!(info.protocol_version, "a"); assert_eq!(info.agent_version, "b"); assert!(!info.protocols.is_empty()); assert!(info.listen_addrs.is_empty()); return; } future::Either::Right(SwarmEvent::ConnectionEstablished { .. }) => { // Once a connection is established, we can initiate an // active push below. } _ => { continue } } } swarm2.behaviour_mut().push(std::iter::once(pubkey1.clone().into_peer_id())); } }) } }
37.987097
115
0.550144
fef020b6422de9cf335123bbba436ad8da186fd3
4,104
// Copyright 2018 The Grin Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Definition of the genesis block. Placeholder for now. use time; use core; use consensus; use core::target::Difficulty; use global; /// Genesis block definition for development networks. The proof of work size /// is small enough to mine it on the fly, so it does not contain its own /// proof of work solution. Can also be easily mutated for different tests. pub fn genesis_dev() -> core::Block { core::Block { header: core::BlockHeader { height: 0, previous: core::hash::Hash([0xff; 32]), timestamp: time::Tm { tm_year: 1997 - 1900, tm_mon: 7, tm_mday: 4, ..time::empty_tm() }, nonce: global::get_genesis_nonce(), ..Default::default() }, inputs: vec![], outputs: vec![], kernels: vec![], } } /// First testnet genesis block, still subject to change (especially the date, /// will hopefully come before Christmas). pub fn genesis_testnet1() -> core::Block { core::Block { header: core::BlockHeader { height: 0, previous: core::hash::Hash([0xff; 32]), timestamp: time::Tm { tm_year: 2017 - 1900, tm_mon: 10, tm_mday: 16, tm_hour: 20, ..time::empty_tm() }, nonce: 28205, pow: core::Proof::new(vec![ 0x21e, 0x7a2, 0xeae, 0x144e, 0x1b1c, 0x1fbd, 0x203a, 0x214b, 0x293b, 0x2b74, 0x2bfa, 0x2c26, 0x32bb, 0x346a, 0x34c7, 0x37c5, 0x4164, 0x42cc, 0x4cc3, 0x55af, 0x5a70, 0x5b14, 0x5e1c, 0x5f76, 0x6061, 0x60f9, 0x61d7, 0x6318, 0x63a1, 0x63fb, 0x649b, 0x64e5, 0x65a1, 0x6b69, 0x70f8, 0x71c7, 0x71cd, 0x7492, 0x7b11, 0x7db8, 0x7f29, 0x7ff8, ]), ..Default::default() }, inputs: vec![], outputs: vec![], kernels: vec![], } } /// Second testnet genesis block (cuckoo30). TBD and don't start getting excited /// just because you see this reference here... this is for testing mining /// at cuckoo 30 pub fn genesis_testnet2() -> core::Block { core::Block { header: core::BlockHeader { height: 0, previous: core::hash::Hash([0xff; 32]), timestamp: time::Tm { tm_year: 2017 - 1900, tm_mon: 10, tm_mday: 16, tm_hour: 20, ..time::empty_tm() }, //TODO: Check this is over-estimated at T2 launch total_difficulty: Difficulty::from_num(global::initial_block_difficulty()), nonce: 70081, pow: core::Proof::new(vec![ 0x43ee48, 0x18d5a49, 0x2b76803, 0x3181a29, 0x39d6a8a, 0x39ef8d8, 0x478a0fb, 0x69c1f9e, 0x6da4bca, 0x6f8782c, 0x9d842d7, 0xa051397, 0xb56934c, 0xbf1f2c7, 0xc992c89, 0xce53a5a, 0xfa87225, 0x1070f99e, 0x107b39af, 0x1160a11b, 0x11b379a8, 0x12420e02, 0x12991602, 0x12cc4a71, 0x13d91075, 0x15c950d0, 0x1659b7be, 0x1682c2b4, 0x1796c62f, 0x191cf4c9, 0x19d71ac0, 0x1b812e44, 0x1d150efe, 0x1d15bd77, 0x1d172841, 0x1d51e967, 0x1ee1de39, 0x1f35c9b3, 0x1f557204, 0x1fbf884f, 0x1fcf80bf, 0x1fd59d40, ]), ..Default::default() }, inputs: vec![], outputs: vec![], kernels: vec![], } } /// Placeholder for mainnet genesis block, will definitely change before /// release so no use trying to pre-mine it. pub fn genesis_main() -> core::Block { core::Block { header: core::BlockHeader { height: 0, previous: core::hash::Hash([0xff; 32]), timestamp: time::Tm { tm_year: 2018 - 1900, tm_mon: 7, tm_mday: 14, ..time::empty_tm() }, total_difficulty: Difficulty::from_num(global::initial_block_difficulty()), nonce: global::get_genesis_nonce(), pow: core::Proof::zero(consensus::PROOFSIZE), ..Default::default() }, inputs: vec![], outputs: vec![], kernels: vec![], } }
30.626866
87
0.677632
2146742713e68b860d281c0f2303fd5614afff47
7,067
//! Implements low-level bitboard operations. These are fast, but not ergonomic; //! prefer to use abstractions under [`game`] if possible. //! //! Under the hood, all these operations work on u64 bitboards. By convention, //! the MSB is the upper-left of the board, and uses row-major order. use packed_simd::{u64x4, u64x8}; /// A wrapper type for bitboards, to ensure they aren't mixed with other numeric types. #[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord, Default)] pub struct Bitboard(pub u64); /// Compute a mask of the occupied locations on the board. #[inline] pub fn get_occupancy_mask(player_1: Bitboard, player_2: Bitboard) -> Bitboard { Bitboard(player_1.0 | player_2.0) } /// Compute a mask of empty squares on the board. #[inline] pub fn get_empty_mask(player_1: Bitboard, player_2: Bitboard) -> Bitboard { Bitboard(!(get_occupancy_mask(player_1, player_2).0)) } /// Count the number of empty spaces on the board. #[inline] pub fn count_empties(player_1: Bitboard, player_2: Bitboard) -> u8 { get_occupancy_mask(player_1, player_2).0.count_zeros() as u8 } /// Score a board as: # my pieces - # opponent pieces. /// Faster than [`score_winner_gets_empties()`], but less common. #[inline] pub fn score_absolute_difference(active: Bitboard, opponent: Bitboard) -> i8 { (active.0.count_ones() as i8) - (opponent.0.count_ones() as i8) } /// Score a board as: # my spaces - # opponent spaces, where empty spaces are scored for the winner. #[inline] pub fn score_winner_gets_empties(active: Bitboard, opponent: Bitboard) -> i8 { let absolute_difference = score_absolute_difference(active, opponent); if absolute_difference.is_positive() { absolute_difference + (count_empties(active, opponent) as i8) } else if absolute_difference.is_negative() { absolute_difference - (count_empties(active, opponent) as i8) } else { 0 } } /// Compute a mask of the legal moves for the active player from /// masks of the active player's stones and the opponent's stones. // Algorithm adapted from Sam Blazes' Coin, released under the Apache 2.0 license: // https://github.com/Tenebryo/coin/blob/master/bitboard/src/find_moves_fast.rs #[inline] pub fn get_move_mask(active: Bitboard, opponent: Bitboard) -> Bitboard { // Shifts for each vectorized direction: E/W, N/S, NW/SE, NE/SW. // The first direction is handled by SHL, the second by SHR. const SHIFTS_1: u64x4 = u64x4::new(1, 8, 7, 9); const SHIFTS_2: u64x4 = u64x4::new(2, 16, 14, 18); const SHIFTS_4: u64x4 = u64x4::new(4, 32, 28, 36); // Mask to clip off the invalid wraparound pieces on the edge. const EDGE_MASK: u64 = 0x7E7E7E7E7E7E7E7Eu64; let opponent_edge_mask = EDGE_MASK & opponent.0; // Masks used for each shift direction. The same for SHL and SHR. let masks: u64x4 = u64x4::new( opponent_edge_mask, opponent.0, opponent_edge_mask, opponent_edge_mask, ); // Pieces we flip while shifting along each direction. let mut flip_l = u64x4::splat(active.0); let mut flip_r = flip_l; // Accumulated mask when shifting along each direction. let mut masks_l = masks & (masks << SHIFTS_1); let mut masks_r = masks & (masks >> SHIFTS_1); // Smear our pieces in each direction while masking invalid flips. flip_l |= masks & (flip_l << SHIFTS_1); flip_l |= masks_l & (flip_l << SHIFTS_2); masks_l &= masks_l << SHIFTS_2; flip_l |= masks_l & (flip_l << SHIFTS_4); flip_r |= masks & (flip_r >> SHIFTS_1); flip_r |= masks_r & (flip_r >> SHIFTS_2); masks_r &= masks_r >> SHIFTS_2; flip_r |= masks_r & (flip_r >> SHIFTS_4); // Moves are the union of empties and one extra shift of all flipped locations. let empties = get_empty_mask(active, opponent).0; let captures_l = (flip_l & masks) << SHIFTS_1; let captures_r = (flip_r & masks) >> SHIFTS_1; Bitboard(empties & (captures_l | captures_r).or()) } /// Compute an updated board after a given move is made, returning new bitboards /// for the active player and the opponent. `move_mask` must be a one-hot bitboard /// indicating the move location; otherwise, the behavior of this function is undefined. #[inline] pub fn apply_move( active: Bitboard, opponent: Bitboard, move_mask: Bitboard, ) -> (Bitboard, Bitboard) { // Masks selecting everything except the far-left and far-right columns. const NOT_A_FILE: u64 = 0xfefefefefefefefe; const NOT_H_FILE: u64 = 0x7f7f7f7f7f7f7f7f; const FULL_MASK: u64 = 0xffffffffffffffff; // Masks applied when left-shifting or right-shifting. const LEFT_MASKS: u64x8 = u64x8::new( NOT_A_FILE, FULL_MASK, NOT_H_FILE, NOT_A_FILE, NOT_A_FILE, FULL_MASK, NOT_H_FILE, NOT_A_FILE, ); const RIGHT_MASKS: u64x8 = u64x8::new( NOT_H_FILE, FULL_MASK, NOT_A_FILE, NOT_H_FILE, NOT_H_FILE, FULL_MASK, NOT_A_FILE, NOT_H_FILE, ); // Shifts for each vectorized direction: E/W, N/S, NW/SE, NE/SW. // The first direction is handled by SHL, the second by SHR. const SHIFTS_1: u64x8 = u64x8::new(1, 8, 7, 9, 1, 8, 7, 9); const SHIFTS_2: u64x8 = u64x8::new(2, 16, 14, 18, 2, 16, 14, 18); const SHIFTS_4: u64x8 = u64x8::new(4, 32, 28, 36, 4, 32, 28, 36); // Generators and propagators for all LSH directions: E, N, NW, NE. // Two concatenated vectors: [new + opponent interactions, self + opponent interactions]. let mut gen_left = u64x8::new( move_mask.0, move_mask.0, move_mask.0, move_mask.0, active.0, active.0, active.0, active.0, ); let mut pro_left = u64x8::splat(opponent.0); // Generators and propagators for all RSH directions: W, S, SE, SW. // Two concatenated vectors: [self + opponent interactions, new + opponent interactions]. let mut gen_right = u64x8::new( active.0, active.0, active.0, active.0, move_mask.0, move_mask.0, move_mask.0, move_mask.0, ); let mut pro_right = pro_left; // Compute all LSH propagations. pro_left &= LEFT_MASKS; gen_left |= pro_left & (gen_left << SHIFTS_1); pro_left &= pro_left << SHIFTS_1; gen_left |= pro_left & (gen_left << SHIFTS_2); pro_left &= pro_left << SHIFTS_2; gen_left |= pro_left & (gen_left << SHIFTS_4); // Compute all RSH propagations. pro_right &= RIGHT_MASKS; gen_right |= pro_right & (gen_right >> SHIFTS_1); pro_right &= pro_right >> SHIFTS_1; gen_right |= pro_right & (gen_right >> SHIFTS_2); pro_right &= pro_right >> SHIFTS_2; gen_right |= pro_right & (gen_right >> SHIFTS_4); // gen_left : [Egp, Ngp, NWgp, NEgp, Eop, Nop, NWop, NEop] // gen_right: [Wop, Sop, SEop, SWop, Wgp, Sgp, SEgp, SWgp] let flip_mask = (gen_left & gen_right).or(); let new_active = Bitboard((active.0 ^ flip_mask) | move_mask.0); let new_opponent = Bitboard(opponent.0 ^ flip_mask); (new_active, new_opponent) }
37.791444
100
0.671006
efa7177783fdee2de2e433dd99d94d8ac6a2b8e2
2,520
//!Router asigns handlers to paths and resolves them per request pub use self::http_router::HttpRouter; pub use self::request_handler::{RequestHandler, ResponseFinalizer}; pub use self::router::{Router, Route, RouteResult}; pub mod http_router; pub mod request_handler; pub mod router; /// The path_utils collects some small helper methods that operate on the path mod path_utils { use regex::Regex; use std::collections::HashMap; // matches named variables (e.g. :userid) static REGEX_VAR_SEQ: Regex = regex!(r":([,a-zA-Z0-9_-]*)"); static VAR_SEQ:&'static str = "[,a-zA-Z0-9_-]*"; static VAR_SEQ_WITH_SLASH:&'static str = "[,/a-zA-Z0-9_-]*"; static VAR_SEQ_WITH_CAPTURE:&'static str = "([,a-zA-Z0-9%_-]*)"; // matches request params (e.g. ?foo=true&bar=false) static REGEX_PARAM_SEQ:&'static str = "(\\?[a-zA-Z0-9%_=&-]*)?"; static REGEX_START:&'static str = "^"; static REGEX_END:&'static str = "$"; pub fn create_regex (route_path: &str) -> Regex { let updated_path = route_path.to_string() // first mark all double wildcards for replacement. // We can't directly replace them since the replacement // does contain the * symbol as well, which would get // overwritten with the next replace call .replace("**", "___DOUBLE_WILDCARD___") // then replace the regular wildcard symbols (*) with the // appropriate regex .replace("*", VAR_SEQ) // now replace the previously marked double wild cards (**) .replace("___DOUBLE_WILDCARD___", VAR_SEQ_WITH_SLASH); // then replace the variable symbols (:variable) with the appropriate regex let result = [REGEX_START, REGEX_VAR_SEQ.replace_all(updated_path.as_slice(), VAR_SEQ_WITH_CAPTURE) .as_slice(), REGEX_PARAM_SEQ, REGEX_END].concat(); Regex::new(result.as_slice()).ok().unwrap() } pub fn get_variable_info (route_path: &str) -> HashMap<String, uint> { REGEX_VAR_SEQ.captures_iter(route_path) .enumerate() .map(|(i, matched)| (matched.at(1).to_string(), i)) .collect() } }
45
83
0.55754
505b2237c350439c7ba74d7faaad196db8af6332
8,536
//! ## LineGauge //! //! `LineGauge` is a line gauge /** * MIT License * * tui-realm - Copyright (C) 2021 Christian Visintin * * 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 super::props::{ LINE_GAUGE_STYLE_DOUBLE, LINE_GAUGE_STYLE_NORMAL, LINE_GAUGE_STYLE_ROUND, LINE_GAUGE_STYLE_THICK, }; use tuirealm::command::{Cmd, CmdResult}; use tuirealm::props::{ Alignment, AttrValue, Attribute, Borders, Color, PropPayload, PropValue, Props, Style, TextModifiers, }; use tuirealm::tui::{ layout::Rect, symbols::line::{Set, DOUBLE, NORMAL, ROUNDED, THICK}, widgets::LineGauge as TuiLineGauge, }; use tuirealm::{Frame, MockComponent, State}; // -- Component /// ## LineGauge /// /// provides a component which shows the progress. It is possible to set the style for the progress bar and the text shown above it. #[derive(Default)] pub struct LineGauge { props: Props, } impl LineGauge { pub fn foreground(mut self, fg: Color) -> Self { self.attr(Attribute::Foreground, AttrValue::Color(fg)); self } pub fn background(mut self, bg: Color) -> Self { self.attr(Attribute::Background, AttrValue::Color(bg)); self } pub fn borders(mut self, b: Borders) -> Self { self.attr(Attribute::Borders, AttrValue::Borders(b)); self } pub fn modifiers(mut self, m: TextModifiers) -> Self { self.attr(Attribute::TextProps, AttrValue::TextModifiers(m)); self } pub fn title<S: AsRef<str>>(mut self, t: S, a: Alignment) -> Self { self.attr( Attribute::Title, AttrValue::Title((t.as_ref().to_string(), a)), ); self } pub fn label<S: AsRef<str>>(mut self, s: S) -> Self { self.attr(Attribute::Text, AttrValue::String(s.as_ref().to_string())); self } pub fn progress(mut self, p: f64) -> Self { Self::assert_progress(p); self.attr( Attribute::Value, AttrValue::Payload(PropPayload::One(PropValue::F64(p))), ); self } pub fn style(mut self, s: u8) -> Self { Self::assert_line_style(s); self.attr( Attribute::Style, AttrValue::Payload(PropPayload::One(PropValue::U8(s))), ); self } fn line_set(&self) -> Set { match self .props .get_or( Attribute::Style, AttrValue::Payload(PropPayload::One(PropValue::U8(LINE_GAUGE_STYLE_NORMAL))), ) .unwrap_payload() { PropPayload::One(PropValue::U8(LINE_GAUGE_STYLE_DOUBLE)) => DOUBLE, PropPayload::One(PropValue::U8(LINE_GAUGE_STYLE_ROUND)) => ROUNDED, PropPayload::One(PropValue::U8(LINE_GAUGE_STYLE_THICK)) => THICK, _ => NORMAL, } } fn assert_line_style(s: u8) { if !(&[ LINE_GAUGE_STYLE_DOUBLE, LINE_GAUGE_STYLE_NORMAL, LINE_GAUGE_STYLE_ROUND, LINE_GAUGE_STYLE_THICK, ] .iter() .any(|x| *x == s)) { panic!("Invalid line style"); } } fn assert_progress(p: f64) { if !(0.0..=1.0).contains(&p) { panic!("Progress value must be in range [0.0, 1.0]"); } } } impl MockComponent for LineGauge { fn view(&mut self, render: &mut Frame, area: Rect) { // Make a Span if self.props.get_or(Attribute::Display, AttrValue::Flag(true)) == AttrValue::Flag(true) { // Text let label = self .props .get_or(Attribute::Text, AttrValue::String(String::default())) .unwrap_string(); let foreground = self .props .get_or(Attribute::Foreground, AttrValue::Color(Color::Reset)) .unwrap_color(); let background = self .props .get_or(Attribute::Background, AttrValue::Color(Color::Reset)) .unwrap_color(); let borders = self .props .get_or(Attribute::Borders, AttrValue::Borders(Borders::default())) .unwrap_borders(); let modifiers = self .props .get_or( Attribute::TextProps, AttrValue::TextModifiers(TextModifiers::empty()), ) .unwrap_text_modifiers(); let title = self.props.get(Attribute::Title).map(|x| x.unwrap_title()); // Get percentage let percentage = self .props .get_or( Attribute::Value, AttrValue::Payload(PropPayload::One(PropValue::F64(0.0))), ) .unwrap_payload() .unwrap_one() .unwrap_f64(); let div = crate::utils::get_block(borders, title, true, None); // Make progress bar render.render_widget( TuiLineGauge::default() .block(div) .gauge_style( Style::default() .fg(foreground) .bg(background) .add_modifier(modifiers), ) .line_set(self.line_set()) .label(label) .ratio(percentage), area, ); } } fn query(&self, attr: Attribute) -> Option<AttrValue> { self.props.get(attr) } fn attr(&mut self, attr: Attribute, value: AttrValue) { if let Attribute::Style = attr { if let AttrValue::Payload(s) = value.clone() { Self::assert_line_style(s.unwrap_one().unwrap_u8()); } } if let Attribute::Value = attr { if let AttrValue::Payload(p) = value.clone() { Self::assert_progress(p.unwrap_one().unwrap_f64()); } } self.props.set(attr, value) } fn state(&self) -> State { State::None } fn perform(&mut self, _cmd: Cmd) -> CmdResult { CmdResult::None } } #[cfg(test)] mod test { use super::*; use pretty_assertions::assert_eq; #[test] fn test_components_progress_bar() { let component = LineGauge::default() .background(Color::Red) .foreground(Color::White) .progress(0.60) .title("Downloading file...", Alignment::Center) .label("60% - ETA 00:20") .style(LINE_GAUGE_STYLE_DOUBLE) .borders(Borders::default()); // Get value assert_eq!(component.state(), State::None); } #[test] #[should_panic] fn line_gauge_bad_prog() { LineGauge::default() .background(Color::Red) .foreground(Color::White) .progress(6.0) .title("Downloading file...", Alignment::Center) .label("60% - ETA 00:20") .borders(Borders::default()); } #[test] #[should_panic] fn line_gauge_bad_symbol() { LineGauge::default() .background(Color::Red) .foreground(Color::White) .style(254) .title("Downloading file...", Alignment::Center) .label("60% - ETA 00:20") .borders(Borders::default()); } }
31.153285
132
0.550492
896aa29de17e7c1ab6c5ed03d3f9673da48f5e79
4,578
#![allow(dead_code)] #![allow(unused_variables)] #![allow(unused_mut)] pub fn foo() { // strings are implemented as a collection of bytes plus some methods to provide useful // functionality when those bytes are interpreted as text. // the 'str' type represents a string slice, and is usually seen in its borrowed form &str // str is a type in the langugage itself // String type is provided by the standard library // Both String and string slices are UTF-8 encoded. let mut s = String::from("foo bar"); { let slice: &str = &mut s[0..4]; // Can't do the following?? // slice[2] = 'x'; } println!("new string: {}", s); // 2 ways of creating String objects from string literals are equivalent let s = "foo bar".to_string(); let s = String::from("foo bar"); // Since strings are utf-8, the following are all valid let hello = "السلام عليكم"; let hello = "Dobrý den"; let hello = "Hello"; let hello = "שָׁלוֹם"; let hello = "नमस्ते"; let hello = "こんにちは"; let hello = "안녕하세요"; let hello = "你好"; let hello = "Olá"; let hello = "Здравствуйте"; let hello = "Hola"; // When taking string slices, we only read the bytes specified by the range. If the range of // bytes is cannot be decoded to UTF-8 code points, an attemp to do so might result in an // error. let hello = "नमस्ते"; let s = &hello[..3]; // This will only print न instead of नमस्. println!("I say: {}", s); // If we instead give the range of [0..2], the programs panics with the error: // 'byte index 2 is not a char boundary; it is inside 'न' (bytes 0..3) of `नमस्ते' // let s = &hello[..2]; // println!("{}", s); // String mutations // Push a string slice let mut hello = String::from("hello"); hello.push_str("foo"); // Push a character (unicode code point) let mut hello = "hol".to_string(); hello.push('न'); println!("hol is now: {}", hello); // Concat strings let hello = "hello,".to_string(); let world = String::from(" world!"); let hello_world = hello /* moved */ + &world; // We can't add 2 string values. The + operator takes a string reference as its argument. // Does this lead to new space allocation to store the new string? // hello = hello + world; is not allowed // CAn only add a &str to a String. &String gets coerced into a &str using deref coercion // (something like converting &s to &s[..]. println!("{}", hello_world); // Concatenating multiple strings let s1 = String::from("tic"); let s2 = String::from("tac"); let s3 = String::from("toe"); // format! macro is similar to println. Does not take ownership of its arguments let s = format!("{}-{}-{}", s1, s2, s3); // When doing simple addition, the first argument is moved. Does the str reference type not // implement the + operator? let s = s1 + "-" + &s2 + "-" + &s3; // println!("{}", s1); s1 has been moved! println!("{}", s2); println!("{}", s3); // We can't index into a string due to UTF-8 encoding and resulting ambiguity in what is really // desired fromt he index // Also, the expectation with indexing is O(1) access, whereas thay might not be possible for // Strings, due to the UTF-8 encoding of characters. let hello = "Здравствуйте"; // Not allowed: // let answer = &hello[0]; // // Instead, rust supports getting a string slice by specifying the byte range let s: &str = &hello[..2]; // index out-of-range will not be detected at compile time println!("{}", s); // In rust, we can think of strings in 3 ways: // 1. Sequence of bytes (vec[u8]) // 2. Unicode scalar values (these are what the'char' type in rust would have) // 3. Grapheme Clusters // e.g., the string "नमस्ते" can be: // 1. [224, 164, 168, 224, 164, 174, 224, 164, 184, 224, 165, 141, 224, 164, 164, 224, 165, 135] // 2. ['न', 'म', 'स', '्', 'त', 'े'] // Note that the 4th and 6th elements in this array are not // really characters, but instead diatrics which do not make sense in isolation. // 3. ["न", "म", "स्", "ते"] // // Apart from string slicing, rust also provides a way to iterator over the bytes or the // characters. Iteration over grapheme clusters is not provided through the standard library. // let hello = "नमस्ते"; for b in hello.bytes() { println!("{}", b); } for c in hello.chars() { println!("{}", c); } }
38.15
100
0.604412
5bd5c0145fe075c74ce4dc930739ba250a86aa89
410
#[doc = "Reader of register AHBNSPPCEXP1"] pub type R = crate::R<u32, super::AHBNSPPCEXP1>; #[doc = "Writer for register AHBNSPPCEXP1"] pub type W = crate::W<u32, super::AHBNSPPCEXP1>; #[doc = "Register AHBNSPPCEXP1 `reset()`'s with value 0"] impl crate::ResetValue for super::AHBNSPPCEXP1 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } impl R {} impl W {}
27.333333
57
0.643902
8aecb51e5bad98a2f49513c12fced8b358fd5d99
3,625
//! Pure Rust implementation of Ryū, an algorithm to quickly convert floating //! point numbers to decimal strings. //! //! The PLDI'18 paper [*Ryū: fast float-to-string conversion*][paper] by Ulf //! Adams includes a complete correctness proof of the algorithm. The paper is //! available under the creative commons CC-BY-SA license. //! //! This Rust implementation is a line-by-line port of Ulf Adams' implementation //! in C, [https://github.com/ulfjack/ryu][upstream]. //! //! [paper]: https://dl.acm.org/citation.cfm?id=3192369 //! [upstream]: https://github.com/ulfjack/ryu //! //! # Example //! //! ```edition2018 //! fn main() { //! let mut buffer = ryu::Buffer::new(); //! let printed = buffer.format(1.234); //! assert_eq!(printed, "1.234"); //! } //! ``` //! //! ## Performance //! //! You can run upstream's benchmarks with: //! //! ```console //! $ git clone https://github.com/ulfjack/ryu c-ryu //! $ cd c-ryu //! $ bazel run -c opt //ryu/benchmark //! ``` //! //! And the same benchmark against our implementation with: //! //! ```console //! $ git clone https://github.com/dtolnay/ryu rust-ryu //! $ cd rust-ryu //! $ cargo run --example upstream_benchmark --release //! ``` //! //! These benchmarks measure the average time to print a 32-bit float and average //! time to print a 64-bit float, where the inputs are distributed as uniform random //! bit patterns 32 and 64 bits wide. //! //! The upstream C code, the unsafe direct Rust port, and the safe pretty Rust API //! all perform the same, taking around 21 nanoseconds to format a 32-bit float and //! 31 nanoseconds to format a 64-bit float. //! //! There is also a Rust-specific benchmark comparing this implementation to the //! standard library which you can run with: //! //! ```console //! $ cargo bench //! ``` //! //! The benchmark shows Ryu approximately 4-10x faster than the standard library //! across a range of f32 and f64 inputs. Measurements are in nanoseconds per //! iteration; smaller is better. //! //! | type=f32 | 0.0 | 0.1234 | 2.718281828459045 | f32::MAX | //! |:--------:|:----:|:------:|:-----------------:|:--------:| //! | RYU | 3ns | 28ns | 23ns | 22ns | //! | STD | 40ns | 106ns | 128ns | 110ns | //! //! | type=f64 | 0.0 | 0.1234 | 2.718281828459045 | f64::MAX | //! |:--------:|:----:|:------:|:-----------------:|:--------:| //! | RYU | 3ns | 50ns | 35ns | 32ns | //! | STD | 39ns | 105ns | 128ns | 202ns | //! //! ## Formatting //! //! This library tends to produce more human-readable output than the standard //! library's to\_string, which never uses scientific notation. Here are two //! examples: //! //! - *ryu:* 1.23e40, *std:* 12300000000000000000000000000000000000000 //! - *ryu:* 1.23e-40, *std:* 0.000000000000000000000000000000000000000123 //! //! Both libraries print short decimals such as 0.0000123 without scientific //! notation. #![no_std] #![doc(html_root_url = "https://docs.rs/ryu/1.0.2")] #![cfg_attr(feature = "cargo-clippy", allow(renamed_and_removed_lints))] #![cfg_attr( feature = "cargo-clippy", allow(cast_lossless, many_single_char_names, unreadable_literal,) )] #[cfg(feature = "no-panic")] extern crate no_panic; mod buffer; mod common; mod d2s; #[cfg(not(feature = "small"))] mod d2s_full_table; mod d2s_intrinsics; #[cfg(feature = "small")] mod d2s_small_table; mod digit_table; mod f2s; mod pretty; pub use buffer::{Buffer, Float}; /// Unsafe functions that mirror the API of the C implementation of Ryū. pub mod raw { pub use pretty::{format32, format64}; }
32.366071
84
0.630897
f81920be54af934da96070c850dba1fcc7a4b50f
920
//! Generated file, do not edit by hand, see `xtask/codegen` use crate::generated::FormatJsAnyArrayBindingPatternElement; use crate::prelude::*; use rome_js_syntax::JsAnyArrayBindingPatternElement; impl FormatRule<JsAnyArrayBindingPatternElement> for FormatJsAnyArrayBindingPatternElement { type Context = JsFormatContext; fn fmt(node: &JsAnyArrayBindingPatternElement, f: &mut JsFormatter) -> FormatResult<()> { match node { JsAnyArrayBindingPatternElement::JsArrayHole(node) => node.format().fmt(f), JsAnyArrayBindingPatternElement::JsAnyBindingPattern(node) => node.format().fmt(f), JsAnyArrayBindingPatternElement::JsBindingPatternWithDefault(node) => { node.format().fmt(f) } JsAnyArrayBindingPatternElement::JsArrayBindingPatternRestElement(node) => { node.format().fmt(f) } } } }
43.809524
95
0.686957
3817efb5ae7fb7026c67932cb7c93e204f2c4fe9
4,301
//! An example of decoding multipart form requests extern crate futures; extern crate gotham; extern crate hyper; extern crate mime; extern crate multipart; use futures::{future, Future, Stream}; use gotham::handler::{HandlerFuture, IntoHandlerError}; use gotham::helpers::http::response::create_response; use gotham::router::builder::{build_simple_router, DefineSingleRoute, DrawRoutes}; use gotham::router::Router; use gotham::state::{FromState, State}; use hyper::header::CONTENT_TYPE; use hyper::{Body, HeaderMap, StatusCode}; use multipart::server::Multipart; use std::io::Cursor; use std::io::Read; /// Extracts the elements of the POST request and responds with the form keys and values fn form_handler(mut state: State) -> Box<HandlerFuture> { const BOUNDARY: &str = "boundary="; let header_map = HeaderMap::take_from(&mut state); let boundary = header_map .get(CONTENT_TYPE) .and_then(|ct| { let ct = ct.to_str().ok()?; let idx = ct.find(BOUNDARY)?; Some(ct[idx + BOUNDARY.len()..].to_string()) }) .unwrap(); let f = Body::take_from(&mut state) .concat2() .then(|full_body| match full_body { Ok(valid_body) => { let mut m = Multipart::with_body(Cursor::new(valid_body), boundary); match m.read_entry() { Ok(Some(mut field)) => { let mut data = Vec::new(); field.data.read_to_end(&mut data).expect("can't read"); let res_result = String::from_utf8(data); let res_body; match res_result { Ok(r) => res_body = r.to_string(), Err(e) => res_body = format!("{:?}", e), } let res = create_response(&state, StatusCode::OK, mime::TEXT_PLAIN, res_body); future::ok((state, res)) } Ok(None) => { let res = create_response( &state, StatusCode::OK, mime::TEXT_PLAIN, "can't read".to_string(), ); future::ok((state, res)) } Err(e) => { let res = create_response( &state, StatusCode::OK, mime::TEXT_PLAIN, format!("{:?}", e), ); future::ok((state, res)) } } } Err(e) => future::err((state, e.into_handler_error())), }); Box::new(f) } /// Create a `Router` fn router() -> Router { build_simple_router(|route| { route.post("/").to(form_handler); }) } /// Start a server and use a `Router` to dispatch requests pub fn main() { let addr = "127.0.0.1:7878"; println!("Listening for requests at http://{}", addr); gotham::start(addr, router()) } #[cfg(test)] mod tests { use super::*; use gotham::test::TestServer; use hyper::header::HeaderValue; #[test] fn form_request() { let boundary = "--abcdef1234--"; let body = format!( "--{0}\r\n\ content-disposition: form-data; name=\"foo\"\r\n\r\n\ bar\r\n\ --{0}--\r\n", boundary ); let test_server = TestServer::new(router()).unwrap(); let client = test_server.client(); let mut request = client.post("http://localhost", body, mime::MULTIPART_FORM_DATA); let content_type_string = format!("multipart/form-data; boundary={}", boundary); request.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str(content_type_string.as_str()).unwrap(), ); let response = request.perform().unwrap(); assert_eq!(response.status(), StatusCode::OK); let body = response.read_body().unwrap(); let r = String::from_utf8(body).unwrap(); assert_eq!(r, "bar"); } }
34.408
96
0.500349
16c78da81c846fce0e972ebf6874c8a852a22dd1
4,920
//! Abstraction over blocking and unblocking the current thread. //! //! Provides an abstraction over blocking the current thread. This is similar to //! the park / unpark constructs provided by [`std`] but made generic. This //! allows embedding custom functionality to perform when the thread is blocked. //! //! A blocked [`Park`][p] instance is unblocked by calling [`unpark`] on its //! [`Unpark`][up] handle. //! //! The [`ParkThread`] struct implements [`Park`][p] using //! [`thread::park`][`std`] to put the thread to sleep. The Tokio reactor also //! implements park, but uses [`mio::Poll`][mio] to block the thread instead. //! //! The [`Park`][p] trait is composable. A timer implementation might decorate a //! [`Park`][p] implementation by checking if any timeouts have elapsed after //! the inner [`Park`][p] implementation unblocks. //! //! # Model //! //! Conceptually, each [`Park`][p] instance has an associated token, which is //! initially not present: //! //! * The [`park`] method blocks the current thread unless or until the token //! is available, at which point it atomically consumes the token. //! * The [`unpark`] method atomically makes the token available if it wasn't //! already. //! //! Some things to note: //! //! * If [`unpark`] is called before [`park`], the next call to [`park`] will //! **not** block the thread. //! * **Spurious** wakeups are permitted, i.e., the [`park`] method may unblock //! even if [`unpark`] was not called. //! * [`park_timeout`] does the same as [`park`] but allows specifying a maximum //! time to block the thread for. //! //! [`std`]: https://doc.rust-lang.org/std/thread/fn.park.html //! [`thread::park`]: https://doc.rust-lang.org/std/thread/fn.park.html //! [`ParkThread`]: struct.ParkThread.html //! [p]: trait.Park.html //! [`park`]: trait.Park.html#tymethod.park //! [`park_timeout`]: trait.Park.html#tymethod.park_timeout //! [`unpark`]: trait.Unpark.html#tymethod.unpark //! [up]: trait.Unpark.html //! [mio]: https://docs.rs/mio/0.6/mio/struct.Poll.html mod thread; pub use self::thread::{ParkError, ParkThread, UnparkThread}; use std::sync::Arc; use std::time::Duration; /// Block the current thread. /// /// See [module documentation][mod] for more details. /// /// [mod]: ../index.html pub trait Park { /// Unpark handle type for the `Park` implementation. type Unpark: Unpark; /// Error returned by `park` type Error; /// Get a new `Unpark` handle associated with this `Park` instance. fn unpark(&self) -> Self::Unpark; /// Block the current thread unless or until the token is available. /// /// A call to `park` does not guarantee that the thread will remain blocked /// forever, and callers should be prepared for this possibility. This /// function may wakeup spuriously for any reason. /// /// See [module documentation][mod] for more details. /// /// # Panics /// /// This function **should** not panic, but ultimately, panics are left as /// an implementation detail. Refer to the documentation for the specific /// `Park` implementation /// /// [mod]: ../index.html fn park(&mut self) -> Result<(), Self::Error>; /// Park the current thread for at most `duration`. /// /// This function is the same as `park` but allows specifying a maximum time /// to block the thread for. /// /// Same as `park`, there is no guarantee that the thread will remain /// blocked for any amount of time. Spurious wakeups are permitted for any /// reason. /// /// See [module documentation][mod] for more details. /// /// # Panics /// /// This function **should** not panic, but ultimately, panics are left as /// an implementation detail. Refer to the documentation for the specific /// `Park` implementation /// /// [mod]: ../index.html fn park_timeout(&mut self, duration: Duration) -> Result<(), Self::Error>; } /// Unblock a thread blocked by the associated [`Park`] instance. /// /// See [module documentation][mod] for more details. /// /// [mod]: ../index.html /// [`Park`]: trait.Park.html pub trait Unpark: Sync + Send + 'static { /// Unblock a thread that is blocked by the associated `Park` handle. /// /// Calling `unpark` atomically makes available the unpark token, if it is /// not already available. /// /// See [module documentation][mod] for more details. /// /// # Panics /// /// This function **should** not panic, but ultimately, panics are left as /// an implementation detail. Refer to the documentation for the specific /// `Unpark` implementation /// /// [mod]: ../index.html fn unpark(&self); } impl Unpark for Box<dyn Unpark> { fn unpark(&self) { (**self).unpark() } } impl Unpark for Arc<dyn Unpark> { fn unpark(&self) { (**self).unpark() } }
34.893617
80
0.642683
1ab50d6e872a010fc900445b204ab19a3241b3ab
5,898
//! ## Tools for working with functions //! //! e.g.: //! - chaining //! - composing //! - applying to values //! - supplying arguments //! - currying (O_O) //! - Flipping arguments/output/both //! - Cartesian product of functions //! - Untupling (running a function `A, B -> _` on _argument_ `(A, B)`) //! //! ## DISCLAIMER //! //! This library more an fun experiment with rust, than really useful library. //! //! However, in some cases it can make code a bit cleaner. //! //! ## Alternatives //! //! Similar libraries: //! - [tool](https://stebalien.github.io/tool-rs/tool/index.html) //! - [compose](https://docs.rs/compose/0.1.0/compose/) //! //! You know other alternatives? - ping me in [telegram] or open issue on //! [github]! //! //! ## Stability //! //! This library can work on both `stable` and `nightly` _however_ without //! nightly it loses **a lot** of core functionality. //! //! To build with `nightly` features you need to enable `"nightly"` crate //! feature: //! ```toml //! // Cargo.toml //! fntools = { version = "0.1.0", features = ["nightly"] } //! ``` //! This will add [`unstable`] module with all the APIs which use //! nightly-only unstable API. //! //! ## Unstable API //! //! Unstable API provides these features: //! - Multi-argument working (this uses a lot of hacks, but works!) //! - You can e.g. chain `A, B -> C` and `C -> D` to receive `A, B -> D` //! - You can e.g. chain `A -> (B, C)` and `B, C -> D`to receive `A -> D` //! - You can e.g. product `A, B -> C` and `X -> Y` to receive `A, B, X -> (C, //! Y)` // TODO //! - Working with all fns at once (no `_mut` and `_once` versions of functions) //! - Flipping big functions (e.g.: `A, B, C -> D` to `C, B, A -> D`) // TODO //! - Destructing functions into inner functions (e.g.: [`Chain::into_inner`]) //! - Extensions on `Fn*` traits (e.g.: [`.chain`]) //! //! Using [`unboxed_closures`] and [`fn_traits`] features ([tracking issue]) //! //! ## See also //! //! - [Wiki: Function Composition] //! - [rossetacode.org: Function Composition] //! - [stackoverflow: How to compose functions in Rust?] //! //! [telegram]: https://vee.gg/t/WaffleLapkin //! [github]: https://github.com/WaffleLapkin/fntools //! //! [`unstable`]: crate::unstable //! //! [`Chain::into_inner`]: crate::unstable::Chain::into_inner //! [`.chain`]: crate::unstable::FnExt::chain //! //! [`fn_traits`]: https://doc.rust-lang.org/unstable-book/library-features/fn-traits.html //! [`unboxed_closures`]: https://doc.rust-lang.org/unstable-book/language-features/unboxed-closures.html //! [tracking issue]: https://github.com/rust-lang/rust/issues/29625 //! //! [Wiki: Function Composition]: https://en.wikipedia.org/wiki/Function_composition //! [rossetacode.org: Function Composition]: https://rosettacode.org/wiki/Function_composition#Rust //! [stackoverflow: How to compose functions in Rust?]: https://stackoverflow.com/questions/45786955/how-to-compose-functions-in-rust #![cfg_attr(feature = "nightly", feature(unboxed_closures, fn_traits))] #![doc(html_favicon_url = "https://raw.githubusercontent.com/WaffleLapkin/fntools/dev/icon.ico")] #![doc(html_logo_url = "https://raw.githubusercontent.com/WaffleLapkin/fntools/dev/logo.svg")] // I want explicit `Fn(Arg) -> ()` #![allow(clippy::unused_unit)] #![deny( missing_debug_implementations, missing_copy_implementations, missing_docs, broken_intra_doc_links )] #[macro_use] /// Helper macros these are used in this lib mod local_macros; /// Definitions on public (`#[macro_export]`) macros mod macro_def; /// 'Sealed' trait that prevents implementing tuple traits in other crates mod sealed; /// Helper module for moving stable thing to dedicated dir mod stable { pub mod chain; pub mod compose; pub mod flip; pub mod product; /// Unit function output. pub mod unit; /// Extensions for all types pub mod value; } pub use stable::{ chain::{chain, chain_mut, chain_once}, compose::{compose, compose_mut, compose_once}, flip::{flip, flip_mut, flip_once}, product::{product, product_mut, product_once}, unit::{unit, unit_mut, unit_once}, value, }; /// Features that uses nightly-only unstable API #[cfg(feature = "nightly")] pub mod unstable { pub use self::{ chain::{chain, Chain}, compose::{compose, Compose}, curry::{curry, Curry}, ext::FnExt, flip::{flip, Flip}, supply::{supply, Supply}, unit::{unit, Unit}, untuple::{untuple, Untuple}, value::ValueExtUnstable, }; mod chain; mod compose; mod curry; mod ext; mod flip; mod supply; mod unit; mod untuple; mod value; } /// Helpers for working with tuples /// /// **Note**: in all of the traits there is no tuples of arity >= 13 (neither in /// requirements neither in return types). It's because Rust current type system /// can't express "tuple of any size" (see [Draft RFC: variadic generics] for /// proposes how to fix this) so this lib follows the [stdlib] in implementing /// traits on tuples of arity 12 or less. /// /// [Draft RFC: variadic generics]: https://github.com/rust-lang/rfcs/issues/376 /// [stdlib]: https://doc.rust-lang.org/std/primitive.tuple.html#trait-implementations pub mod tuple { /// Append element to tuple (`T + (A, B) => (T, A, B)`) pub mod append; /// Tuple with at least 2 elements. pub mod at_least_2; /// Concat tuples (`(A, B) + (C, D) => (A, B, C, D)`) /// /// **NOTE**: this module is under `#[cfg(feature = "concat")]` #[cfg(feature = "concat")] pub mod concat; /// Flip tuple (`(A, B) => (B, A)`) pub mod flip; /// Pop element from tuple (`(A, B, T) => ((A, B), T)`) pub mod pop; /// Push element to tuple (`(A, B) + T => (A, B, T)`) pub mod push; /// Take element from tuple (`(T, A, B) => (T, (A, B))`) pub mod take; }
33.896552
133
0.633435
2f863d3da62ac957f1b83a314c35ac4ca71c21c0
675
// xfail-fast // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[allow(dead_assignment)]; extern mod extra; use std::vec::*; pub fn main() { let mut v = from_elem(0u, 0); v = append(v, [4, 2]); assert_eq!(from_fn(2, |i| 2*(i+1)), ~[2, 4]); }
29.347826
68
0.682963
8a1dea4d99bfed44e1aa40e4ab67fde92f6c79c9
17,533
//! A helper class for dealing with static archives use std::env; use std::ffi::{CStr, CString, OsString}; use std::io; use std::mem; use std::path::{Path, PathBuf}; use std::ptr; use std::str; use crate::llvm::archive_ro::{ArchiveRO, Child}; use crate::llvm::{self, ArchiveKind, LLVMMachineType, LLVMRustCOFFShortExport}; use rustc_codegen_ssa::back::archive::ArchiveBuilder; use rustc_data_structures::temp_dir::MaybeTempDir; use rustc_session::cstore::{DllCallingConvention, DllImport}; use rustc_session::Session; struct ArchiveConfig<'a> { pub sess: &'a Session, pub dst: PathBuf, pub src: Option<PathBuf>, } /// Helper for adding many files to an archive. #[must_use = "must call build() to finish building the archive"] pub struct LlvmArchiveBuilder<'a> { config: ArchiveConfig<'a>, removals: Vec<String>, additions: Vec<Addition>, should_update_symbols: bool, src_archive: Option<Option<ArchiveRO>>, } enum Addition { File { path: PathBuf, name_in_archive: String }, Archive { path: PathBuf, archive: ArchiveRO, skip: Box<dyn FnMut(&str) -> bool> }, } impl Addition { fn path(&self) -> &Path { match self { Addition::File { path, .. } | Addition::Archive { path, .. } => path, } } } fn is_relevant_child(c: &Child<'_>) -> bool { match c.name() { Some(name) => !name.contains("SYMDEF"), None => false, } } fn archive_config<'a>(sess: &'a Session, output: &Path, input: Option<&Path>) -> ArchiveConfig<'a> { ArchiveConfig { sess, dst: output.to_path_buf(), src: input.map(|p| p.to_path_buf()) } } /// Map machine type strings to values of LLVM's MachineTypes enum. fn llvm_machine_type(cpu: &str) -> LLVMMachineType { match cpu { "x86_64" => LLVMMachineType::AMD64, "x86" => LLVMMachineType::I386, "aarch64" => LLVMMachineType::ARM64, "arm" => LLVMMachineType::ARM, _ => panic!("unsupported cpu type {}", cpu), } } impl<'a> ArchiveBuilder<'a> for LlvmArchiveBuilder<'a> { /// Creates a new static archive, ready for modifying the archive specified /// by `config`. fn new(sess: &'a Session, output: &Path, input: Option<&Path>) -> LlvmArchiveBuilder<'a> { let config = archive_config(sess, output, input); LlvmArchiveBuilder { config, removals: Vec::new(), additions: Vec::new(), should_update_symbols: false, src_archive: None, } } /// Removes a file from this archive fn remove_file(&mut self, file: &str) { self.removals.push(file.to_string()); } /// Lists all files in an archive fn src_files(&mut self) -> Vec<String> { if self.src_archive().is_none() { return Vec::new(); } let archive = self.src_archive.as_ref().unwrap().as_ref().unwrap(); archive .iter() .filter_map(|child| child.ok()) .filter(is_relevant_child) .filter_map(|child| child.name()) .filter(|name| !self.removals.iter().any(|x| x == name)) .map(|name| name.to_owned()) .collect() } fn add_archive<F>(&mut self, archive: &Path, skip: F) -> io::Result<()> where F: FnMut(&str) -> bool + 'static, { let archive_ro = match ArchiveRO::open(archive) { Ok(ar) => ar, Err(e) => return Err(io::Error::new(io::ErrorKind::Other, e)), }; if self.additions.iter().any(|ar| ar.path() == archive) { return Ok(()); } self.additions.push(Addition::Archive { path: archive.to_path_buf(), archive: archive_ro, skip: Box::new(skip), }); Ok(()) } /// Adds an arbitrary file to this archive fn add_file(&mut self, file: &Path) { let name = file.file_name().unwrap().to_str().unwrap(); self.additions .push(Addition::File { path: file.to_path_buf(), name_in_archive: name.to_owned() }); } /// Indicate that the next call to `build` should update all symbols in /// the archive (equivalent to running 'ar s' over it). fn update_symbols(&mut self) { self.should_update_symbols = true; } /// Combine the provided files, rlibs, and native libraries into a single /// `Archive`. fn build(mut self) { let kind = self.llvm_archive_kind().unwrap_or_else(|kind| { self.config.sess.fatal(&format!("Don't know how to build archive of type: {}", kind)) }); if let Err(e) = self.build_with_llvm(kind) { self.config.sess.fatal(&format!("failed to build archive: {}", e)); } } fn inject_dll_import_lib( &mut self, lib_name: &str, dll_imports: &[DllImport], tmpdir: &MaybeTempDir, ) { let output_path = { let mut output_path: PathBuf = tmpdir.as_ref().to_path_buf(); output_path.push(format!("{}_imports", lib_name)); output_path.with_extension("lib") }; let mingw_gnu_toolchain = self.config.sess.target.llvm_target.ends_with("pc-windows-gnu"); let import_name_and_ordinal_vector: Vec<(String, Option<u16>)> = dll_imports .iter() .map(|import: &DllImport| { if self.config.sess.target.arch == "x86" { ( LlvmArchiveBuilder::i686_decorated_name(import, mingw_gnu_toolchain), import.ordinal, ) } else { (import.name.to_string(), import.ordinal) } }) .collect(); if mingw_gnu_toolchain { // The binutils linker used on -windows-gnu targets cannot read the import // libraries generated by LLVM: in our attempts, the linker produced an .EXE // that loaded but crashed with an AV upon calling one of the imported // functions. Therefore, use binutils to create the import library instead, // by writing a .DEF file to the temp dir and calling binutils's dlltool. let def_file_path = tmpdir.as_ref().join(format!("{}_imports", lib_name)).with_extension("def"); let def_file_content = format!( "EXPORTS\n{}", import_name_and_ordinal_vector .into_iter() .map(|(name, ordinal)| { match ordinal { Some(n) => format!("{} @{} NONAME", name, n), None => name, } }) .collect::<Vec<String>>() .join("\n") ); match std::fs::write(&def_file_path, def_file_content) { Ok(_) => {} Err(e) => { self.config.sess.fatal(&format!("Error writing .DEF file: {}", e)); } }; let dlltool = find_binutils_dlltool(self.config.sess); let result = std::process::Command::new(dlltool) .args([ "-d", def_file_path.to_str().unwrap(), "-D", lib_name, "-l", output_path.to_str().unwrap(), ]) .output(); match result { Err(e) => { self.config.sess.fatal(&format!("Error calling dlltool: {}", e)); } Ok(output) if !output.status.success() => self.config.sess.fatal(&format!( "Dlltool could not create import library: {}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr) )), _ => {} } } else { // we've checked for \0 characters in the library name already let dll_name_z = CString::new(lib_name).unwrap(); let output_path_z = rustc_fs_util::path_to_c_string(&output_path); tracing::trace!("invoking LLVMRustWriteImportLibrary"); tracing::trace!(" dll_name {:#?}", dll_name_z); tracing::trace!(" output_path {}", output_path.display()); tracing::trace!( " import names: {}", dll_imports .iter() .map(|import| import.name.to_string()) .collect::<Vec<_>>() .join(", "), ); // All import names are Rust identifiers and therefore cannot contain \0 characters. // FIXME: when support for #[link_name] is implemented, ensure that the import names // still don't contain any \0 characters. Also need to check that the names don't // contain substrings like " @" or "NONAME" that are keywords or otherwise reserved // in definition files. let cstring_import_name_and_ordinal_vector: Vec<(CString, Option<u16>)> = import_name_and_ordinal_vector .into_iter() .map(|(name, ordinal)| (CString::new(name).unwrap(), ordinal)) .collect(); let ffi_exports: Vec<LLVMRustCOFFShortExport> = cstring_import_name_and_ordinal_vector .iter() .map(|(name_z, ordinal)| LLVMRustCOFFShortExport::new(name_z.as_ptr(), *ordinal)) .collect(); let result = unsafe { crate::llvm::LLVMRustWriteImportLibrary( dll_name_z.as_ptr(), output_path_z.as_ptr(), ffi_exports.as_ptr(), ffi_exports.len(), llvm_machine_type(&self.config.sess.target.arch) as u16, !self.config.sess.target.is_like_msvc, ) }; if result == crate::llvm::LLVMRustResult::Failure { self.config.sess.fatal(&format!( "Error creating import library for {}: {}", lib_name, llvm::last_error().unwrap_or("unknown LLVM error".to_string()) )); } }; self.add_archive(&output_path, |_| false).unwrap_or_else(|e| { self.config.sess.fatal(&format!( "failed to add native library {}: {}", output_path.display(), e )); }); } } impl<'a> LlvmArchiveBuilder<'a> { fn src_archive(&mut self) -> Option<&ArchiveRO> { if let Some(ref a) = self.src_archive { return a.as_ref(); } let src = self.config.src.as_ref()?; self.src_archive = Some(ArchiveRO::open(src).ok()); self.src_archive.as_ref().unwrap().as_ref() } fn llvm_archive_kind(&self) -> Result<ArchiveKind, &str> { let kind = &*self.config.sess.target.archive_format; kind.parse().map_err(|_| kind) } fn build_with_llvm(&mut self, kind: ArchiveKind) -> io::Result<()> { let removals = mem::take(&mut self.removals); let mut additions = mem::take(&mut self.additions); let mut strings = Vec::new(); let mut members = Vec::new(); let dst = CString::new(self.config.dst.to_str().unwrap())?; let should_update_symbols = self.should_update_symbols; unsafe { if let Some(archive) = self.src_archive() { for child in archive.iter() { let child = child.map_err(string_to_io_error)?; let child_name = match child.name() { Some(s) => s, None => continue, }; if removals.iter().any(|r| r == child_name) { continue; } let name = CString::new(child_name)?; members.push(llvm::LLVMRustArchiveMemberNew( ptr::null(), name.as_ptr(), Some(child.raw), )); strings.push(name); } } for addition in &mut additions { match addition { Addition::File { path, name_in_archive } => { let path = CString::new(path.to_str().unwrap())?; let name = CString::new(name_in_archive.clone())?; members.push(llvm::LLVMRustArchiveMemberNew( path.as_ptr(), name.as_ptr(), None, )); strings.push(path); strings.push(name); } Addition::Archive { archive, skip, .. } => { for child in archive.iter() { let child = child.map_err(string_to_io_error)?; if !is_relevant_child(&child) { continue; } let child_name = child.name().unwrap(); if skip(child_name) { continue; } // It appears that LLVM's archive writer is a little // buggy if the name we pass down isn't just the // filename component, so chop that off here and // pass it in. // // See LLVM bug 25877 for more info. let child_name = Path::new(child_name).file_name().unwrap().to_str().unwrap(); let name = CString::new(child_name)?; let m = llvm::LLVMRustArchiveMemberNew( ptr::null(), name.as_ptr(), Some(child.raw), ); members.push(m); strings.push(name); } } } } let r = llvm::LLVMRustWriteArchive( dst.as_ptr(), members.len() as libc::size_t, members.as_ptr() as *const &_, should_update_symbols, kind, ); let ret = if r.into_result().is_err() { let err = llvm::LLVMRustGetLastError(); let msg = if err.is_null() { "failed to write archive".into() } else { String::from_utf8_lossy(CStr::from_ptr(err).to_bytes()) }; Err(io::Error::new(io::ErrorKind::Other, msg)) } else { Ok(()) }; for member in members { llvm::LLVMRustArchiveMemberFree(member); } ret } } fn i686_decorated_name(import: &DllImport, mingw: bool) -> String { let name = import.name; let prefix = if mingw { "" } else { "_" }; match import.calling_convention { DllCallingConvention::C => format!("{}{}", prefix, name), DllCallingConvention::Stdcall(arg_list_size) => { format!("{}{}@{}", prefix, name, arg_list_size) } DllCallingConvention::Fastcall(arg_list_size) => format!("@{}@{}", name, arg_list_size), DllCallingConvention::Vectorcall(arg_list_size) => { format!("{}@@{}", name, arg_list_size) } } } } fn string_to_io_error(s: String) -> io::Error { io::Error::new(io::ErrorKind::Other, format!("bad archive: {}", s)) } fn find_binutils_dlltool(sess: &Session) -> OsString { assert!(sess.target.options.is_like_windows && !sess.target.options.is_like_msvc); if let Some(dlltool_path) = &sess.opts.debugging_opts.dlltool { return dlltool_path.clone().into_os_string(); } let mut tool_name: OsString = if sess.host.arch != sess.target.arch { // We are cross-compiling, so we need the tool with the prefix matching our target if sess.target.arch == "x86" { "i686-w64-mingw32-dlltool" } else { "x86_64-w64-mingw32-dlltool" } } else { // We are not cross-compiling, so we just want `dlltool` "dlltool" } .into(); if sess.host.options.is_like_windows { // If we're compiling on Windows, add the .exe suffix tool_name.push(".exe"); } // NOTE: it's not clear how useful it is to explicitly search PATH. for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) { let full_path = dir.join(&tool_name); if full_path.is_file() { return full_path.into_os_string(); } } // The user didn't specify the location of the dlltool binary, and we weren't able // to find the appropriate one on the PATH. Just return the name of the tool // and let the invocation fail with a hopefully useful error message. tool_name }
37.543897
100
0.507671
224b5e50e32d6966193e7eb5bb1d7d1aa815d3e1
8,562
use once_cell::sync::Lazy; use regex::Regex; use crate::config_parser::parse; use crate::letters::*; use crate::ligatures::LIGATURES; use std::collections::HashMap; use std::iter::repeat; static HARAKAT_RE: Lazy<Regex> = Lazy::new(|| { // correct Regex -> safe unwrap Regex::new( "[\u{0610}-\u{061a}\u{064b}-\u{065f}\u{0670}\u{06d6}-\u{06dc}\u{06df}-\u{06e8}\u{06ea}-\u{06ed}\u{08d4}-\u{08e1}\u{08d4}-\u{08ed}\u{08e3}-\u{08ff}]" ).unwrap() }); const NOT_SUPPORTED: i16 = -1; const EMPTY: (char, i16) = ('e', NOT_SUPPORTED); pub struct ArabicReshaper { configuration: HashMap<String, bool>, re_group_index_to_ligature_forms: HashMap<usize, [&'static str; 4]>, patterns: Vec<String>, } impl ArabicReshaper { pub fn new() -> Self { Self { configuration: parse(), re_group_index_to_ligature_forms: HashMap::new(), patterns: Vec::new(), } } #[allow(clippy::cognitive_complexity)] pub fn reshape(&mut self, text: &str) -> String { let mut output = Vec::new(); let delete_harakat = self.configuration["delete_harakat"]; let delete_tatweel = self.configuration["delete_tatweel"]; let support_zwj = self.configuration["support_zwj"]; let shift_harakat_position = self.configuration["shift_harakat_position"]; let use_unshaped_instead_of_isolated = self.configuration["use_unshaped_instead_of_isolated"]; let mut position_harakat: HashMap<i16, Vec<char>> = HashMap::new(); let isolated_form = if use_unshaped_instead_of_isolated { UNSHAPED } else { ISOLATED }; if text.len() < 3 { return text.to_string(); }; for letter in text.chars() { if HARAKAT_RE.find(&letter.to_string()).is_some() { let len = output.len(); if !delete_harakat { let mut position = (len - 1) as i16; if shift_harakat_position { position -= 1; } position_harakat.entry(position).or_insert_with(Vec::new); if shift_harakat_position { let v = position_harakat.entry(position).or_default(); v.insert(0, letter); } else { let v = position_harakat.entry(position).or_default(); v.push(letter); } } } else if letter == TATWEEL && delete_tatweel || letter == ZWJ && !support_zwj { } else if !LETTERS.contains_key(&letter) { output.push((letter, NOT_SUPPORTED)); } else if output.is_empty() { output.push((letter, isolated_form)); } else { let len = output.len(); let out_clone = output.clone(); let previous_letter = out_clone[len - 1]; if (previous_letter.1 == NOT_SUPPORTED) || (!connects_with_letter_before(letter)) || (!connects_with_letter_after(previous_letter.0)) || (previous_letter.1 == FINAL && !connects_with_letters_before_and_after(previous_letter.0)) { output.push((letter, isolated_form)); } else if previous_letter.1 == isolated_form { output[len - 1] = (previous_letter.0, INITIAL); output.push((letter, FINAL)); } else { output[len - 1] = (previous_letter.0, MEDIAL); output.push((letter, FINAL)); } } let len = output.len(); if support_zwj && output.len() > 1 && output[len - 2].0 == ZWJ { output.remove(len - 2); } } if support_zwj && !output.is_empty() && output[output.len() - 1].0 == ZWJ { output.pop(); } //adjust vector length to match text length adjust_len(&mut output); if self.configuration["support_ligatures"] { let mut text = HARAKAT_RE.replace_all(text, "").into_owned(); if delete_tatweel { text = text.replace(TATWEEL, ""); } for re_match in self.ligature_re().find_iter(&text) { let mut group_index = 4; for (index, letter_group) in self.ligature_re().as_str().split('|').enumerate() { if letter_group == re_match.as_str() { group_index = index; break; } } let (a, b) = (re_match.start(), re_match.end()); let forms = self.re_group_index_to_ligature_forms[&group_index]; let a_form = output[a].1; let b_form = output[b - 2].1; let ligature_form; // +-----------+----------+---------+---------+----------+ // | a \ b | ISOLATED | INITIAL | MEDIAL | FINAL | // +-----------+----------+---------+---------+----------+ // | ISOLATED | ISOLATED | INITIAL | INITIAL | ISOLATED | // | INITIAL | ISOLATED | INITIAL | INITIAL | ISOLATED | // | MEDIAL | FINAL | MEDIAL | MEDIAL | FINAL | // | FINAL | FINAL | MEDIAL | MEDIAL | FINAL | // +-----------+----------+---------+---------+----------+ if a_form == isolated_form || a_form == INITIAL { if b_form == isolated_form || b_form == FINAL { ligature_form = FINAL; } else { ligature_form = INITIAL; } } else if b_form == isolated_form || b_form == FINAL { ligature_form = FINAL; } else { ligature_form = MEDIAL; } if forms[ligature_form as usize].is_empty() { continue; } output[a] = ( forms[ligature_form as usize].chars().next().unwrap(), NOT_SUPPORTED, ); let v: Vec<(char, i16)> = repeat(EMPTY).take(b - 1 - a).collect(); let mut index = a + 1; let mut v_index = 0; while index != b { output[index] = v[v_index]; index += 1; v_index += 1; } } } let mut result = Vec::new(); if !delete_harakat && position_harakat.contains_key(&-1) { result.extend(position_harakat[&-1].clone()); } for (i, o) in output.iter().enumerate() { if o.0 != 'e' { if o.1 == NOT_SUPPORTED || o.1 == UNSHAPED { result.push(o.0); } else { let unc = LETTERS[&o.0][o.1 as usize]; result.push(unc.chars().next().unwrap()); } } if !delete_harakat && position_harakat.contains_key(&(i as i16)) { result.extend(position_harakat[&(i as i16)].clone()); } } let result: String = result.into_iter().collect(); result } fn ligature_re(&mut self) -> Regex { let mut index = 0; //const FORMS: i16 = 1; //const MATCH: i16 = 0; if self.re_group_index_to_ligature_forms.is_empty() { for ligature_record in LIGATURES.iter() { let (ligature, replacement) = ligature_record; if !self.configuration[*ligature] { continue; } self.re_group_index_to_ligature_forms .insert(index, replacement.1); self.patterns.push(replacement.0.to_string()); index += 1; } } Regex::new(&self.patterns.join("|")).unwrap() } } fn adjust_len(v: &mut Vec<(char, i16)>) { let mut idx = 0; let mut current_len = v.len(); while idx < current_len { let (char_o, _) = v[idx]; let len = char_o.len_utf8() - 1; for _ in 0..len { v.insert(idx + 1, EMPTY); idx += 1; } idx += 1; current_len = v.len(); } }
36.746781
156
0.471035
4a0ec7ce169fed882906217cc8f06fa26f72d7c4
586
#[derive(Debug, Serialize, Deserialize, PartialEq)] pub enum r#LogAuthenticationProvider { #[serde(rename = "OKTA_AUTHENTICATION_PROVIDER")] r#OktaAuthenticationProvider, #[serde(rename = "ACTIVE_DIRECTORY")] r#ActiveDirectory, #[serde(rename = "LDAP")] r#Ldap, #[serde(rename = "FEDERATION")] r#Federation, #[serde(rename = "SOCIAL")] r#Social, #[serde(rename = "FACTOR_PROVIDER")] r#FactorProvider, } impl Default for r#LogAuthenticationProvider { fn default() -> Self { r#LogAuthenticationProvider::OktaAuthenticationProvider } }
29.3
84
0.68942
2197538f0115991df909800512563f06c5b8cb2d
2,228
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::*; use libra_crypto; use language_common::{error_codes::*, tooling::fake_executor::Account}; use move_ir::{assert_error_type, assert_no_error}; use libra_types::account_address::AccountAddress; #[test] fn cant_send_transaction_with_old_key_after_rotation() { let mut test_env = TestEnvironment::default(); // Not a public key anyone can sign for let new_key = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef"; let program = format!( " import 0x0.LibraAccount; main() {{ let new_key; new_key = b\"{}\"; LibraAccount.rotate_authentication_key(move(new_key)); return; }}", new_key ); // rotate key assert_no_error!(test_env.run(to_standalone_script(program.as_bytes()))); // prologue will fail when signing with old key after rotation assert_error_type!( test_env.run(to_standalone_script(b"main() { return; }")), ErrorKind::AssertError(EBAD_ACCOUNT_AUTHENTICATION_KEY, _) ) } #[test] fn can_send_transaction_with_new_key_after_rotation() { let mut test_env = TestEnvironment::default(); let (privkey, pubkey) = compat::generate_keypair(&mut test_env.accounts.randomness_source); let program = format!( " import 0x0.LibraAccount; main() {{ let new_key; new_key = b\"{}\"; LibraAccount.rotate_authentication_key(move(new_key)); return; }}", hex::encode(AccountAddress::from_public_key(pubkey)) ); // rotate key assert_no_error!(test_env.run(to_standalone_script(program.as_bytes()))); // we need to use the new key in order to send a transaction let old_account = test_env.accounts.get_account(0); let new_account = Account { addr: old_account.addr, privkey, pubkey, }; let sequence_number = test_env.get_txn_sequence_number(0); let txn = test_env.create_signed_txn( to_standalone_script(b"main() { return; }"), old_account.addr, new_account, sequence_number, TestEnvironment::DEFAULT_MAX_GAS, TestEnvironment::DEFAULT_GAS_COST, ); assert_no_error!(test_env.run_txn(txn)) }
27.85
95
0.695691
d9262c7d973eb41b1622c7feceb0a0df1596378a
6,813
use futures::executor::block_on; use image::ImageFormat; use imgui::*; use imgui_wgpu::Renderer; use imgui_winit_support; use std::time::Instant; use winit::{ dpi::LogicalSize, event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent}, event_loop::{ControlFlow, EventLoop}, window::Window, }; fn main() { env_logger::init(); // Set up window and GPU let event_loop = EventLoop::new(); let mut hidpi_factor = 1.0; let (window, mut size, surface) = { let version = env!("CARGO_PKG_VERSION"); let window = Window::new(&event_loop).unwrap(); window.set_inner_size(LogicalSize { width: 1280.0, height: 720.0, }); window.set_title(&format!("imgui-wgpu {}", version)); let size = window.inner_size(); let surface = wgpu::Surface::create(&window); (window, size, surface) }; let adapter = block_on(wgpu::Adapter::request( &wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, compatible_surface: Some(&surface), }, wgpu::BackendBit::PRIMARY, )) .unwrap(); let (mut device, mut queue) = block_on(adapter.request_device(&wgpu::DeviceDescriptor { extensions: wgpu::Extensions { anisotropic_filtering: false, }, limits: wgpu::Limits::default(), })); // Set up swap chain let mut sc_desc = wgpu::SwapChainDescriptor { usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT, format: wgpu::TextureFormat::Bgra8Unorm, width: size.width as u32, height: size.height as u32, present_mode: wgpu::PresentMode::Mailbox, }; let mut swap_chain = device.create_swap_chain(&surface, &sc_desc); // Set up dear imgui let mut imgui = imgui::Context::create(); let mut platform = imgui_winit_support::WinitPlatform::init(&mut imgui); platform.attach_window( imgui.io_mut(), &window, imgui_winit_support::HiDpiMode::Default, ); imgui.set_ini_filename(None); let font_size = (13.0 * hidpi_factor) as f32; imgui.io_mut().font_global_scale = (1.0 / hidpi_factor) as f32; imgui.fonts().add_font(&[FontSource::DefaultFontData { config: Some(imgui::FontConfig { oversample_h: 1, pixel_snap_h: true, size_pixels: font_size, ..Default::default() }), }]); // // Set up dear imgui wgpu renderer // let clear_color = wgpu::Color { r: 0.1, g: 0.2, b: 0.3, a: 1.0, }; let mut renderer = Renderer::new( &mut imgui, &device, &mut queue, sc_desc.format, Some(clear_color), ); let mut last_frame = Instant::now(); // Set up Lenna texture let lenna_bytes = include_bytes!("../resources/Lenna.jpg"); let image = image::load_from_memory_with_format(lenna_bytes, ImageFormat::JPEG).expect("inavlid image"); let image = image.to_rgba(); let (width, height) = image.dimensions(); let raw_data = image.into_raw(); let lenna_texture_id = renderer.upload_texture(&device, &mut queue, &raw_data, width, height); // Event loop event_loop.run(move |event, _, control_flow| { *control_flow = if cfg!(feature = "metal-auto-capture") { ControlFlow::Exit } else { ControlFlow::Poll }; match event { Event::WindowEvent { event: WindowEvent::ScaleFactorChanged { scale_factor, .. }, .. } => { hidpi_factor = scale_factor; } Event::WindowEvent { event: WindowEvent::Resized(_), .. } => { size = window.inner_size(); sc_desc = wgpu::SwapChainDescriptor { usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT, format: wgpu::TextureFormat::Bgra8Unorm, width: size.width as u32, height: size.height as u32, present_mode: wgpu::PresentMode::Mailbox, }; swap_chain = device.create_swap_chain(&surface, &sc_desc); } Event::WindowEvent { event: WindowEvent::KeyboardInput { input: KeyboardInput { virtual_keycode: Some(VirtualKeyCode::Escape), state: ElementState::Pressed, .. }, .. }, .. } | Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => { *control_flow = ControlFlow::Exit; } Event::MainEventsCleared => { window.request_redraw(); } Event::RedrawEventsCleared => { last_frame = imgui.io_mut().update_delta_time(last_frame); let frame = match swap_chain.get_next_texture() { Ok(frame) => frame, Err(_) => { eprintln!("swapchain timed out"); return; } }; platform .prepare_frame(imgui.io_mut(), &window) .expect("Failed to prepare frame"); let ui = imgui.frame(); { let size = [width as f32, height as f32]; let window = imgui::Window::new(im_str!("Hello world")); window .size([400.0, 600.0], Condition::FirstUseEver) .build(&ui, || { ui.text(im_str!("Hello textures!")); ui.text(im_str!("Say hello to Lenna.jpg")); Image::new(lenna_texture_id, size).build(&ui); }); } let mut encoder: wgpu::CommandEncoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("render encoder"), }); platform.prepare_render(&ui, &window); renderer .render(ui.render(), &mut device, &mut encoder, &frame.view) .expect("Rendering failed"); queue.submit(&[encoder.finish()]); } _ => (), } platform.handle_event(imgui.io_mut(), &window, &event); }); }
32.442857
100
0.505211
ed574df58435267163d099bbdeabdd845a868d50
6,638
use tokio::sync::mpsc; use tokio::time::Instant; use tracing_futures::Instrument; use crate::core::CandidateState; use crate::core::RaftCore; use crate::core::State; use crate::error::VoteError; use crate::raft::VoteRequest; use crate::raft::VoteResponse; use crate::summary::MessageSummary; use crate::RaftNetwork; use crate::RaftNetworkFactory; use crate::RaftStorage; use crate::RaftTypeConfig; use crate::StorageError; impl<C: RaftTypeConfig, N: RaftNetworkFactory<C>, S: RaftStorage<C>> RaftCore<C, N, S> { /// An RPC invoked by candidates to gather votes (§5.2). /// /// See `receiver implementation: RequestVote RPC` in raft-essentials.md in this repo. #[tracing::instrument(level = "debug", skip(self, req), fields(req=%req.summary()))] pub(super) async fn handle_vote_request(&mut self, req: VoteRequest<C>) -> Result<VoteResponse<C>, VoteError<C>> { tracing::debug!( %req.vote, ?self.vote, "start handle_vote_request" ); let last_log_id = self.last_log_id; if req.vote < self.vote { tracing::debug!( %req.vote, ?self.vote, "RequestVote RPC term is less than current term" ); return Ok(VoteResponse { vote: self.vote, vote_granted: false, last_log_id, }); } // Do not respond to the request if we've received a heartbeat within the election timeout minimum. if let Some(inst) = &self.last_heartbeat { let now = Instant::now(); let delta = now.duration_since(*inst); if self.config.election_timeout_min >= (delta.as_millis() as u64) { tracing::debug!( %req.vote, ?delta, "rejecting vote request received within election timeout minimum" ); return Ok(VoteResponse { vote: self.vote, vote_granted: false, last_log_id, }); } } // Check if candidate's log is at least as up-to-date as this node's. // If candidate's log is not at least as up-to-date as this node, then reject. if req.last_log_id < last_log_id { tracing::debug!( %req.vote, "rejecting vote request as candidate's log is not up-to-date" ); return Ok(VoteResponse { vote: self.vote, vote_granted: false, last_log_id, }); } self.update_next_election_timeout(false); self.vote = req.vote; self.save_vote().await?; self.set_target_state(State::Follower); tracing::debug!(%req.vote, "voted for candidate"); Ok(VoteResponse { vote: self.vote, vote_granted: true, last_log_id, }) } } impl<'a, C: RaftTypeConfig, N: RaftNetworkFactory<C>, S: RaftStorage<C>> CandidateState<'a, C, N, S> { /// Handle response from a vote request sent to a peer. #[tracing::instrument(level = "debug", skip(self, res))] pub(super) async fn handle_vote_response( &mut self, res: VoteResponse<C>, target: C::NodeId, ) -> Result<(), StorageError<C>> { tracing::debug!(res=?res, target=display(target), "recv vote response"); // If peer's vote is greater than current vote, revert to follower state. if res.vote > self.core.vote { // If the core.vote is changed(to some greater value), then no further vote response would be valid. // Because they just granted an old `vote`. // A quorum does not mean the core is legal to use the new greater `vote`. // Thus no matter the last_log_id is greater than the remote peer or not, revert to follower at once. // TODO(xp): This is a simplified impl: revert to follower as soon as seeing a higher `last_log_id`. // When reverted to follower, it waits for heartbeat for 2 second before starting a new round of // election. self.core.set_target_state(State::Follower); tracing::debug!( id = %self.core.id, %res.vote, %self.core.vote, self_last_log_id=?self.core.last_log_id, res_last_log_id=?res.last_log_id, "reverting to follower state due to greater vote observed in RequestVote RPC response"); self.core.vote = res.vote; self.core.save_vote().await?; return Ok(()); } if res.vote_granted { self.granted.insert(target); if self.core.effective_membership.membership.is_majority(&self.granted) { tracing::debug!("transitioning to leader state as minimum number of votes have been received"); self.core.set_target_state(State::Leader); return Ok(()); } } // Otherwise, we just return and let the candidate loop wait for more votes to come in. Ok(()) } /// Spawn parallel vote requests to all cluster members. #[tracing::instrument(level = "trace", skip(self))] pub(super) async fn spawn_parallel_vote_requests(&mut self) -> mpsc::Receiver<(VoteResponse<C>, C::NodeId)> { let all_nodes = self.core.effective_membership.all_members().clone(); let (tx, rx) = mpsc::channel(all_nodes.len()); for member in all_nodes.into_iter().filter(|member| member != &self.core.id) { let rpc = VoteRequest::new(self.core.vote, self.core.last_log_id); let target_node = self.core.effective_membership.get_node(member).cloned(); let (mut network, tx_inner) = ( self.core.network.connect(member, target_node.as_ref()).await, tx.clone(), ); let _ = tokio::spawn( async move { let res = network.send_vote(rpc).await; match res { Ok(vote_resp) => { let _ = tx_inner.send((vote_resp, member)).await; } Err(err) => tracing::error!({error=%err, target=display(member)}, "while requesting vote"), } } .instrument(tracing::debug_span!("send_vote_req", target = display(member))), ); } rx } }
37.931429
118
0.559807
edd82b42876aafed6f28f3b768ac331b8e74c8d1
17,726
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub use syntax::diagnostic; use back::link; use driver::driver::{Input, FileInput, StrInput}; use driver::session::{Session, build_session}; use lint::Lint; use lint; use metadata; use std::any::AnyRefExt; use std::io; use std::os; use std::task::TaskBuilder; use syntax::ast; use syntax::parse; use syntax::diagnostic::Emitter; use syntax::diagnostics; use getopts; pub mod driver; pub mod session; pub mod config; pub mod pretty; pub fn run(args: Vec<String>) -> int { monitor(proc() run_compiler(args.as_slice())); 0 } static BUG_REPORT_URL: &'static str = "http://doc.rust-lang.org/complement-bugreport.html"; fn run_compiler(args: &[String]) { let matches = match handle_options(args.to_vec()) { Some(matches) => matches, None => return }; let descriptions = diagnostics::registry::Registry::new(super::DIAGNOSTICS); match matches.opt_str("explain") { Some(ref code) => { match descriptions.find_description(code.as_slice()) { Some(ref description) => { println!("{}", description); } None => { early_error(format!("no extended information for {}", code).as_slice()); } } return; }, None => () } let sopts = config::build_session_options(&matches); let (input, input_file_path) = match matches.free.len() { 0u => { if sopts.describe_lints { let mut ls = lint::LintStore::new(); ls.register_builtin(None); describe_lints(&ls, false); return; } early_error("no input filename given"); } 1u => { let ifile = matches.free[0].as_slice(); if ifile == "-" { let contents = io::stdin().read_to_end().unwrap(); let src = String::from_utf8(contents).unwrap(); (StrInput(src), None) } else { (FileInput(Path::new(ifile)), Some(Path::new(ifile))) } } _ => early_error("multiple input filenames provided") }; let sess = build_session(sopts, input_file_path, descriptions); let cfg = config::build_configuration(&sess); let odir = matches.opt_str("out-dir").map(|o| Path::new(o)); let ofile = matches.opt_str("o").map(|o| Path::new(o)); let pretty = matches.opt_default("pretty", "normal").map(|a| { pretty::parse_pretty(&sess, a.as_slice()) }); match pretty { Some((ppm, opt_uii)) => { pretty::pretty_print_input(sess, cfg, &input, ppm, opt_uii, ofile); return; } None => {/* continue */ } } let r = matches.opt_strs("Z"); if r.contains(&("ls".to_string())) { match input { FileInput(ref ifile) => { let mut stdout = io::stdout(); list_metadata(&sess, &(*ifile), &mut stdout).unwrap(); } StrInput(_) => { early_error("can not list metadata for stdin"); } } return; } if print_crate_info(&sess, &input, &odir, &ofile) { return; } driver::compile_input(sess, cfg, &input, &odir, &ofile, None); } /// Returns a version string such as "0.12.0-dev". pub fn release_str() -> Option<&'static str> { option_env!("CFG_RELEASE") } /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built. pub fn commit_hash_str() -> Option<&'static str> { option_env!("CFG_VER_HASH") } /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string. pub fn commit_date_str() -> Option<&'static str> { option_env!("CFG_VER_DATE") } /// Prints version information and returns None on success or an error /// message on failure. pub fn version(binary: &str, matches: &getopts::Matches) -> Option<String> { let verbose = match matches.opt_str("version").as_ref().map(|s| s.as_slice()) { None => false, Some("verbose") => true, Some(s) => return Some(format!("Unrecognized argument: {}", s)) }; println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version")); if verbose { fn unw(x: Option<&str>) -> &str { x.unwrap_or("unknown") } println!("binary: {}", binary); println!("commit-hash: {}", unw(commit_hash_str())); println!("commit-date: {}", unw(commit_date_str())); println!("host: {}", driver::host_triple()); println!("release: {}", unw(release_str())); } None } fn usage() { let message = format!("Usage: rustc [OPTIONS] INPUT"); println!("{}\n\ Additional help: -C help Print codegen options -W help Print 'lint' options and default settings -Z help Print internal options for debugging rustc\n", getopts::usage(message.as_slice(), config::optgroups().as_slice())); } fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) { println!(" Available lint options: -W <foo> Warn about <foo> -A <foo> Allow <foo> -D <foo> Deny <foo> -F <foo> Forbid <foo> (deny, and deny all overrides) "); fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> { let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect(); lints.sort_by(|x: &&Lint, y: &&Lint| { match x.default_level.cmp(&y.default_level) { // The sort doesn't case-fold but it's doubtful we care. Equal => x.name.cmp(y.name), r => r, } }); lints } fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>) -> Vec<(&'static str, Vec<lint::LintId>)> { let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect(); lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>), &(y, _): &(&'static str, Vec<lint::LintId>)| { x.cmp(y) }); lints } let (plugin, builtin) = lint_store.get_lints().partitioned(|&(_, p)| p); let plugin = sort_lints(plugin); let builtin = sort_lints(builtin); let (plugin_groups, builtin_groups) = lint_store.get_lint_groups().partitioned(|&(_, _, p)| p); let plugin_groups = sort_lint_groups(plugin_groups); let builtin_groups = sort_lint_groups(builtin_groups); let max_name_len = plugin.iter().chain(builtin.iter()) .map(|&s| s.name.width(true)) .max().unwrap_or(0); let padded = |x: &str| { let mut s = " ".repeat(max_name_len - x.char_len()); s.push_str(x); s }; println!("Lint checks provided by rustc:\n"); println!(" {} {:7.7s} {}", padded("name"), "default", "meaning"); println!(" {} {:7.7s} {}", padded("----"), "-------", "-------"); let print_lints = |lints: Vec<&Lint>| { for lint in lints.into_iter() { let name = lint.name_lower().replace("_", "-"); println!(" {} {:7.7s} {}", padded(name.as_slice()), lint.default_level.as_str(), lint.desc); } println!("\n"); }; print_lints(builtin); let max_name_len = plugin_groups.iter().chain(builtin_groups.iter()) .map(|&(s, _)| s.width(true)) .max().unwrap_or(0); let padded = |x: &str| { let mut s = " ".repeat(max_name_len - x.char_len()); s.push_str(x); s }; println!("Lint groups provided by rustc:\n"); println!(" {} {}", padded("name"), "sub-lints"); println!(" {} {}", padded("----"), "---------"); let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| { for (name, to) in lints.into_iter() { let name = name.chars().map(|x| x.to_lowercase()) .collect::<String>().replace("_", "-"); let desc = to.into_iter().map(|x| x.as_str().replace("_", "-")) .collect::<Vec<String>>().connect(", "); println!(" {} {}", padded(name.as_slice()), desc); } println!("\n"); }; print_lint_groups(builtin_groups); match (loaded_plugins, plugin.len(), plugin_groups.len()) { (false, 0, _) | (false, _, 0) => { println!("Compiler plugins can provide additional lints and lint groups. To see a \ listing of these, re-run `rustc -W help` with a crate filename."); } (false, _, _) => panic!("didn't load lint plugins but got them anyway!"), (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."), (true, l, g) => { if l > 0 { println!("Lint checks provided by plugins loaded by this crate:\n"); print_lints(plugin); } if g > 0 { println!("Lint groups provided by plugins loaded by this crate:\n"); print_lint_groups(plugin_groups); } } } } fn describe_debug_flags() { println!("\nAvailable debug options:\n"); let r = config::debugging_opts_map(); for tuple in r.iter() { match *tuple { (ref name, ref desc, _) => { println!(" -Z {:>20s} -- {}", *name, *desc); } } } } fn describe_codegen_flags() { println!("\nAvailable codegen options:\n"); let mut cg = config::basic_codegen_options(); for &(name, parser, desc) in config::CG_OPTIONS.iter() { // we invoke the parser function on `None` to see if this option needs // an argument or not. let (width, extra) = if parser(&mut cg, None) { (25, "") } else { (21, "=val") }; println!(" -C {:>width$s}{} -- {}", name.replace("_", "-"), extra, desc, width=width); } } /// Process command line options. Emits messages as appropriate. If compilation /// should continue, returns a getopts::Matches object parsed from args, otherwise /// returns None. pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> { // Throw away the first argument, the name of the binary let _binary = args.remove(0).unwrap(); if args.is_empty() { usage(); return None; } let matches = match getopts::getopts(args.as_slice(), config::optgroups().as_slice()) { Ok(m) => m, Err(f) => { early_error(f.to_string().as_slice()); } }; if matches.opt_present("h") || matches.opt_present("help") { usage(); return None; } // Don't handle -W help here, because we might first load plugins. let r = matches.opt_strs("Z"); if r.iter().any(|x| x.as_slice() == "help") { describe_debug_flags(); return None; } let cg_flags = matches.opt_strs("C"); if cg_flags.iter().any(|x| x.as_slice() == "help") { describe_codegen_flags(); return None; } if cg_flags.contains(&"passes=list".to_string()) { unsafe { ::llvm::LLVMRustPrintPasses(); } return None; } if matches.opt_present("version") { match version("rustc", &matches) { Some(err) => early_error(err.as_slice()), None => return None } } Some(matches) } fn print_crate_info(sess: &Session, input: &Input, odir: &Option<Path>, ofile: &Option<Path>) -> bool { let (crate_name, crate_file_name) = sess.opts.print_metas; // these nasty nested conditions are to avoid doing extra work if crate_name || crate_file_name { let attrs = parse_crate_attrs(sess, input); let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs.as_slice(), sess); let id = link::find_crate_name(Some(sess), attrs.as_slice(), input); if crate_name { println!("{}", id); } if crate_file_name { let crate_types = driver::collect_crate_types(sess, attrs.as_slice()); let metadata = driver::collect_crate_metadata(sess, attrs.as_slice()); *sess.crate_metadata.borrow_mut() = metadata; for &style in crate_types.iter() { let fname = link::filename_for_input(sess, style, id.as_slice(), &t_outputs.with_extension("")); println!("{}", fname.filename_display()); } } true } else { false } } fn parse_crate_attrs(sess: &Session, input: &Input) -> Vec<ast::Attribute> { let result = match *input { FileInput(ref ifile) => { parse::parse_crate_attrs_from_file(ifile, Vec::new(), &sess.parse_sess) } StrInput(ref src) => { parse::parse_crate_attrs_from_source_str( driver::anon_src().to_string(), src.to_string(), Vec::new(), &sess.parse_sess) } }; result.into_iter().collect() } pub fn early_error(msg: &str) -> ! { let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None); emitter.emit(None, msg, None, diagnostic::Fatal); panic!(diagnostic::FatalError); } pub fn early_warn(msg: &str) { let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None); emitter.emit(None, msg, None, diagnostic::Warning); } pub fn list_metadata(sess: &Session, path: &Path, out: &mut io::Writer) -> io::IoResult<()> { metadata::loader::list_file_metadata(sess.target.target.options.is_like_osx, path, out) } /// Run a procedure which will detect failures in the compiler and print nicer /// error messages rather than just failing the test. /// /// The diagnostic emitter yielded to the procedure should be used for reporting /// errors of the compiler. pub fn monitor(f: proc():Send) { // FIXME: This is a hack for newsched since it doesn't support split stacks. // rustc needs a lot of stack! When optimizations are disabled, it needs // even *more* stack than usual as well. #[cfg(rtopt)] static STACK_SIZE: uint = 6000000; // 6MB #[cfg(not(rtopt))] static STACK_SIZE: uint = 20000000; // 20MB let (tx, rx) = channel(); let w = io::ChanWriter::new(tx); let mut r = io::ChanReader::new(rx); let mut task = TaskBuilder::new().named("rustc").stderr(box w); // FIXME: Hacks on hacks. If the env is trying to override the stack size // then *don't* set it explicitly. if os::getenv("RUST_MIN_STACK").is_none() { task = task.stack_size(STACK_SIZE); } match task.try(f) { Ok(()) => { /* fallthrough */ } Err(value) => { // Task panicked without emitting a fatal diagnostic if !value.is::<diagnostic::FatalError>() { let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None); // a .span_bug or .bug call has already printed what // it wants to print. if !value.is::<diagnostic::ExplicitBug>() { emitter.emit( None, "unexpected panic", None, diagnostic::Bug); } let xs = [ "the compiler unexpectedly panicked. this is a bug.".to_string(), format!("we would appreciate a bug report: {}", BUG_REPORT_URL), "run with `RUST_BACKTRACE=1` for a backtrace".to_string(), ]; for note in xs.iter() { emitter.emit(None, note.as_slice(), None, diagnostic::Note) } match r.read_to_string() { Ok(s) => println!("{}", s), Err(e) => { emitter.emit(None, format!("failed to read internal \ stderr: {}", e).as_slice(), None, diagnostic::Error) } } } // Panic so the process returns a failure code, but don't pollute the // output with some unnecessary failure messages, we've already // printed everything that we needed to. io::stdio::set_stderr(box io::util::NullWriter); panic!(); } } }
34.419417
100
0.530012
0aa3f36d29cbb48dff6d720d42116b67fd8f2ba7
525
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern:1 == 2 fn main() { assert (1 == 2); }
32.8125
68
0.71619
b962e8cf6eb1c0393e2e11dc2e3cf5c10e61273e
3,366
use crate as btc_relay; use crate::{Config, Error}; use frame_support::{parameter_types, traits::GenesisBuild}; use mocktopus::mocking::clear_mocks; use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, }; pub const BITCOIN_CONFIRMATIONS: u32 = 6; pub const PARACHAIN_CONFIRMATIONS: u64 = 20; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>; type Block = frame_system::mocking::MockBlock<Test>; // Configure a mock runtime to test the pallet. frame_support::construct_runtime!( pub enum Test where Block = Block, NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Pallet, Call, Storage, Config, Event<T>}, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, // Operational BTCRelay: btc_relay::{Pallet, Call, Config<T>, Storage, Event<T>}, Security: security::{Pallet, Call, Storage, Event<T>}, } ); pub type AccountId = u64; pub type BlockNumber = u64; pub type Moment = u64; pub type Index = u64; parameter_types! { pub const BlockHashCount: u64 = 250; pub const SS58Prefix: u8 = 42; } impl frame_system::Config for Test { type BaseCallFilter = (); type BlockWeights = (); type BlockLength = (); type DbWeight = (); type Origin = Origin; type Call = Call; type Index = Index; type BlockNumber = BlockNumber; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = IdentityLookup<Self::AccountId>; type Header = Header; type Event = TestEvent; type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = SS58Prefix; type OnSetCode = (); } parameter_types! { pub const ParachainBlocksPerBitcoinBlock: BlockNumber = 100; } impl Config for Test { type Event = TestEvent; type ParachainBlocksPerBitcoinBlock = ParachainBlocksPerBitcoinBlock; type WeightInfo = (); } parameter_types! { pub const MinimumPeriod: Moment = 5; } impl pallet_timestamp::Config for Test { type Moment = Moment; type OnTimestampSet = (); type MinimumPeriod = MinimumPeriod; type WeightInfo = (); } impl security::Config for Test { type Event = TestEvent; } pub type TestEvent = Event; pub type TestError = Error<Test>; pub type SecurityError = security::Error<Test>; pub struct ExtBuilder; impl ExtBuilder { pub fn build() -> sp_io::TestExternalities { let mut storage = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap(); btc_relay::GenesisConfig::<Test> { bitcoin_confirmations: BITCOIN_CONFIRMATIONS, parachain_confirmations: PARACHAIN_CONFIRMATIONS, disable_difficulty_check: false, disable_inclusion_check: false, } .assimilate_storage(&mut storage) .unwrap(); sp_io::TestExternalities::from(storage) } } pub fn run_test<T>(test: T) where T: FnOnce(), { clear_mocks(); ExtBuilder::build().execute_with(|| { System::set_block_number(1); Security::set_active_block_number(1); test(); }); }
26.296875
98
0.669935
75f29ea64674c6104ae956f5adff9302bfe8573b
3,990
#[doc = "Register `NVIC_ISER` reader"] pub struct R(crate::R<NVIC_ISER_SPEC>); impl core::ops::Deref for R { type Target = crate::R<NVIC_ISER_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<NVIC_ISER_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<NVIC_ISER_SPEC>) -> Self { R(reader) } } #[doc = "Register `NVIC_ISER` writer"] pub struct W(crate::W<NVIC_ISER_SPEC>); impl core::ops::Deref for W { type Target = crate::W<NVIC_ISER_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<NVIC_ISER_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<NVIC_ISER_SPEC>) -> Self { W(writer) } } #[doc = "Field `SETENA` reader - Interrupt set-enable bits. Write: 0 = No effect. 1 = Enable interrupt. Read: 0 = Interrupt disabled. 1 = Interrupt enabled."] pub struct SETENA_R(crate::FieldReader<u32, u32>); impl SETENA_R { #[inline(always)] pub(crate) fn new(bits: u32) -> Self { SETENA_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for SETENA_R { type Target = crate::FieldReader<u32, u32>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `SETENA` writer - Interrupt set-enable bits. Write: 0 = No effect. 1 = Enable interrupt. Read: 0 = Interrupt disabled. 1 = Interrupt enabled."] pub struct SETENA_W<'a> { w: &'a mut W, } impl<'a> SETENA_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 - Interrupt set-enable bits. Write: 0 = No effect. 1 = Enable interrupt. Read: 0 = Interrupt disabled. 1 = Interrupt enabled."] #[inline(always)] pub fn setena(&self) -> SETENA_R { SETENA_R::new((self.bits & 0xffff_ffff) as u32) } } impl W { #[doc = "Bits 0:31 - Interrupt set-enable bits. Write: 0 = No effect. 1 = Enable interrupt. Read: 0 = Interrupt disabled. 1 = Interrupt enabled."] #[inline(always)] pub fn setena(&mut self) -> SETENA_W { SETENA_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 = "Use the Interrupt Set-Enable Register to enable interrupts and determine which interrupts are currently enabled. If a pending interrupt is enabled, the NVIC activates the interrupt based on its priority. If an interrupt is not enabled, asserting its interrupt signal changes the interrupt state to pending, but the NVIC never activates the interrupt, regardless of its priority. This 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). For information about available fields see [nvic_iser](index.html) module"] pub struct NVIC_ISER_SPEC; impl crate::RegisterSpec for NVIC_ISER_SPEC { type Ux = u32; } #[doc = "`read()` method returns [nvic_iser::R](R) reader structure"] impl crate::Readable for NVIC_ISER_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [nvic_iser::W](W) writer structure"] impl crate::Writable for NVIC_ISER_SPEC { type Writer = W; } #[doc = "`reset()` method sets NVIC_ISER to value 0"] impl crate::Resettable for NVIC_ISER_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
30
300
0.627318
ffccb4ce26f022a1f00091e65f8be01c1184b4a7
45,546
#[doc = "Register `PPS` reader"] pub struct R(crate::R<PPS_SPEC>); impl core::ops::Deref for R { type Target = crate::R<PPS_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<PPS_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<PPS_SPEC>) -> Self { R(reader) } } #[doc = "Register `PPS` writer"] pub struct W(crate::W<PPS_SPEC>); impl core::ops::Deref for W { type Target = crate::W<PPS_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<PPS_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<PPS_SPEC>) -> Self { W(writer) } } #[doc = "Port n Pin Power Save Bit 0\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PPS0_A { #[doc = "0: Pin Power Save of Pn.x is disabled."] VALUE1 = 0, #[doc = "1: Pin Power Save of Pn.x is enabled."] VALUE2 = 1, } impl From<PPS0_A> for bool { #[inline(always)] fn from(variant: PPS0_A) -> Self { variant as u8 != 0 } } #[doc = "Field `PPS0` reader - Port n Pin Power Save Bit 0"] pub struct PPS0_R(crate::FieldReader<bool, PPS0_A>); impl PPS0_R { pub(crate) fn new(bits: bool) -> Self { PPS0_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PPS0_A { match self.bits { false => PPS0_A::VALUE1, true => PPS0_A::VALUE2, } } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { **self == PPS0_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { **self == PPS0_A::VALUE2 } } impl core::ops::Deref for PPS0_R { type Target = crate::FieldReader<bool, PPS0_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `PPS0` writer - Port n Pin Power Save Bit 0"] pub struct PPS0_W<'a> { w: &'a mut W, } impl<'a> PPS0_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PPS0_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Pin Power Save of Pn.x is disabled."] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(PPS0_A::VALUE1) } #[doc = "Pin Power Save of Pn.x is enabled."] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(PPS0_A::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | (value as u32 & 0x01); self.w } } #[doc = "Port n Pin Power Save Bit 1\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PPS1_A { #[doc = "0: Pin Power Save of Pn.x is disabled."] VALUE1 = 0, #[doc = "1: Pin Power Save of Pn.x is enabled."] VALUE2 = 1, } impl From<PPS1_A> for bool { #[inline(always)] fn from(variant: PPS1_A) -> Self { variant as u8 != 0 } } #[doc = "Field `PPS1` reader - Port n Pin Power Save Bit 1"] pub struct PPS1_R(crate::FieldReader<bool, PPS1_A>); impl PPS1_R { pub(crate) fn new(bits: bool) -> Self { PPS1_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PPS1_A { match self.bits { false => PPS1_A::VALUE1, true => PPS1_A::VALUE2, } } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { **self == PPS1_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { **self == PPS1_A::VALUE2 } } impl core::ops::Deref for PPS1_R { type Target = crate::FieldReader<bool, PPS1_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `PPS1` writer - Port n Pin Power Save Bit 1"] pub struct PPS1_W<'a> { w: &'a mut W, } impl<'a> PPS1_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PPS1_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Pin Power Save of Pn.x is disabled."] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(PPS1_A::VALUE1) } #[doc = "Pin Power Save of Pn.x is enabled."] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(PPS1_A::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | ((value as u32 & 0x01) << 1); self.w } } #[doc = "Port n Pin Power Save Bit 2\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PPS2_A { #[doc = "0: Pin Power Save of Pn.x is disabled."] VALUE1 = 0, #[doc = "1: Pin Power Save of Pn.x is enabled."] VALUE2 = 1, } impl From<PPS2_A> for bool { #[inline(always)] fn from(variant: PPS2_A) -> Self { variant as u8 != 0 } } #[doc = "Field `PPS2` reader - Port n Pin Power Save Bit 2"] pub struct PPS2_R(crate::FieldReader<bool, PPS2_A>); impl PPS2_R { pub(crate) fn new(bits: bool) -> Self { PPS2_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PPS2_A { match self.bits { false => PPS2_A::VALUE1, true => PPS2_A::VALUE2, } } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { **self == PPS2_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { **self == PPS2_A::VALUE2 } } impl core::ops::Deref for PPS2_R { type Target = crate::FieldReader<bool, PPS2_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `PPS2` writer - Port n Pin Power Save Bit 2"] pub struct PPS2_W<'a> { w: &'a mut W, } impl<'a> PPS2_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PPS2_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Pin Power Save of Pn.x is disabled."] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(PPS2_A::VALUE1) } #[doc = "Pin Power Save of Pn.x is enabled."] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(PPS2_A::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | ((value as u32 & 0x01) << 2); self.w } } #[doc = "Port n Pin Power Save Bit 3\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PPS3_A { #[doc = "0: Pin Power Save of Pn.x is disabled."] VALUE1 = 0, #[doc = "1: Pin Power Save of Pn.x is enabled."] VALUE2 = 1, } impl From<PPS3_A> for bool { #[inline(always)] fn from(variant: PPS3_A) -> Self { variant as u8 != 0 } } #[doc = "Field `PPS3` reader - Port n Pin Power Save Bit 3"] pub struct PPS3_R(crate::FieldReader<bool, PPS3_A>); impl PPS3_R { pub(crate) fn new(bits: bool) -> Self { PPS3_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PPS3_A { match self.bits { false => PPS3_A::VALUE1, true => PPS3_A::VALUE2, } } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { **self == PPS3_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { **self == PPS3_A::VALUE2 } } impl core::ops::Deref for PPS3_R { type Target = crate::FieldReader<bool, PPS3_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `PPS3` writer - Port n Pin Power Save Bit 3"] pub struct PPS3_W<'a> { w: &'a mut W, } impl<'a> PPS3_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PPS3_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Pin Power Save of Pn.x is disabled."] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(PPS3_A::VALUE1) } #[doc = "Pin Power Save of Pn.x is enabled."] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(PPS3_A::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | ((value as u32 & 0x01) << 3); self.w } } #[doc = "Port n Pin Power Save Bit 4\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PPS4_A { #[doc = "0: Pin Power Save of Pn.x is disabled."] VALUE1 = 0, #[doc = "1: Pin Power Save of Pn.x is enabled."] VALUE2 = 1, } impl From<PPS4_A> for bool { #[inline(always)] fn from(variant: PPS4_A) -> Self { variant as u8 != 0 } } #[doc = "Field `PPS4` reader - Port n Pin Power Save Bit 4"] pub struct PPS4_R(crate::FieldReader<bool, PPS4_A>); impl PPS4_R { pub(crate) fn new(bits: bool) -> Self { PPS4_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PPS4_A { match self.bits { false => PPS4_A::VALUE1, true => PPS4_A::VALUE2, } } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { **self == PPS4_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { **self == PPS4_A::VALUE2 } } impl core::ops::Deref for PPS4_R { type Target = crate::FieldReader<bool, PPS4_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `PPS4` writer - Port n Pin Power Save Bit 4"] pub struct PPS4_W<'a> { w: &'a mut W, } impl<'a> PPS4_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PPS4_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Pin Power Save of Pn.x is disabled."] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(PPS4_A::VALUE1) } #[doc = "Pin Power Save of Pn.x is enabled."] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(PPS4_A::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | ((value as u32 & 0x01) << 4); self.w } } #[doc = "Port n Pin Power Save Bit 5\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PPS5_A { #[doc = "0: Pin Power Save of Pn.x is disabled."] VALUE1 = 0, #[doc = "1: Pin Power Save of Pn.x is enabled."] VALUE2 = 1, } impl From<PPS5_A> for bool { #[inline(always)] fn from(variant: PPS5_A) -> Self { variant as u8 != 0 } } #[doc = "Field `PPS5` reader - Port n Pin Power Save Bit 5"] pub struct PPS5_R(crate::FieldReader<bool, PPS5_A>); impl PPS5_R { pub(crate) fn new(bits: bool) -> Self { PPS5_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PPS5_A { match self.bits { false => PPS5_A::VALUE1, true => PPS5_A::VALUE2, } } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { **self == PPS5_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { **self == PPS5_A::VALUE2 } } impl core::ops::Deref for PPS5_R { type Target = crate::FieldReader<bool, PPS5_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `PPS5` writer - Port n Pin Power Save Bit 5"] pub struct PPS5_W<'a> { w: &'a mut W, } impl<'a> PPS5_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PPS5_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Pin Power Save of Pn.x is disabled."] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(PPS5_A::VALUE1) } #[doc = "Pin Power Save of Pn.x is enabled."] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(PPS5_A::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | ((value as u32 & 0x01) << 5); self.w } } #[doc = "Port n Pin Power Save Bit 6\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PPS6_A { #[doc = "0: Pin Power Save of Pn.x is disabled."] VALUE1 = 0, #[doc = "1: Pin Power Save of Pn.x is enabled."] VALUE2 = 1, } impl From<PPS6_A> for bool { #[inline(always)] fn from(variant: PPS6_A) -> Self { variant as u8 != 0 } } #[doc = "Field `PPS6` reader - Port n Pin Power Save Bit 6"] pub struct PPS6_R(crate::FieldReader<bool, PPS6_A>); impl PPS6_R { pub(crate) fn new(bits: bool) -> Self { PPS6_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PPS6_A { match self.bits { false => PPS6_A::VALUE1, true => PPS6_A::VALUE2, } } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { **self == PPS6_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { **self == PPS6_A::VALUE2 } } impl core::ops::Deref for PPS6_R { type Target = crate::FieldReader<bool, PPS6_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `PPS6` writer - Port n Pin Power Save Bit 6"] pub struct PPS6_W<'a> { w: &'a mut W, } impl<'a> PPS6_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PPS6_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Pin Power Save of Pn.x is disabled."] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(PPS6_A::VALUE1) } #[doc = "Pin Power Save of Pn.x is enabled."] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(PPS6_A::VALUE2) } #[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 << 6)) | ((value as u32 & 0x01) << 6); self.w } } #[doc = "Port n Pin Power Save Bit 7\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PPS7_A { #[doc = "0: Pin Power Save of Pn.x is disabled."] VALUE1 = 0, #[doc = "1: Pin Power Save of Pn.x is enabled."] VALUE2 = 1, } impl From<PPS7_A> for bool { #[inline(always)] fn from(variant: PPS7_A) -> Self { variant as u8 != 0 } } #[doc = "Field `PPS7` reader - Port n Pin Power Save Bit 7"] pub struct PPS7_R(crate::FieldReader<bool, PPS7_A>); impl PPS7_R { pub(crate) fn new(bits: bool) -> Self { PPS7_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PPS7_A { match self.bits { false => PPS7_A::VALUE1, true => PPS7_A::VALUE2, } } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { **self == PPS7_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { **self == PPS7_A::VALUE2 } } impl core::ops::Deref for PPS7_R { type Target = crate::FieldReader<bool, PPS7_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `PPS7` writer - Port n Pin Power Save Bit 7"] pub struct PPS7_W<'a> { w: &'a mut W, } impl<'a> PPS7_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PPS7_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Pin Power Save of Pn.x is disabled."] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(PPS7_A::VALUE1) } #[doc = "Pin Power Save of Pn.x is enabled."] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(PPS7_A::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | ((value as u32 & 0x01) << 7); self.w } } #[doc = "Port n Pin Power Save Bit 8\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PPS8_A { #[doc = "0: Pin Power Save of Pn.x is disabled."] VALUE1 = 0, #[doc = "1: Pin Power Save of Pn.x is enabled."] VALUE2 = 1, } impl From<PPS8_A> for bool { #[inline(always)] fn from(variant: PPS8_A) -> Self { variant as u8 != 0 } } #[doc = "Field `PPS8` reader - Port n Pin Power Save Bit 8"] pub struct PPS8_R(crate::FieldReader<bool, PPS8_A>); impl PPS8_R { pub(crate) fn new(bits: bool) -> Self { PPS8_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PPS8_A { match self.bits { false => PPS8_A::VALUE1, true => PPS8_A::VALUE2, } } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { **self == PPS8_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { **self == PPS8_A::VALUE2 } } impl core::ops::Deref for PPS8_R { type Target = crate::FieldReader<bool, PPS8_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `PPS8` writer - Port n Pin Power Save Bit 8"] pub struct PPS8_W<'a> { w: &'a mut W, } impl<'a> PPS8_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PPS8_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Pin Power Save of Pn.x is disabled."] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(PPS8_A::VALUE1) } #[doc = "Pin Power Save of Pn.x is enabled."] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(PPS8_A::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | ((value as u32 & 0x01) << 8); self.w } } #[doc = "Port n Pin Power Save Bit 9\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PPS9_A { #[doc = "0: Pin Power Save of Pn.x is disabled."] VALUE1 = 0, #[doc = "1: Pin Power Save of Pn.x is enabled."] VALUE2 = 1, } impl From<PPS9_A> for bool { #[inline(always)] fn from(variant: PPS9_A) -> Self { variant as u8 != 0 } } #[doc = "Field `PPS9` reader - Port n Pin Power Save Bit 9"] pub struct PPS9_R(crate::FieldReader<bool, PPS9_A>); impl PPS9_R { pub(crate) fn new(bits: bool) -> Self { PPS9_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PPS9_A { match self.bits { false => PPS9_A::VALUE1, true => PPS9_A::VALUE2, } } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { **self == PPS9_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { **self == PPS9_A::VALUE2 } } impl core::ops::Deref for PPS9_R { type Target = crate::FieldReader<bool, PPS9_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `PPS9` writer - Port n Pin Power Save Bit 9"] pub struct PPS9_W<'a> { w: &'a mut W, } impl<'a> PPS9_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PPS9_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Pin Power Save of Pn.x is disabled."] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(PPS9_A::VALUE1) } #[doc = "Pin Power Save of Pn.x is enabled."] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(PPS9_A::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | ((value as u32 & 0x01) << 9); self.w } } #[doc = "Port n Pin Power Save Bit 10\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PPS10_A { #[doc = "0: Pin Power Save of Pn.x is disabled."] VALUE1 = 0, #[doc = "1: Pin Power Save of Pn.x is enabled."] VALUE2 = 1, } impl From<PPS10_A> for bool { #[inline(always)] fn from(variant: PPS10_A) -> Self { variant as u8 != 0 } } #[doc = "Field `PPS10` reader - Port n Pin Power Save Bit 10"] pub struct PPS10_R(crate::FieldReader<bool, PPS10_A>); impl PPS10_R { pub(crate) fn new(bits: bool) -> Self { PPS10_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PPS10_A { match self.bits { false => PPS10_A::VALUE1, true => PPS10_A::VALUE2, } } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { **self == PPS10_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { **self == PPS10_A::VALUE2 } } impl core::ops::Deref for PPS10_R { type Target = crate::FieldReader<bool, PPS10_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `PPS10` writer - Port n Pin Power Save Bit 10"] pub struct PPS10_W<'a> { w: &'a mut W, } impl<'a> PPS10_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PPS10_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Pin Power Save of Pn.x is disabled."] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(PPS10_A::VALUE1) } #[doc = "Pin Power Save of Pn.x is enabled."] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(PPS10_A::VALUE2) } #[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 << 10)) | ((value as u32 & 0x01) << 10); self.w } } #[doc = "Port n Pin Power Save Bit 11\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PPS11_A { #[doc = "0: Pin Power Save of Pn.x is disabled."] VALUE1 = 0, #[doc = "1: Pin Power Save of Pn.x is enabled."] VALUE2 = 1, } impl From<PPS11_A> for bool { #[inline(always)] fn from(variant: PPS11_A) -> Self { variant as u8 != 0 } } #[doc = "Field `PPS11` reader - Port n Pin Power Save Bit 11"] pub struct PPS11_R(crate::FieldReader<bool, PPS11_A>); impl PPS11_R { pub(crate) fn new(bits: bool) -> Self { PPS11_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PPS11_A { match self.bits { false => PPS11_A::VALUE1, true => PPS11_A::VALUE2, } } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { **self == PPS11_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { **self == PPS11_A::VALUE2 } } impl core::ops::Deref for PPS11_R { type Target = crate::FieldReader<bool, PPS11_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `PPS11` writer - Port n Pin Power Save Bit 11"] pub struct PPS11_W<'a> { w: &'a mut W, } impl<'a> PPS11_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PPS11_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Pin Power Save of Pn.x is disabled."] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(PPS11_A::VALUE1) } #[doc = "Pin Power Save of Pn.x is enabled."] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(PPS11_A::VALUE2) } #[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 << 11)) | ((value as u32 & 0x01) << 11); self.w } } #[doc = "Port n Pin Power Save Bit 12\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PPS12_A { #[doc = "0: Pin Power Save of Pn.x is disabled."] VALUE1 = 0, #[doc = "1: Pin Power Save of Pn.x is enabled."] VALUE2 = 1, } impl From<PPS12_A> for bool { #[inline(always)] fn from(variant: PPS12_A) -> Self { variant as u8 != 0 } } #[doc = "Field `PPS12` reader - Port n Pin Power Save Bit 12"] pub struct PPS12_R(crate::FieldReader<bool, PPS12_A>); impl PPS12_R { pub(crate) fn new(bits: bool) -> Self { PPS12_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PPS12_A { match self.bits { false => PPS12_A::VALUE1, true => PPS12_A::VALUE2, } } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { **self == PPS12_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { **self == PPS12_A::VALUE2 } } impl core::ops::Deref for PPS12_R { type Target = crate::FieldReader<bool, PPS12_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `PPS12` writer - Port n Pin Power Save Bit 12"] pub struct PPS12_W<'a> { w: &'a mut W, } impl<'a> PPS12_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PPS12_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Pin Power Save of Pn.x is disabled."] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(PPS12_A::VALUE1) } #[doc = "Pin Power Save of Pn.x is enabled."] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(PPS12_A::VALUE2) } #[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 << 12)) | ((value as u32 & 0x01) << 12); self.w } } #[doc = "Port n Pin Power Save Bit 13\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PPS13_A { #[doc = "0: Pin Power Save of Pn.x is disabled."] VALUE1 = 0, #[doc = "1: Pin Power Save of Pn.x is enabled."] VALUE2 = 1, } impl From<PPS13_A> for bool { #[inline(always)] fn from(variant: PPS13_A) -> Self { variant as u8 != 0 } } #[doc = "Field `PPS13` reader - Port n Pin Power Save Bit 13"] pub struct PPS13_R(crate::FieldReader<bool, PPS13_A>); impl PPS13_R { pub(crate) fn new(bits: bool) -> Self { PPS13_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PPS13_A { match self.bits { false => PPS13_A::VALUE1, true => PPS13_A::VALUE2, } } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { **self == PPS13_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { **self == PPS13_A::VALUE2 } } impl core::ops::Deref for PPS13_R { type Target = crate::FieldReader<bool, PPS13_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `PPS13` writer - Port n Pin Power Save Bit 13"] pub struct PPS13_W<'a> { w: &'a mut W, } impl<'a> PPS13_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PPS13_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Pin Power Save of Pn.x is disabled."] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(PPS13_A::VALUE1) } #[doc = "Pin Power Save of Pn.x is enabled."] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(PPS13_A::VALUE2) } #[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 << 13)) | ((value as u32 & 0x01) << 13); self.w } } #[doc = "Port n Pin Power Save Bit 14\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PPS14_A { #[doc = "0: Pin Power Save of Pn.x is disabled."] VALUE1 = 0, #[doc = "1: Pin Power Save of Pn.x is enabled."] VALUE2 = 1, } impl From<PPS14_A> for bool { #[inline(always)] fn from(variant: PPS14_A) -> Self { variant as u8 != 0 } } #[doc = "Field `PPS14` reader - Port n Pin Power Save Bit 14"] pub struct PPS14_R(crate::FieldReader<bool, PPS14_A>); impl PPS14_R { pub(crate) fn new(bits: bool) -> Self { PPS14_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PPS14_A { match self.bits { false => PPS14_A::VALUE1, true => PPS14_A::VALUE2, } } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { **self == PPS14_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { **self == PPS14_A::VALUE2 } } impl core::ops::Deref for PPS14_R { type Target = crate::FieldReader<bool, PPS14_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `PPS14` writer - Port n Pin Power Save Bit 14"] pub struct PPS14_W<'a> { w: &'a mut W, } impl<'a> PPS14_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PPS14_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Pin Power Save of Pn.x is disabled."] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(PPS14_A::VALUE1) } #[doc = "Pin Power Save of Pn.x is enabled."] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(PPS14_A::VALUE2) } #[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 << 14)) | ((value as u32 & 0x01) << 14); self.w } } #[doc = "Port n Pin Power Save Bit 15\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PPS15_A { #[doc = "0: Pin Power Save of Pn.x is disabled."] VALUE1 = 0, #[doc = "1: Pin Power Save of Pn.x is enabled."] VALUE2 = 1, } impl From<PPS15_A> for bool { #[inline(always)] fn from(variant: PPS15_A) -> Self { variant as u8 != 0 } } #[doc = "Field `PPS15` reader - Port n Pin Power Save Bit 15"] pub struct PPS15_R(crate::FieldReader<bool, PPS15_A>); impl PPS15_R { pub(crate) fn new(bits: bool) -> Self { PPS15_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PPS15_A { match self.bits { false => PPS15_A::VALUE1, true => PPS15_A::VALUE2, } } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { **self == PPS15_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { **self == PPS15_A::VALUE2 } } impl core::ops::Deref for PPS15_R { type Target = crate::FieldReader<bool, PPS15_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `PPS15` writer - Port n Pin Power Save Bit 15"] pub struct PPS15_W<'a> { w: &'a mut W, } impl<'a> PPS15_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PPS15_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Pin Power Save of Pn.x is disabled."] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(PPS15_A::VALUE1) } #[doc = "Pin Power Save of Pn.x is enabled."] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(PPS15_A::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | ((value as u32 & 0x01) << 15); self.w } } impl R { #[doc = "Bit 0 - Port n Pin Power Save Bit 0"] #[inline(always)] pub fn pps0(&self) -> PPS0_R { PPS0_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - Port n Pin Power Save Bit 1"] #[inline(always)] pub fn pps1(&self) -> PPS1_R { PPS1_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - Port n Pin Power Save Bit 2"] #[inline(always)] pub fn pps2(&self) -> PPS2_R { PPS2_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - Port n Pin Power Save Bit 3"] #[inline(always)] pub fn pps3(&self) -> PPS3_R { PPS3_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - Port n Pin Power Save Bit 4"] #[inline(always)] pub fn pps4(&self) -> PPS4_R { PPS4_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - Port n Pin Power Save Bit 5"] #[inline(always)] pub fn pps5(&self) -> PPS5_R { PPS5_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - Port n Pin Power Save Bit 6"] #[inline(always)] pub fn pps6(&self) -> PPS6_R { PPS6_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - Port n Pin Power Save Bit 7"] #[inline(always)] pub fn pps7(&self) -> PPS7_R { PPS7_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - Port n Pin Power Save Bit 8"] #[inline(always)] pub fn pps8(&self) -> PPS8_R { PPS8_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - Port n Pin Power Save Bit 9"] #[inline(always)] pub fn pps9(&self) -> PPS9_R { PPS9_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 10 - Port n Pin Power Save Bit 10"] #[inline(always)] pub fn pps10(&self) -> PPS10_R { PPS10_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 11 - Port n Pin Power Save Bit 11"] #[inline(always)] pub fn pps11(&self) -> PPS11_R { PPS11_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 12 - Port n Pin Power Save Bit 12"] #[inline(always)] pub fn pps12(&self) -> PPS12_R { PPS12_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 13 - Port n Pin Power Save Bit 13"] #[inline(always)] pub fn pps13(&self) -> PPS13_R { PPS13_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 14 - Port n Pin Power Save Bit 14"] #[inline(always)] pub fn pps14(&self) -> PPS14_R { PPS14_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 15 - Port n Pin Power Save Bit 15"] #[inline(always)] pub fn pps15(&self) -> PPS15_R { PPS15_R::new(((self.bits >> 15) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Port n Pin Power Save Bit 0"] #[inline(always)] pub fn pps0(&mut self) -> PPS0_W { PPS0_W { w: self } } #[doc = "Bit 1 - Port n Pin Power Save Bit 1"] #[inline(always)] pub fn pps1(&mut self) -> PPS1_W { PPS1_W { w: self } } #[doc = "Bit 2 - Port n Pin Power Save Bit 2"] #[inline(always)] pub fn pps2(&mut self) -> PPS2_W { PPS2_W { w: self } } #[doc = "Bit 3 - Port n Pin Power Save Bit 3"] #[inline(always)] pub fn pps3(&mut self) -> PPS3_W { PPS3_W { w: self } } #[doc = "Bit 4 - Port n Pin Power Save Bit 4"] #[inline(always)] pub fn pps4(&mut self) -> PPS4_W { PPS4_W { w: self } } #[doc = "Bit 5 - Port n Pin Power Save Bit 5"] #[inline(always)] pub fn pps5(&mut self) -> PPS5_W { PPS5_W { w: self } } #[doc = "Bit 6 - Port n Pin Power Save Bit 6"] #[inline(always)] pub fn pps6(&mut self) -> PPS6_W { PPS6_W { w: self } } #[doc = "Bit 7 - Port n Pin Power Save Bit 7"] #[inline(always)] pub fn pps7(&mut self) -> PPS7_W { PPS7_W { w: self } } #[doc = "Bit 8 - Port n Pin Power Save Bit 8"] #[inline(always)] pub fn pps8(&mut self) -> PPS8_W { PPS8_W { w: self } } #[doc = "Bit 9 - Port n Pin Power Save Bit 9"] #[inline(always)] pub fn pps9(&mut self) -> PPS9_W { PPS9_W { w: self } } #[doc = "Bit 10 - Port n Pin Power Save Bit 10"] #[inline(always)] pub fn pps10(&mut self) -> PPS10_W { PPS10_W { w: self } } #[doc = "Bit 11 - Port n Pin Power Save Bit 11"] #[inline(always)] pub fn pps11(&mut self) -> PPS11_W { PPS11_W { w: self } } #[doc = "Bit 12 - Port n Pin Power Save Bit 12"] #[inline(always)] pub fn pps12(&mut self) -> PPS12_W { PPS12_W { w: self } } #[doc = "Bit 13 - Port n Pin Power Save Bit 13"] #[inline(always)] pub fn pps13(&mut self) -> PPS13_W { PPS13_W { w: self } } #[doc = "Bit 14 - Port n Pin Power Save Bit 14"] #[inline(always)] pub fn pps14(&mut self) -> PPS14_W { PPS14_W { w: self } } #[doc = "Bit 15 - Port n Pin Power Save Bit 15"] #[inline(always)] pub fn pps15(&mut self) -> PPS15_W { PPS15_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 = "Port 9 Pin Power Save Register\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 [pps](index.html) module"] pub struct PPS_SPEC; impl crate::RegisterSpec for PPS_SPEC { type Ux = u32; } #[doc = "`read()` method returns [pps::R](R) reader structure"] impl crate::Readable for PPS_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [pps::W](W) writer structure"] impl crate::Writable for PPS_SPEC { type Writer = W; } #[doc = "`reset()` method sets PPS to value 0"] impl crate::Resettable for PPS_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
29.290032
414
0.549928
f8b9d37a5cc4e757efe2960f1a1a804a62e839cd
113
// run-rustfix #![warn(clippy::redundant_closure_call)] #![allow(unused)] fn main() { let a = (|| 42)(); }
12.555556
40
0.575221
29f538f3d58240b406ca9cbba923c4f5231cfbba
234
//! Communication backends for [clients] to connect to the node software. //! //! These are pluggable and reusable modules wrapping specific libraries that perform network //! requests. //! //! [clients]: crate::client pub mod http;
26
93
0.730769
1d27f73a2e2795c7c235c1dae5c74e4cbf605bfe
4,012
use intcode_computer::Computer; fn main() { challenge_1(); challenge_2(); } fn challenge_1() { let computer = Computer::load_from_file("input"); println!( "Challenge 1: Number of points affected by tractor beam = {}", points_in_tractor_beam(computer, (50, 50)) ); } fn challenge_2() { let computer = Computer::load_from_file("input"); let mut scan_scale = 100; let mut point = None; while point.is_none() { let scan = scan_area(computer.clone(), (scan_scale, scan_scale)); point = fit_area((100, 100), scan); scan_scale *= 2; } let point = point.unwrap(); println!("Challenge 2: Value = {}", 10_000 * point.0 + point.1); } fn points_in_tractor_beam(computer: Computer, area: (usize, usize)) -> usize { let scan = scan_area(computer, area); scan.iter().fold(0, |acc, row| { acc + row .iter() .fold(0, |row_acc, v| row_acc + if *v { 1 } else { 0 }) }) } fn scan_area(computer: Computer, area: (usize, usize)) -> Vec<Vec<bool>> { let mut out = vec![]; for y in 0..area.1 { let mut row = vec![]; for x in 0..area.0 { let mut computer = computer.clone(); let (output, _) = computer.run(vec![x as i64, y as i64]); row.push(output[0] == 1); } out.push(row); } out } fn fit_area(area: (usize, usize), scan: Vec<Vec<bool>>) -> Option<(usize, usize)> { for (y, row) in scan.iter().enumerate() { let last_y = y + area.1 - 1; if last_y >= scan.len() { return None; } if let Some(x_in_beam_from_right) = row.iter().rev().position(|&v| v) { let last_x = row.len() - x_in_beam_from_right - 1; if last_x <= area.0 { continue; } let x = last_x - (area.0 - 1); if scan[y][x] && scan[last_y][x] { return Some((x, y)); } } } None } #[cfg(test)] mod test_day_19 { use super::*; #[test] fn computes_number_of_points_affected_by_the_tractor_beam() { let computer = Computer::load_from_file("../input"); assert!(points_in_tractor_beam(computer, (10, 10)) > 0); } #[test] fn finds_closest_point_that_fits_area() { let scan = " 1000000000000000000000000000000000000000 0100000000000000000000000000000000000000 0011000000000000000000000000000000000000 0001110000000000000000000000000000000000 0000111000000000000000000000000000000000 0000011110000000000000000000000000000000 0000001111100000000000000000000000000000 0000001111110000000000000000000000000000 0000000111111100000000000000000000000000 0000000011111111000000000000000000000000 0000000001111111110000000000000000000000 0000000000111111111000000000000000000000 0000000000011111111110000000000000000000 0000000000011111111111100000000000000000 0000000000001111111111110000000000000000 0000000000000111111111111100000000000000 0000000000000011111111111111000000000000 0000000000000001111111111111110000000000 0000000000000000111111111111111000000000 0000000000000000111111111111111110000000 0000000000000000011111111111111111100000 0000000000000000001111111111111111110000 0000000000000000000111111111111111111100 0000000000000000000011111111111111111111 0000000000000000000001111111111111111111 0000000000000000000001111111111111111111 0000000000000000000000111111111111111111 0000000000000000000000011111111111111111 0000000000000000000000001111111111111111 0000000000000000000000000111111111111111 0000000000000000000000000011111111111111 0000000000000000000000000011111111111111 0000000000000000000000000001111111111111 0000000000000000000000000000111111111111 0000000000000000000000000000011111111111" .trim(); let scan: Vec<Vec<_>> = scan .lines() .map(|l| l.chars().map(|c| c == '1').collect()) .collect(); assert_eq!(fit_area((10, 10), scan), Some((25, 20))); } }
31.34375
83
0.686441
ff3ea7501550360aa9c21ace91fdadde90d15bad
70,660
// This file is generated by rust-protobuf 2.25.1. Do not edit // @generated // https://github.com/rust-lang/rust-clippy/issues/702 #![allow(unknown_lints)] #![allow(clippy::all)] #![allow(unused_attributes)] #![cfg_attr(rustfmt, rustfmt::skip)] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] #![allow(unused_imports)] #![allow(unused_results)] //! Generated file from `perftest_data.proto` /// Generated files are compatible only with the same version /// of protobuf runtime. // const _PROTOBUF_VERSION_CHECK: () = ::protobuf::VERSION_2_25_1; #[derive(PartialEq,Clone,Default)] pub struct Test1 { // message fields value: ::std::option::Option<i32>, // special fields pub unknown_fields: ::protobuf::UnknownFields, pub cached_size: ::protobuf::CachedSize, } impl<'a> ::std::default::Default for &'a Test1 { fn default() -> &'a Test1 { <Test1 as ::protobuf::Message>::default_instance() } } impl Test1 { pub fn new() -> Test1 { ::std::default::Default::default() } // optional int32 value = 1; pub fn get_value(&self) -> i32 { self.value.unwrap_or(0) } pub fn clear_value(&mut self) { self.value = ::std::option::Option::None; } pub fn has_value(&self) -> bool { self.value.is_some() } // Param is passed by value, moved pub fn set_value(&mut self, v: i32) { self.value = ::std::option::Option::Some(v); } } impl ::protobuf::Message for Test1 { fn is_initialized(&self) -> bool { true } fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> { while !is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { if wire_type != ::protobuf::wire_format::WireTypeVarint { return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type)); } let tmp = is.read_int32()?; self.value = ::std::option::Option::Some(tmp); }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } // Compute sizes of nested messages #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; if let Some(v) = self.value { my_size += ::protobuf::rt::value_size(1, v, ::protobuf::wire_format::WireTypeVarint); } my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { if let Some(v) = self.value { os.write_int32(1, v)?; } os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &dyn (::std::any::Any) { self as &dyn (::std::any::Any) } fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { self as &mut dyn (::std::any::Any) } fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> Test1 { Test1::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_option_accessor::<_, ::protobuf::types::ProtobufTypeInt32>( "value", |m: &Test1| { &m.value }, |m: &mut Test1| { &mut m.value }, )); ::protobuf::reflect::MessageDescriptor::new_pb_name::<Test1>( "Test1", fields, file_descriptor_proto() ) }) } fn default_instance() -> &'static Test1 { static instance: ::protobuf::rt::LazyV2<Test1> = ::protobuf::rt::LazyV2::INIT; instance.get(Test1::new) } } impl ::protobuf::Clear for Test1 { fn clear(&mut self) { self.value = ::std::option::Option::None; self.unknown_fields.clear(); } } impl ::std::fmt::Debug for Test1 { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for Test1 { fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { ::protobuf::reflect::ReflectValueRef::Message(self) } } #[derive(PartialEq,Clone,Default)] pub struct TestRepeatedBool { // message fields pub values: ::std::vec::Vec<bool>, // special fields pub unknown_fields: ::protobuf::UnknownFields, pub cached_size: ::protobuf::CachedSize, } impl<'a> ::std::default::Default for &'a TestRepeatedBool { fn default() -> &'a TestRepeatedBool { <TestRepeatedBool as ::protobuf::Message>::default_instance() } } impl TestRepeatedBool { pub fn new() -> TestRepeatedBool { ::std::default::Default::default() } // repeated bool values = 1; pub fn get_values(&self) -> &[bool] { &self.values } pub fn clear_values(&mut self) { self.values.clear(); } // Param is passed by value, moved pub fn set_values(&mut self, v: ::std::vec::Vec<bool>) { self.values = v; } // Mutable pointer to the field. pub fn mut_values(&mut self) -> &mut ::std::vec::Vec<bool> { &mut self.values } // Take field pub fn take_values(&mut self) -> ::std::vec::Vec<bool> { ::std::mem::replace(&mut self.values, ::std::vec::Vec::new()) } } impl ::protobuf::Message for TestRepeatedBool { fn is_initialized(&self) -> bool { true } fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> { while !is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { ::protobuf::rt::read_repeated_bool_into(wire_type, is, &mut self.values)?; }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } // Compute sizes of nested messages #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; my_size += 2 * self.values.len() as u32; my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { for v in &self.values { os.write_bool(1, *v)?; }; os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &dyn (::std::any::Any) { self as &dyn (::std::any::Any) } fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { self as &mut dyn (::std::any::Any) } fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> TestRepeatedBool { TestRepeatedBool::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_vec_accessor::<_, ::protobuf::types::ProtobufTypeBool>( "values", |m: &TestRepeatedBool| { &m.values }, |m: &mut TestRepeatedBool| { &mut m.values }, )); ::protobuf::reflect::MessageDescriptor::new_pb_name::<TestRepeatedBool>( "TestRepeatedBool", fields, file_descriptor_proto() ) }) } fn default_instance() -> &'static TestRepeatedBool { static instance: ::protobuf::rt::LazyV2<TestRepeatedBool> = ::protobuf::rt::LazyV2::INIT; instance.get(TestRepeatedBool::new) } } impl ::protobuf::Clear for TestRepeatedBool { fn clear(&mut self) { self.values.clear(); self.unknown_fields.clear(); } } impl ::std::fmt::Debug for TestRepeatedBool { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for TestRepeatedBool { fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { ::protobuf::reflect::ReflectValueRef::Message(self) } } #[derive(PartialEq,Clone,Default)] pub struct TestRepeatedPackedInt32 { // message fields pub values: ::std::vec::Vec<i32>, // special fields pub unknown_fields: ::protobuf::UnknownFields, pub cached_size: ::protobuf::CachedSize, } impl<'a> ::std::default::Default for &'a TestRepeatedPackedInt32 { fn default() -> &'a TestRepeatedPackedInt32 { <TestRepeatedPackedInt32 as ::protobuf::Message>::default_instance() } } impl TestRepeatedPackedInt32 { pub fn new() -> TestRepeatedPackedInt32 { ::std::default::Default::default() } // repeated int32 values = 1; pub fn get_values(&self) -> &[i32] { &self.values } pub fn clear_values(&mut self) { self.values.clear(); } // Param is passed by value, moved pub fn set_values(&mut self, v: ::std::vec::Vec<i32>) { self.values = v; } // Mutable pointer to the field. pub fn mut_values(&mut self) -> &mut ::std::vec::Vec<i32> { &mut self.values } // Take field pub fn take_values(&mut self) -> ::std::vec::Vec<i32> { ::std::mem::replace(&mut self.values, ::std::vec::Vec::new()) } } impl ::protobuf::Message for TestRepeatedPackedInt32 { fn is_initialized(&self) -> bool { true } fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> { while !is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { ::protobuf::rt::read_repeated_int32_into(wire_type, is, &mut self.values)?; }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } // Compute sizes of nested messages #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; if !self.values.is_empty() { my_size += ::protobuf::rt::vec_packed_varint_size(1, &self.values); } my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { if !self.values.is_empty() { os.write_tag(1, ::protobuf::wire_format::WireTypeLengthDelimited)?; // TODO: Data size is computed again, it should be cached os.write_raw_varint32(::protobuf::rt::vec_packed_varint_data_size(&self.values))?; for v in &self.values { os.write_int32_no_tag(*v)?; }; } os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &dyn (::std::any::Any) { self as &dyn (::std::any::Any) } fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { self as &mut dyn (::std::any::Any) } fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> TestRepeatedPackedInt32 { TestRepeatedPackedInt32::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_vec_accessor::<_, ::protobuf::types::ProtobufTypeInt32>( "values", |m: &TestRepeatedPackedInt32| { &m.values }, |m: &mut TestRepeatedPackedInt32| { &mut m.values }, )); ::protobuf::reflect::MessageDescriptor::new_pb_name::<TestRepeatedPackedInt32>( "TestRepeatedPackedInt32", fields, file_descriptor_proto() ) }) } fn default_instance() -> &'static TestRepeatedPackedInt32 { static instance: ::protobuf::rt::LazyV2<TestRepeatedPackedInt32> = ::protobuf::rt::LazyV2::INIT; instance.get(TestRepeatedPackedInt32::new) } } impl ::protobuf::Clear for TestRepeatedPackedInt32 { fn clear(&mut self) { self.values.clear(); self.unknown_fields.clear(); } } impl ::std::fmt::Debug for TestRepeatedPackedInt32 { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for TestRepeatedPackedInt32 { fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { ::protobuf::reflect::ReflectValueRef::Message(self) } } #[derive(PartialEq,Clone,Default)] pub struct TestRepeatedMessages { // message fields pub messages1: ::protobuf::RepeatedField<TestRepeatedMessages>, pub messages2: ::protobuf::RepeatedField<TestRepeatedMessages>, pub messages3: ::protobuf::RepeatedField<TestRepeatedMessages>, // special fields pub unknown_fields: ::protobuf::UnknownFields, pub cached_size: ::protobuf::CachedSize, } impl<'a> ::std::default::Default for &'a TestRepeatedMessages { fn default() -> &'a TestRepeatedMessages { <TestRepeatedMessages as ::protobuf::Message>::default_instance() } } impl TestRepeatedMessages { pub fn new() -> TestRepeatedMessages { ::std::default::Default::default() } // repeated .perftest_data.TestRepeatedMessages messages1 = 1; pub fn get_messages1(&self) -> &[TestRepeatedMessages] { &self.messages1 } pub fn clear_messages1(&mut self) { self.messages1.clear(); } // Param is passed by value, moved pub fn set_messages1(&mut self, v: ::protobuf::RepeatedField<TestRepeatedMessages>) { self.messages1 = v; } // Mutable pointer to the field. pub fn mut_messages1(&mut self) -> &mut ::protobuf::RepeatedField<TestRepeatedMessages> { &mut self.messages1 } // Take field pub fn take_messages1(&mut self) -> ::protobuf::RepeatedField<TestRepeatedMessages> { ::std::mem::replace(&mut self.messages1, ::protobuf::RepeatedField::new()) } // repeated .perftest_data.TestRepeatedMessages messages2 = 2; pub fn get_messages2(&self) -> &[TestRepeatedMessages] { &self.messages2 } pub fn clear_messages2(&mut self) { self.messages2.clear(); } // Param is passed by value, moved pub fn set_messages2(&mut self, v: ::protobuf::RepeatedField<TestRepeatedMessages>) { self.messages2 = v; } // Mutable pointer to the field. pub fn mut_messages2(&mut self) -> &mut ::protobuf::RepeatedField<TestRepeatedMessages> { &mut self.messages2 } // Take field pub fn take_messages2(&mut self) -> ::protobuf::RepeatedField<TestRepeatedMessages> { ::std::mem::replace(&mut self.messages2, ::protobuf::RepeatedField::new()) } // repeated .perftest_data.TestRepeatedMessages messages3 = 3; pub fn get_messages3(&self) -> &[TestRepeatedMessages] { &self.messages3 } pub fn clear_messages3(&mut self) { self.messages3.clear(); } // Param is passed by value, moved pub fn set_messages3(&mut self, v: ::protobuf::RepeatedField<TestRepeatedMessages>) { self.messages3 = v; } // Mutable pointer to the field. pub fn mut_messages3(&mut self) -> &mut ::protobuf::RepeatedField<TestRepeatedMessages> { &mut self.messages3 } // Take field pub fn take_messages3(&mut self) -> ::protobuf::RepeatedField<TestRepeatedMessages> { ::std::mem::replace(&mut self.messages3, ::protobuf::RepeatedField::new()) } } impl ::protobuf::Message for TestRepeatedMessages { fn is_initialized(&self) -> bool { for v in &self.messages1 { if !v.is_initialized() { return false; } }; for v in &self.messages2 { if !v.is_initialized() { return false; } }; for v in &self.messages3 { if !v.is_initialized() { return false; } }; true } fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> { while !is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { ::protobuf::rt::read_repeated_message_into(wire_type, is, &mut self.messages1)?; }, 2 => { ::protobuf::rt::read_repeated_message_into(wire_type, is, &mut self.messages2)?; }, 3 => { ::protobuf::rt::read_repeated_message_into(wire_type, is, &mut self.messages3)?; }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } // Compute sizes of nested messages #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; for value in &self.messages1 { let len = value.compute_size(); my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len; }; for value in &self.messages2 { let len = value.compute_size(); my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len; }; for value in &self.messages3 { let len = value.compute_size(); my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len; }; my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { for v in &self.messages1 { os.write_tag(1, ::protobuf::wire_format::WireTypeLengthDelimited)?; os.write_raw_varint32(v.get_cached_size())?; v.write_to_with_cached_sizes(os)?; }; for v in &self.messages2 { os.write_tag(2, ::protobuf::wire_format::WireTypeLengthDelimited)?; os.write_raw_varint32(v.get_cached_size())?; v.write_to_with_cached_sizes(os)?; }; for v in &self.messages3 { os.write_tag(3, ::protobuf::wire_format::WireTypeLengthDelimited)?; os.write_raw_varint32(v.get_cached_size())?; v.write_to_with_cached_sizes(os)?; }; os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &dyn (::std::any::Any) { self as &dyn (::std::any::Any) } fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { self as &mut dyn (::std::any::Any) } fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> TestRepeatedMessages { TestRepeatedMessages::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_repeated_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<TestRepeatedMessages>>( "messages1", |m: &TestRepeatedMessages| { &m.messages1 }, |m: &mut TestRepeatedMessages| { &mut m.messages1 }, )); fields.push(::protobuf::reflect::accessor::make_repeated_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<TestRepeatedMessages>>( "messages2", |m: &TestRepeatedMessages| { &m.messages2 }, |m: &mut TestRepeatedMessages| { &mut m.messages2 }, )); fields.push(::protobuf::reflect::accessor::make_repeated_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<TestRepeatedMessages>>( "messages3", |m: &TestRepeatedMessages| { &m.messages3 }, |m: &mut TestRepeatedMessages| { &mut m.messages3 }, )); ::protobuf::reflect::MessageDescriptor::new_pb_name::<TestRepeatedMessages>( "TestRepeatedMessages", fields, file_descriptor_proto() ) }) } fn default_instance() -> &'static TestRepeatedMessages { static instance: ::protobuf::rt::LazyV2<TestRepeatedMessages> = ::protobuf::rt::LazyV2::INIT; instance.get(TestRepeatedMessages::new) } } impl ::protobuf::Clear for TestRepeatedMessages { fn clear(&mut self) { self.messages1.clear(); self.messages2.clear(); self.messages3.clear(); self.unknown_fields.clear(); } } impl ::std::fmt::Debug for TestRepeatedMessages { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for TestRepeatedMessages { fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { ::protobuf::reflect::ReflectValueRef::Message(self) } } #[derive(PartialEq,Clone,Default)] pub struct TestOptionalMessages { // message fields pub message1: ::protobuf::SingularPtrField<TestOptionalMessages>, pub message2: ::protobuf::SingularPtrField<TestOptionalMessages>, pub message3: ::protobuf::SingularPtrField<TestOptionalMessages>, // special fields pub unknown_fields: ::protobuf::UnknownFields, pub cached_size: ::protobuf::CachedSize, } impl<'a> ::std::default::Default for &'a TestOptionalMessages { fn default() -> &'a TestOptionalMessages { <TestOptionalMessages as ::protobuf::Message>::default_instance() } } impl TestOptionalMessages { pub fn new() -> TestOptionalMessages { ::std::default::Default::default() } // optional .perftest_data.TestOptionalMessages message1 = 1; pub fn get_message1(&self) -> &TestOptionalMessages { self.message1.as_ref().unwrap_or_else(|| <TestOptionalMessages as ::protobuf::Message>::default_instance()) } pub fn clear_message1(&mut self) { self.message1.clear(); } pub fn has_message1(&self) -> bool { self.message1.is_some() } // Param is passed by value, moved pub fn set_message1(&mut self, v: TestOptionalMessages) { self.message1 = ::protobuf::SingularPtrField::some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_message1(&mut self) -> &mut TestOptionalMessages { if self.message1.is_none() { self.message1.set_default(); } self.message1.as_mut().unwrap() } // Take field pub fn take_message1(&mut self) -> TestOptionalMessages { self.message1.take().unwrap_or_else(|| TestOptionalMessages::new()) } // optional .perftest_data.TestOptionalMessages message2 = 2; pub fn get_message2(&self) -> &TestOptionalMessages { self.message2.as_ref().unwrap_or_else(|| <TestOptionalMessages as ::protobuf::Message>::default_instance()) } pub fn clear_message2(&mut self) { self.message2.clear(); } pub fn has_message2(&self) -> bool { self.message2.is_some() } // Param is passed by value, moved pub fn set_message2(&mut self, v: TestOptionalMessages) { self.message2 = ::protobuf::SingularPtrField::some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_message2(&mut self) -> &mut TestOptionalMessages { if self.message2.is_none() { self.message2.set_default(); } self.message2.as_mut().unwrap() } // Take field pub fn take_message2(&mut self) -> TestOptionalMessages { self.message2.take().unwrap_or_else(|| TestOptionalMessages::new()) } // optional .perftest_data.TestOptionalMessages message3 = 3; pub fn get_message3(&self) -> &TestOptionalMessages { self.message3.as_ref().unwrap_or_else(|| <TestOptionalMessages as ::protobuf::Message>::default_instance()) } pub fn clear_message3(&mut self) { self.message3.clear(); } pub fn has_message3(&self) -> bool { self.message3.is_some() } // Param is passed by value, moved pub fn set_message3(&mut self, v: TestOptionalMessages) { self.message3 = ::protobuf::SingularPtrField::some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_message3(&mut self) -> &mut TestOptionalMessages { if self.message3.is_none() { self.message3.set_default(); } self.message3.as_mut().unwrap() } // Take field pub fn take_message3(&mut self) -> TestOptionalMessages { self.message3.take().unwrap_or_else(|| TestOptionalMessages::new()) } } impl ::protobuf::Message for TestOptionalMessages { fn is_initialized(&self) -> bool { for v in &self.message1 { if !v.is_initialized() { return false; } }; for v in &self.message2 { if !v.is_initialized() { return false; } }; for v in &self.message3 { if !v.is_initialized() { return false; } }; true } fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> { while !is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { ::protobuf::rt::read_singular_message_into(wire_type, is, &mut self.message1)?; }, 2 => { ::protobuf::rt::read_singular_message_into(wire_type, is, &mut self.message2)?; }, 3 => { ::protobuf::rt::read_singular_message_into(wire_type, is, &mut self.message3)?; }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } // Compute sizes of nested messages #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; if let Some(ref v) = self.message1.as_ref() { let len = v.compute_size(); my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len; } if let Some(ref v) = self.message2.as_ref() { let len = v.compute_size(); my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len; } if let Some(ref v) = self.message3.as_ref() { let len = v.compute_size(); my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len; } my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { if let Some(ref v) = self.message1.as_ref() { os.write_tag(1, ::protobuf::wire_format::WireTypeLengthDelimited)?; os.write_raw_varint32(v.get_cached_size())?; v.write_to_with_cached_sizes(os)?; } if let Some(ref v) = self.message2.as_ref() { os.write_tag(2, ::protobuf::wire_format::WireTypeLengthDelimited)?; os.write_raw_varint32(v.get_cached_size())?; v.write_to_with_cached_sizes(os)?; } if let Some(ref v) = self.message3.as_ref() { os.write_tag(3, ::protobuf::wire_format::WireTypeLengthDelimited)?; os.write_raw_varint32(v.get_cached_size())?; v.write_to_with_cached_sizes(os)?; } os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &dyn (::std::any::Any) { self as &dyn (::std::any::Any) } fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { self as &mut dyn (::std::any::Any) } fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> TestOptionalMessages { TestOptionalMessages::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_singular_ptr_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<TestOptionalMessages>>( "message1", |m: &TestOptionalMessages| { &m.message1 }, |m: &mut TestOptionalMessages| { &mut m.message1 }, )); fields.push(::protobuf::reflect::accessor::make_singular_ptr_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<TestOptionalMessages>>( "message2", |m: &TestOptionalMessages| { &m.message2 }, |m: &mut TestOptionalMessages| { &mut m.message2 }, )); fields.push(::protobuf::reflect::accessor::make_singular_ptr_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<TestOptionalMessages>>( "message3", |m: &TestOptionalMessages| { &m.message3 }, |m: &mut TestOptionalMessages| { &mut m.message3 }, )); ::protobuf::reflect::MessageDescriptor::new_pb_name::<TestOptionalMessages>( "TestOptionalMessages", fields, file_descriptor_proto() ) }) } fn default_instance() -> &'static TestOptionalMessages { static instance: ::protobuf::rt::LazyV2<TestOptionalMessages> = ::protobuf::rt::LazyV2::INIT; instance.get(TestOptionalMessages::new) } } impl ::protobuf::Clear for TestOptionalMessages { fn clear(&mut self) { self.message1.clear(); self.message2.clear(); self.message3.clear(); self.unknown_fields.clear(); } } impl ::std::fmt::Debug for TestOptionalMessages { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for TestOptionalMessages { fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { ::protobuf::reflect::ReflectValueRef::Message(self) } } #[derive(PartialEq,Clone,Default)] pub struct TestStrings { // message fields s1: ::protobuf::SingularField<::std::string::String>, s2: ::protobuf::SingularField<::std::string::String>, s3: ::protobuf::SingularField<::std::string::String>, // special fields pub unknown_fields: ::protobuf::UnknownFields, pub cached_size: ::protobuf::CachedSize, } impl<'a> ::std::default::Default for &'a TestStrings { fn default() -> &'a TestStrings { <TestStrings as ::protobuf::Message>::default_instance() } } impl TestStrings { pub fn new() -> TestStrings { ::std::default::Default::default() } // optional string s1 = 1; pub fn get_s1(&self) -> &str { match self.s1.as_ref() { Some(v) => &v, None => "", } } pub fn clear_s1(&mut self) { self.s1.clear(); } pub fn has_s1(&self) -> bool { self.s1.is_some() } // Param is passed by value, moved pub fn set_s1(&mut self, v: ::std::string::String) { self.s1 = ::protobuf::SingularField::some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_s1(&mut self) -> &mut ::std::string::String { if self.s1.is_none() { self.s1.set_default(); } self.s1.as_mut().unwrap() } // Take field pub fn take_s1(&mut self) -> ::std::string::String { self.s1.take().unwrap_or_else(|| ::std::string::String::new()) } // optional string s2 = 2; pub fn get_s2(&self) -> &str { match self.s2.as_ref() { Some(v) => &v, None => "", } } pub fn clear_s2(&mut self) { self.s2.clear(); } pub fn has_s2(&self) -> bool { self.s2.is_some() } // Param is passed by value, moved pub fn set_s2(&mut self, v: ::std::string::String) { self.s2 = ::protobuf::SingularField::some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_s2(&mut self) -> &mut ::std::string::String { if self.s2.is_none() { self.s2.set_default(); } self.s2.as_mut().unwrap() } // Take field pub fn take_s2(&mut self) -> ::std::string::String { self.s2.take().unwrap_or_else(|| ::std::string::String::new()) } // optional string s3 = 3; pub fn get_s3(&self) -> &str { match self.s3.as_ref() { Some(v) => &v, None => "", } } pub fn clear_s3(&mut self) { self.s3.clear(); } pub fn has_s3(&self) -> bool { self.s3.is_some() } // Param is passed by value, moved pub fn set_s3(&mut self, v: ::std::string::String) { self.s3 = ::protobuf::SingularField::some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_s3(&mut self) -> &mut ::std::string::String { if self.s3.is_none() { self.s3.set_default(); } self.s3.as_mut().unwrap() } // Take field pub fn take_s3(&mut self) -> ::std::string::String { self.s3.take().unwrap_or_else(|| ::std::string::String::new()) } } impl ::protobuf::Message for TestStrings { fn is_initialized(&self) -> bool { true } fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> { while !is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { ::protobuf::rt::read_singular_string_into(wire_type, is, &mut self.s1)?; }, 2 => { ::protobuf::rt::read_singular_string_into(wire_type, is, &mut self.s2)?; }, 3 => { ::protobuf::rt::read_singular_string_into(wire_type, is, &mut self.s3)?; }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } // Compute sizes of nested messages #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; if let Some(ref v) = self.s1.as_ref() { my_size += ::protobuf::rt::string_size(1, &v); } if let Some(ref v) = self.s2.as_ref() { my_size += ::protobuf::rt::string_size(2, &v); } if let Some(ref v) = self.s3.as_ref() { my_size += ::protobuf::rt::string_size(3, &v); } my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { if let Some(ref v) = self.s1.as_ref() { os.write_string(1, &v)?; } if let Some(ref v) = self.s2.as_ref() { os.write_string(2, &v)?; } if let Some(ref v) = self.s3.as_ref() { os.write_string(3, &v)?; } os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &dyn (::std::any::Any) { self as &dyn (::std::any::Any) } fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { self as &mut dyn (::std::any::Any) } fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> TestStrings { TestStrings::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_singular_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( "s1", |m: &TestStrings| { &m.s1 }, |m: &mut TestStrings| { &mut m.s1 }, )); fields.push(::protobuf::reflect::accessor::make_singular_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( "s2", |m: &TestStrings| { &m.s2 }, |m: &mut TestStrings| { &mut m.s2 }, )); fields.push(::protobuf::reflect::accessor::make_singular_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( "s3", |m: &TestStrings| { &m.s3 }, |m: &mut TestStrings| { &mut m.s3 }, )); ::protobuf::reflect::MessageDescriptor::new_pb_name::<TestStrings>( "TestStrings", fields, file_descriptor_proto() ) }) } fn default_instance() -> &'static TestStrings { static instance: ::protobuf::rt::LazyV2<TestStrings> = ::protobuf::rt::LazyV2::INIT; instance.get(TestStrings::new) } } impl ::protobuf::Clear for TestStrings { fn clear(&mut self) { self.s1.clear(); self.s2.clear(); self.s3.clear(); self.unknown_fields.clear(); } } impl ::std::fmt::Debug for TestStrings { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for TestStrings { fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { ::protobuf::reflect::ReflectValueRef::Message(self) } } #[derive(PartialEq,Clone,Default)] pub struct TestBytes { // message fields b1: ::protobuf::SingularField<::std::vec::Vec<u8>>, // special fields pub unknown_fields: ::protobuf::UnknownFields, pub cached_size: ::protobuf::CachedSize, } impl<'a> ::std::default::Default for &'a TestBytes { fn default() -> &'a TestBytes { <TestBytes as ::protobuf::Message>::default_instance() } } impl TestBytes { pub fn new() -> TestBytes { ::std::default::Default::default() } // optional bytes b1 = 1; pub fn get_b1(&self) -> &[u8] { match self.b1.as_ref() { Some(v) => &v, None => &[], } } pub fn clear_b1(&mut self) { self.b1.clear(); } pub fn has_b1(&self) -> bool { self.b1.is_some() } // Param is passed by value, moved pub fn set_b1(&mut self, v: ::std::vec::Vec<u8>) { self.b1 = ::protobuf::SingularField::some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_b1(&mut self) -> &mut ::std::vec::Vec<u8> { if self.b1.is_none() { self.b1.set_default(); } self.b1.as_mut().unwrap() } // Take field pub fn take_b1(&mut self) -> ::std::vec::Vec<u8> { self.b1.take().unwrap_or_else(|| ::std::vec::Vec::new()) } } impl ::protobuf::Message for TestBytes { fn is_initialized(&self) -> bool { true } fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> { while !is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { ::protobuf::rt::read_singular_bytes_into(wire_type, is, &mut self.b1)?; }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } // Compute sizes of nested messages #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; if let Some(ref v) = self.b1.as_ref() { my_size += ::protobuf::rt::bytes_size(1, &v); } my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { if let Some(ref v) = self.b1.as_ref() { os.write_bytes(1, &v)?; } os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &dyn (::std::any::Any) { self as &dyn (::std::any::Any) } fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { self as &mut dyn (::std::any::Any) } fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> TestBytes { TestBytes::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_singular_field_accessor::<_, ::protobuf::types::ProtobufTypeBytes>( "b1", |m: &TestBytes| { &m.b1 }, |m: &mut TestBytes| { &mut m.b1 }, )); ::protobuf::reflect::MessageDescriptor::new_pb_name::<TestBytes>( "TestBytes", fields, file_descriptor_proto() ) }) } fn default_instance() -> &'static TestBytes { static instance: ::protobuf::rt::LazyV2<TestBytes> = ::protobuf::rt::LazyV2::INIT; instance.get(TestBytes::new) } } impl ::protobuf::Clear for TestBytes { fn clear(&mut self) { self.b1.clear(); self.unknown_fields.clear(); } } impl ::std::fmt::Debug for TestBytes { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for TestBytes { fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { ::protobuf::reflect::ReflectValueRef::Message(self) } } #[derive(PartialEq,Clone,Default)] pub struct PerftestData { // message fields pub test1: ::protobuf::RepeatedField<Test1>, pub test_repeated_bool: ::protobuf::RepeatedField<TestRepeatedBool>, pub test_repeated_messages: ::protobuf::RepeatedField<TestRepeatedMessages>, pub test_optional_messages: ::protobuf::RepeatedField<TestOptionalMessages>, pub test_strings: ::protobuf::RepeatedField<TestStrings>, pub test_repeated_packed_int32: ::protobuf::RepeatedField<TestRepeatedPackedInt32>, pub test_small_bytearrays: ::protobuf::RepeatedField<TestBytes>, pub test_large_bytearrays: ::protobuf::RepeatedField<TestBytes>, // special fields pub unknown_fields: ::protobuf::UnknownFields, pub cached_size: ::protobuf::CachedSize, } impl<'a> ::std::default::Default for &'a PerftestData { fn default() -> &'a PerftestData { <PerftestData as ::protobuf::Message>::default_instance() } } impl PerftestData { pub fn new() -> PerftestData { ::std::default::Default::default() } // repeated .perftest_data.Test1 test1 = 1; pub fn get_test1(&self) -> &[Test1] { &self.test1 } pub fn clear_test1(&mut self) { self.test1.clear(); } // Param is passed by value, moved pub fn set_test1(&mut self, v: ::protobuf::RepeatedField<Test1>) { self.test1 = v; } // Mutable pointer to the field. pub fn mut_test1(&mut self) -> &mut ::protobuf::RepeatedField<Test1> { &mut self.test1 } // Take field pub fn take_test1(&mut self) -> ::protobuf::RepeatedField<Test1> { ::std::mem::replace(&mut self.test1, ::protobuf::RepeatedField::new()) } // repeated .perftest_data.TestRepeatedBool test_repeated_bool = 2; pub fn get_test_repeated_bool(&self) -> &[TestRepeatedBool] { &self.test_repeated_bool } pub fn clear_test_repeated_bool(&mut self) { self.test_repeated_bool.clear(); } // Param is passed by value, moved pub fn set_test_repeated_bool(&mut self, v: ::protobuf::RepeatedField<TestRepeatedBool>) { self.test_repeated_bool = v; } // Mutable pointer to the field. pub fn mut_test_repeated_bool(&mut self) -> &mut ::protobuf::RepeatedField<TestRepeatedBool> { &mut self.test_repeated_bool } // Take field pub fn take_test_repeated_bool(&mut self) -> ::protobuf::RepeatedField<TestRepeatedBool> { ::std::mem::replace(&mut self.test_repeated_bool, ::protobuf::RepeatedField::new()) } // repeated .perftest_data.TestRepeatedMessages test_repeated_messages = 3; pub fn get_test_repeated_messages(&self) -> &[TestRepeatedMessages] { &self.test_repeated_messages } pub fn clear_test_repeated_messages(&mut self) { self.test_repeated_messages.clear(); } // Param is passed by value, moved pub fn set_test_repeated_messages(&mut self, v: ::protobuf::RepeatedField<TestRepeatedMessages>) { self.test_repeated_messages = v; } // Mutable pointer to the field. pub fn mut_test_repeated_messages(&mut self) -> &mut ::protobuf::RepeatedField<TestRepeatedMessages> { &mut self.test_repeated_messages } // Take field pub fn take_test_repeated_messages(&mut self) -> ::protobuf::RepeatedField<TestRepeatedMessages> { ::std::mem::replace(&mut self.test_repeated_messages, ::protobuf::RepeatedField::new()) } // repeated .perftest_data.TestOptionalMessages test_optional_messages = 4; pub fn get_test_optional_messages(&self) -> &[TestOptionalMessages] { &self.test_optional_messages } pub fn clear_test_optional_messages(&mut self) { self.test_optional_messages.clear(); } // Param is passed by value, moved pub fn set_test_optional_messages(&mut self, v: ::protobuf::RepeatedField<TestOptionalMessages>) { self.test_optional_messages = v; } // Mutable pointer to the field. pub fn mut_test_optional_messages(&mut self) -> &mut ::protobuf::RepeatedField<TestOptionalMessages> { &mut self.test_optional_messages } // Take field pub fn take_test_optional_messages(&mut self) -> ::protobuf::RepeatedField<TestOptionalMessages> { ::std::mem::replace(&mut self.test_optional_messages, ::protobuf::RepeatedField::new()) } // repeated .perftest_data.TestStrings test_strings = 5; pub fn get_test_strings(&self) -> &[TestStrings] { &self.test_strings } pub fn clear_test_strings(&mut self) { self.test_strings.clear(); } // Param is passed by value, moved pub fn set_test_strings(&mut self, v: ::protobuf::RepeatedField<TestStrings>) { self.test_strings = v; } // Mutable pointer to the field. pub fn mut_test_strings(&mut self) -> &mut ::protobuf::RepeatedField<TestStrings> { &mut self.test_strings } // Take field pub fn take_test_strings(&mut self) -> ::protobuf::RepeatedField<TestStrings> { ::std::mem::replace(&mut self.test_strings, ::protobuf::RepeatedField::new()) } // repeated .perftest_data.TestRepeatedPackedInt32 test_repeated_packed_int32 = 6; pub fn get_test_repeated_packed_int32(&self) -> &[TestRepeatedPackedInt32] { &self.test_repeated_packed_int32 } pub fn clear_test_repeated_packed_int32(&mut self) { self.test_repeated_packed_int32.clear(); } // Param is passed by value, moved pub fn set_test_repeated_packed_int32(&mut self, v: ::protobuf::RepeatedField<TestRepeatedPackedInt32>) { self.test_repeated_packed_int32 = v; } // Mutable pointer to the field. pub fn mut_test_repeated_packed_int32(&mut self) -> &mut ::protobuf::RepeatedField<TestRepeatedPackedInt32> { &mut self.test_repeated_packed_int32 } // Take field pub fn take_test_repeated_packed_int32(&mut self) -> ::protobuf::RepeatedField<TestRepeatedPackedInt32> { ::std::mem::replace(&mut self.test_repeated_packed_int32, ::protobuf::RepeatedField::new()) } // repeated .perftest_data.TestBytes test_small_bytearrays = 7; pub fn get_test_small_bytearrays(&self) -> &[TestBytes] { &self.test_small_bytearrays } pub fn clear_test_small_bytearrays(&mut self) { self.test_small_bytearrays.clear(); } // Param is passed by value, moved pub fn set_test_small_bytearrays(&mut self, v: ::protobuf::RepeatedField<TestBytes>) { self.test_small_bytearrays = v; } // Mutable pointer to the field. pub fn mut_test_small_bytearrays(&mut self) -> &mut ::protobuf::RepeatedField<TestBytes> { &mut self.test_small_bytearrays } // Take field pub fn take_test_small_bytearrays(&mut self) -> ::protobuf::RepeatedField<TestBytes> { ::std::mem::replace(&mut self.test_small_bytearrays, ::protobuf::RepeatedField::new()) } // repeated .perftest_data.TestBytes test_large_bytearrays = 8; pub fn get_test_large_bytearrays(&self) -> &[TestBytes] { &self.test_large_bytearrays } pub fn clear_test_large_bytearrays(&mut self) { self.test_large_bytearrays.clear(); } // Param is passed by value, moved pub fn set_test_large_bytearrays(&mut self, v: ::protobuf::RepeatedField<TestBytes>) { self.test_large_bytearrays = v; } // Mutable pointer to the field. pub fn mut_test_large_bytearrays(&mut self) -> &mut ::protobuf::RepeatedField<TestBytes> { &mut self.test_large_bytearrays } // Take field pub fn take_test_large_bytearrays(&mut self) -> ::protobuf::RepeatedField<TestBytes> { ::std::mem::replace(&mut self.test_large_bytearrays, ::protobuf::RepeatedField::new()) } } impl ::protobuf::Message for PerftestData { fn is_initialized(&self) -> bool { for v in &self.test1 { if !v.is_initialized() { return false; } }; for v in &self.test_repeated_bool { if !v.is_initialized() { return false; } }; for v in &self.test_repeated_messages { if !v.is_initialized() { return false; } }; for v in &self.test_optional_messages { if !v.is_initialized() { return false; } }; for v in &self.test_strings { if !v.is_initialized() { return false; } }; for v in &self.test_repeated_packed_int32 { if !v.is_initialized() { return false; } }; for v in &self.test_small_bytearrays { if !v.is_initialized() { return false; } }; for v in &self.test_large_bytearrays { if !v.is_initialized() { return false; } }; true } fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> { while !is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { ::protobuf::rt::read_repeated_message_into(wire_type, is, &mut self.test1)?; }, 2 => { ::protobuf::rt::read_repeated_message_into(wire_type, is, &mut self.test_repeated_bool)?; }, 3 => { ::protobuf::rt::read_repeated_message_into(wire_type, is, &mut self.test_repeated_messages)?; }, 4 => { ::protobuf::rt::read_repeated_message_into(wire_type, is, &mut self.test_optional_messages)?; }, 5 => { ::protobuf::rt::read_repeated_message_into(wire_type, is, &mut self.test_strings)?; }, 6 => { ::protobuf::rt::read_repeated_message_into(wire_type, is, &mut self.test_repeated_packed_int32)?; }, 7 => { ::protobuf::rt::read_repeated_message_into(wire_type, is, &mut self.test_small_bytearrays)?; }, 8 => { ::protobuf::rt::read_repeated_message_into(wire_type, is, &mut self.test_large_bytearrays)?; }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } // Compute sizes of nested messages #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; for value in &self.test1 { let len = value.compute_size(); my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len; }; for value in &self.test_repeated_bool { let len = value.compute_size(); my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len; }; for value in &self.test_repeated_messages { let len = value.compute_size(); my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len; }; for value in &self.test_optional_messages { let len = value.compute_size(); my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len; }; for value in &self.test_strings { let len = value.compute_size(); my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len; }; for value in &self.test_repeated_packed_int32 { let len = value.compute_size(); my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len; }; for value in &self.test_small_bytearrays { let len = value.compute_size(); my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len; }; for value in &self.test_large_bytearrays { let len = value.compute_size(); my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len; }; my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { for v in &self.test1 { os.write_tag(1, ::protobuf::wire_format::WireTypeLengthDelimited)?; os.write_raw_varint32(v.get_cached_size())?; v.write_to_with_cached_sizes(os)?; }; for v in &self.test_repeated_bool { os.write_tag(2, ::protobuf::wire_format::WireTypeLengthDelimited)?; os.write_raw_varint32(v.get_cached_size())?; v.write_to_with_cached_sizes(os)?; }; for v in &self.test_repeated_messages { os.write_tag(3, ::protobuf::wire_format::WireTypeLengthDelimited)?; os.write_raw_varint32(v.get_cached_size())?; v.write_to_with_cached_sizes(os)?; }; for v in &self.test_optional_messages { os.write_tag(4, ::protobuf::wire_format::WireTypeLengthDelimited)?; os.write_raw_varint32(v.get_cached_size())?; v.write_to_with_cached_sizes(os)?; }; for v in &self.test_strings { os.write_tag(5, ::protobuf::wire_format::WireTypeLengthDelimited)?; os.write_raw_varint32(v.get_cached_size())?; v.write_to_with_cached_sizes(os)?; }; for v in &self.test_repeated_packed_int32 { os.write_tag(6, ::protobuf::wire_format::WireTypeLengthDelimited)?; os.write_raw_varint32(v.get_cached_size())?; v.write_to_with_cached_sizes(os)?; }; for v in &self.test_small_bytearrays { os.write_tag(7, ::protobuf::wire_format::WireTypeLengthDelimited)?; os.write_raw_varint32(v.get_cached_size())?; v.write_to_with_cached_sizes(os)?; }; for v in &self.test_large_bytearrays { os.write_tag(8, ::protobuf::wire_format::WireTypeLengthDelimited)?; os.write_raw_varint32(v.get_cached_size())?; v.write_to_with_cached_sizes(os)?; }; os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &dyn (::std::any::Any) { self as &dyn (::std::any::Any) } fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { self as &mut dyn (::std::any::Any) } fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> PerftestData { PerftestData::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_repeated_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<Test1>>( "test1", |m: &PerftestData| { &m.test1 }, |m: &mut PerftestData| { &mut m.test1 }, )); fields.push(::protobuf::reflect::accessor::make_repeated_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<TestRepeatedBool>>( "test_repeated_bool", |m: &PerftestData| { &m.test_repeated_bool }, |m: &mut PerftestData| { &mut m.test_repeated_bool }, )); fields.push(::protobuf::reflect::accessor::make_repeated_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<TestRepeatedMessages>>( "test_repeated_messages", |m: &PerftestData| { &m.test_repeated_messages }, |m: &mut PerftestData| { &mut m.test_repeated_messages }, )); fields.push(::protobuf::reflect::accessor::make_repeated_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<TestOptionalMessages>>( "test_optional_messages", |m: &PerftestData| { &m.test_optional_messages }, |m: &mut PerftestData| { &mut m.test_optional_messages }, )); fields.push(::protobuf::reflect::accessor::make_repeated_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<TestStrings>>( "test_strings", |m: &PerftestData| { &m.test_strings }, |m: &mut PerftestData| { &mut m.test_strings }, )); fields.push(::protobuf::reflect::accessor::make_repeated_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<TestRepeatedPackedInt32>>( "test_repeated_packed_int32", |m: &PerftestData| { &m.test_repeated_packed_int32 }, |m: &mut PerftestData| { &mut m.test_repeated_packed_int32 }, )); fields.push(::protobuf::reflect::accessor::make_repeated_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<TestBytes>>( "test_small_bytearrays", |m: &PerftestData| { &m.test_small_bytearrays }, |m: &mut PerftestData| { &mut m.test_small_bytearrays }, )); fields.push(::protobuf::reflect::accessor::make_repeated_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<TestBytes>>( "test_large_bytearrays", |m: &PerftestData| { &m.test_large_bytearrays }, |m: &mut PerftestData| { &mut m.test_large_bytearrays }, )); ::protobuf::reflect::MessageDescriptor::new_pb_name::<PerftestData>( "PerftestData", fields, file_descriptor_proto() ) }) } fn default_instance() -> &'static PerftestData { static instance: ::protobuf::rt::LazyV2<PerftestData> = ::protobuf::rt::LazyV2::INIT; instance.get(PerftestData::new) } } impl ::protobuf::Clear for PerftestData { fn clear(&mut self) { self.test1.clear(); self.test_repeated_bool.clear(); self.test_repeated_messages.clear(); self.test_optional_messages.clear(); self.test_strings.clear(); self.test_repeated_packed_int32.clear(); self.test_small_bytearrays.clear(); self.test_large_bytearrays.clear(); self.unknown_fields.clear(); } } impl ::std::fmt::Debug for PerftestData { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for PerftestData { fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { ::protobuf::reflect::ReflectValueRef::Message(self) } } static file_descriptor_proto_data: &'static [u8] = b"\ \n\x13perftest_data.proto\x12\rperftest_data\"!\n\x05Test1\x12\x16\n\x05\ value\x18\x01\x20\x01(\x05R\x05valueB\0:\0\".\n\x10TestRepeatedBool\x12\ \x18\n\x06values\x18\x01\x20\x03(\x08R\x06valuesB\0:\0\"7\n\x17TestRepea\ tedPackedInt32\x12\x1a\n\x06values\x18\x01\x20\x03(\x05R\x06valuesB\x02\ \x10\x01:\0\"\xe7\x01\n\x14TestRepeatedMessages\x12C\n\tmessages1\x18\ \x01\x20\x03(\x0b2#.perftest_data.TestRepeatedMessagesR\tmessages1B\0\ \x12C\n\tmessages2\x18\x02\x20\x03(\x0b2#.perftest_data.TestRepeatedMess\ agesR\tmessages2B\0\x12C\n\tmessages3\x18\x03\x20\x03(\x0b2#.perftest_da\ ta.TestRepeatedMessagesR\tmessages3B\0:\0\"\xe1\x01\n\x14TestOptionalMes\ sages\x12A\n\x08message1\x18\x01\x20\x01(\x0b2#.perftest_data.TestOption\ alMessagesR\x08message1B\0\x12A\n\x08message2\x18\x02\x20\x01(\x0b2#.per\ ftest_data.TestOptionalMessagesR\x08message2B\0\x12A\n\x08message3\x18\ \x03\x20\x01(\x0b2#.perftest_data.TestOptionalMessagesR\x08message3B\0:\ \0\"E\n\x0bTestStrings\x12\x10\n\x02s1\x18\x01\x20\x01(\tR\x02s1B\0\x12\ \x10\n\x02s2\x18\x02\x20\x01(\tR\x02s2B\0\x12\x10\n\x02s3\x18\x03\x20\ \x01(\tR\x02s3B\0:\0\"\x1f\n\tTestBytes\x12\x10\n\x02b1\x18\x01\x20\x01(\ \x0cR\x02b1B\0:\0\"\x91\x05\n\x0cPerftestData\x12,\n\x05test1\x18\x01\ \x20\x03(\x0b2\x14.perftest_data.Test1R\x05test1B\0\x12O\n\x12test_repea\ ted_bool\x18\x02\x20\x03(\x0b2\x1f.perftest_data.TestRepeatedBoolR\x10te\ stRepeatedBoolB\0\x12[\n\x16test_repeated_messages\x18\x03\x20\x03(\x0b2\ #.perftest_data.TestRepeatedMessagesR\x14testRepeatedMessagesB\0\x12[\n\ \x16test_optional_messages\x18\x04\x20\x03(\x0b2#.perftest_data.TestOpti\ onalMessagesR\x14testOptionalMessagesB\0\x12?\n\x0ctest_strings\x18\x05\ \x20\x03(\x0b2\x1a.perftest_data.TestStringsR\x0btestStringsB\0\x12e\n\ \x1atest_repeated_packed_int32\x18\x06\x20\x03(\x0b2&.perftest_data.Test\ RepeatedPackedInt32R\x17testRepeatedPackedInt32B\0\x12N\n\x15test_small_\ bytearrays\x18\x07\x20\x03(\x0b2\x18.perftest_data.TestBytesR\x13testSma\ llBytearraysB\0\x12N\n\x15test_large_bytearrays\x18\x08\x20\x03(\x0b2\ \x18.perftest_data.TestBytesR\x13testLargeBytearraysB\0:\0B\0b\x06proto2\ "; static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto { ::protobuf::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() } pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto { file_descriptor_proto_lazy.get(|| { parse_descriptor_proto() }) }
34.518808
155
0.591424