hexsha
stringlengths 40
40
| size
int64 4
1.05M
| content
stringlengths 4
1.05M
| avg_line_length
float64 1.33
100
| max_line_length
int64 1
1k
| alphanum_fraction
float64 0.25
1
|
---|---|---|---|---|---|
f4f42c9086ff8dbe0ce1cca9f7a647018c9af0f9 | 6,328 | use crate::{dashboard::basic_components, translation::TranslationBundle, LocalizedId};
use super::{
EmptyContainer, EmptyControl, SettingContainer, SettingControl, SettingsContext,
SettingsResponse,
};
use egui::Ui;
use serde_json as json;
use settings_schema::EntryData;
use std::collections::HashMap;
pub struct ChoiceControl {
default: LocalizedId,
variant_labels: Vec<LocalizedId>,
controls: HashMap<String, (Box<dyn SettingControl>, bool)>,
}
impl ChoiceControl {
pub fn new(
default: String,
variants_schema: Vec<(String, Option<EntryData>)>,
session_fragment: json::Value,
trans_path: &str,
trans: &TranslationBundle,
) -> Self {
let mut session_variants =
json::from_value::<HashMap<String, json::Value>>(session_fragment).unwrap();
Self {
default: LocalizedId {
id: default.clone(),
trans: trans.attribute(trans_path, &default),
},
variant_labels: variants_schema
.iter()
.map(|(id, _)| LocalizedId {
id: id.clone(),
trans: trans.attribute(trans_path, id),
})
.collect(),
controls: variants_schema
.into_iter()
.map(|(id, data)| {
if let Some(data) = data {
(
id.clone(),
(
super::create_setting_control(
data.content,
session_variants.remove(&id).unwrap(),
&format!("{}-{}", trans_path, id),
trans,
),
data.advanced,
),
)
} else {
(id, (Box::new(EmptyControl) as _, false))
}
})
.collect(),
}
}
}
impl SettingControl for ChoiceControl {
fn ui(
&mut self,
ui: &mut Ui,
session_fragment: json::Value,
ctx: &SettingsContext,
) -> Option<SettingsResponse> {
let mut session_variants =
json::from_value::<HashMap<String, json::Value>>(session_fragment).unwrap();
let mut variant =
json::from_value(session_variants.get("variant").cloned().unwrap()).unwrap();
let response =
basic_components::button_group_clicked(ui, &self.variant_labels, &mut variant).then(
|| {
session_variants
.insert("variant".to_owned(), json::to_value(&variant).unwrap());
super::into_fragment(&session_variants)
},
);
let response = super::reset_clicked(
ui,
&variant,
&self.default,
&format!("\"{}\"", self.default.trans),
&ctx.t,
)
.then(|| {
session_variants.insert(
"variant".to_owned(),
json::to_value(&*self.default).unwrap(),
);
super::into_fragment(&session_variants)
})
.or(response);
let (control, advanced) = self.controls.get_mut(&variant).unwrap();
let session_variant = session_variants
.get(&variant)
.cloned()
.unwrap_or(json::Value::Null);
(!*advanced || ctx.advanced)
.then(|| {
super::map_fragment(control.ui(ui, session_variant, ctx), |session_variant| {
session_variants.insert(variant, session_variant);
session_variants
})
})
.flatten()
.or(response)
}
}
pub struct ChoiceContainer {
containers: HashMap<String, (Box<dyn SettingContainer>, bool)>,
}
impl ChoiceContainer {
pub fn new(
variants_schema: Vec<(String, Option<EntryData>)>,
session_fragment: json::Value,
trans_path: &str,
trans: &TranslationBundle,
) -> Self {
let mut session_variants =
json::from_value::<HashMap<String, json::Value>>(session_fragment).unwrap();
Self {
containers: variants_schema
.into_iter()
.map(|(id, data)| {
if let Some(data) = data {
(
id.clone(),
(
super::create_setting_container(
data.content,
session_variants.remove(&id).unwrap(),
&format!("{}-{}", trans_path, id),
trans,
),
data.advanced,
),
)
} else {
(id, (Box::new(EmptyContainer) as _, false))
}
})
.collect(),
}
}
}
impl SettingContainer for ChoiceContainer {
fn ui(
&mut self,
ui: &mut Ui,
session_fragment: json::Value,
context: &SettingsContext,
) -> Option<SettingsResponse> {
let mut session_variants =
json::from_value::<HashMap<String, json::Value>>(session_fragment).unwrap();
let variant = json::from_value(session_variants.get("variant").cloned().unwrap()).unwrap();
let (control, advanced) = self.containers.get_mut(&variant).unwrap();
let session_variant = session_variants
.get(&variant)
.cloned()
.unwrap_or(json::Value::Null);
(!*advanced || context.advanced)
.then(|| {
super::map_fragment(
control.ui(ui, session_variant, context),
|session_variant| {
session_variants.insert(variant, session_variant);
session_variants
},
)
})
.flatten()
}
}
| 32.618557 | 99 | 0.462863 |
bb900bc584adc5dc68693161ab30001174b37a64 | 7,999 | use std::collections::{BTreeMap, VecDeque};
use std::error::Error;
use std::sync::{Arc, Mutex};
use serde::{Deserialize, Serialize};
use crate::config::*;
use crate::interpolate::interpolate_modify;
use crate::worker::LogStream;
use crate::worker::WorkerMessage;
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, PartialOrd)]
#[serde(rename_all(serialize = "lowercase", deserialize = "lowercase"))]
pub enum StatusState {
Blank,
Green,
Yellow,
Red,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Status {
pub config: Config,
pub monitors: Vec<Arc<Mutex<MonitorState>>>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct MonitorState {
pub id: String,
pub config: MonitorDirTestConfig,
#[serde(skip_serializing_if = "MonitorStatus::is_uninitialized")]
pub status: MonitorStatus,
#[serde(skip)]
pub css: Option<String>,
pub children: BTreeMap<String, MonitorChildStatus>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct MonitorChildStatus {
pub axes: BTreeMap<String, MonitorDirAxisValue>,
#[serde(skip_serializing_if = "MonitorStatus::is_uninitialized")]
pub status: MonitorStatus,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct MonitorStatus {
pub status: Option<StatusState>,
pub code: i64,
pub description: String,
pub css: MonitorCssStatus,
pub metadata: BTreeMap<String, String>,
pub log: VecDeque<String>,
#[serde(skip)]
pub pending: Option<MonitorPendingStatus>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct MonitorPendingStatus {
pub status: Option<StatusState>,
pub description: Option<String>,
pub metadata: Option<BTreeMap<String, String>>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct MonitorCssStatus {
pub metadata: Arc<BTreeMap<String, String>>,
}
impl Default for MonitorCssStatus {
fn default() -> Self {
Self {
metadata: Arc::new(Default::default()),
}
}
}
impl MonitorState {
/// Internal use only
fn new_internal(id: String, config: MonitorDirTestConfig) -> Self {
MonitorState {
id,
config,
status: Default::default(),
css: None,
children: Default::default(),
}
}
fn process_log_message<T: FnMut(&str) -> ()>(
&mut self,
stream: &str,
message: &str,
direct_logger: &mut T,
) {
let msg = format!("[{}] {}", stream, message);
direct_logger(&msg);
self.status.log.push_back(msg);
}
pub fn process_message<T: FnMut(&str) -> ()>(
&mut self,
id: &str,
msg: WorkerMessage,
config: &CssMetadataConfig,
direct_logger: &mut T,
) -> Result<(), Box<dyn Error>> {
debug!("[{}] Worker message {:?}", id, msg);
match msg {
WorkerMessage::Starting => {
// Note that we don't update the state here
self.status.pending = None;
self.status.log.clear();
}
WorkerMessage::LogMessage(stream, m) => {
let stream = match stream {
LogStream::StdOut => "stdout",
LogStream::StdErr => "stderr",
};
// TODO: Long lines without \n at the end should have some sort of other delimiter inserted
self.process_log_message(stream, m.trim_end(), direct_logger);
}
WorkerMessage::Metadata(expr) => {
// Make borrow checker happy
let status = &mut self.status;
let children = &mut self.children;
if let Err(err) = interpolate_modify(status, children, &expr) {
self.process_log_message("error ", &expr, direct_logger);
self.process_log_message("error ", &err.to_string(), direct_logger);
error!("Metadata update error: {}", err);
} else {
self.process_log_message("meta ", &expr.to_string(), direct_logger);
}
}
WorkerMessage::AbnormalTermination(s) => {
self.finish(StatusState::Yellow, -1, s, &config);
}
WorkerMessage::Termination(code) => {
if code == 0 {
self.finish(StatusState::Green, code, "Success".into(), &config);
} else {
self.finish(StatusState::Red, code, "Failed".into(), &config);
}
}
}
Ok(())
}
fn finish(
&mut self,
status: StatusState,
code: i64,
description: String,
config: &CssMetadataConfig,
) {
self.css = None;
for child in self.children.iter_mut() {
let child_status = &mut child.1.status;
if child_status.is_pending_status_set() || status != StatusState::Green {
child_status.finish(status, code, description.clone(), &config);
} else {
child_status.finish(StatusState::Blank, code, "".into(), &config);
}
}
self.status.finish(status, code, description, config);
}
}
impl From<&MonitorDirConfig> for MonitorState {
fn from(other: &MonitorDirConfig) -> Self {
let mut state = MonitorState::new_internal(other.id.clone(), other.root.test().clone());
if let MonitorDirRootConfig::Group(ref group) = other.root {
for child in group.children.iter() {
state.children.insert(
child.0.clone(),
MonitorChildStatus {
axes: child.1.axes.clone(),
status: MonitorStatus::default(),
},
);
}
}
state
}
}
impl MonitorStatus {
pub fn initialize(&mut self, config: &CssMetadataConfig) {
self.description = "Unknown (initializing)".into();
self.status = Some(StatusState::Blank);
self.css.metadata = config.blank.clone();
}
pub fn is_pending_status_set(&self) -> bool {
if let Some(ref pending) = self.pending {
if pending.status.is_none() {
return false;
}
} else {
return false;
}
true
}
pub fn is_uninitialized(&self) -> bool {
self.status.is_none()
}
fn finish(
&mut self,
status: StatusState,
code: i64,
description: String,
config: &CssMetadataConfig,
) {
let (pending_status, pending_description, pending_metadata) = self
.pending
.take()
.map(|pending| (pending.status, pending.description, pending.metadata))
.unwrap_or_default();
self.code = code;
// Start with the regular update
self.status = Some(status);
self.description = description;
self.metadata.clear();
// Metadata/status can only be overwritten if the process terminated normally
if status == StatusState::Green {
if let Some(metadata) = pending_metadata {
self.metadata = metadata;
}
if let Some(status) = pending_status {
self.status = Some(status);
}
if let Some(description) = pending_description {
self.description = description;
}
}
// Update the CSS metadata with the final status
if let Some(status) = self.status {
self.css.metadata = match status {
StatusState::Blank => config.blank.clone(),
StatusState::Green => config.green.clone(),
StatusState::Yellow => config.yellow.clone(),
StatusState::Red => config.red.clone(),
};
}
}
}
| 31.368627 | 107 | 0.55907 |
0e8b4d44e8406fb208ddcb3b747bba142a2a5890 | 16,616 | use {
crate::transaction_notifier_interface::TransactionNotifierLock,
crossbeam_channel::{Receiver, RecvTimeoutError},
itertools::izip,
solana_ledger::{
blockstore::Blockstore,
blockstore_processor::{TransactionStatusBatch, TransactionStatusMessage},
},
solana_runtime::bank::{
DurableNonceFee, TransactionExecutionDetails, TransactionExecutionResult,
},
solana_transaction_status::{
extract_and_fmt_memos, InnerInstructions, Reward, TransactionStatusMeta,
},
std::{
sync::{
atomic::{AtomicBool, AtomicU64, Ordering},
Arc,
},
thread::{self, Builder, JoinHandle},
time::Duration,
},
};
pub struct TransactionStatusService {
thread_hdl: JoinHandle<()>,
}
impl TransactionStatusService {
#[allow(clippy::new_ret_no_self)]
pub fn new(
write_transaction_status_receiver: Receiver<TransactionStatusMessage>,
max_complete_transaction_status_slot: Arc<AtomicU64>,
enable_rpc_transaction_history: bool,
transaction_notifier: Option<TransactionNotifierLock>,
blockstore: Arc<Blockstore>,
enable_extended_tx_metadata_storage: bool,
exit: &Arc<AtomicBool>,
) -> Self {
let exit = exit.clone();
let thread_hdl = Builder::new()
.name("solana-transaction-status-writer".to_string())
.spawn(move || loop {
if exit.load(Ordering::Relaxed) {
break;
}
if let Err(RecvTimeoutError::Disconnected) = Self::write_transaction_status_batch(
&write_transaction_status_receiver,
&max_complete_transaction_status_slot,
enable_rpc_transaction_history,
transaction_notifier.clone(),
&blockstore,
enable_extended_tx_metadata_storage,
) {
break;
}
})
.unwrap();
Self { thread_hdl }
}
fn write_transaction_status_batch(
write_transaction_status_receiver: &Receiver<TransactionStatusMessage>,
max_complete_transaction_status_slot: &Arc<AtomicU64>,
enable_rpc_transaction_history: bool,
transaction_notifier: Option<TransactionNotifierLock>,
blockstore: &Arc<Blockstore>,
enable_extended_tx_metadata_storage: bool,
) -> Result<(), RecvTimeoutError> {
match write_transaction_status_receiver.recv_timeout(Duration::from_secs(1))? {
TransactionStatusMessage::Batch(TransactionStatusBatch {
bank,
transactions,
execution_results,
balances,
token_balances,
rent_debits,
}) => {
let slot = bank.slot();
for (
transaction,
execution_result,
pre_balances,
post_balances,
pre_token_balances,
post_token_balances,
rent_debits,
) in izip!(
transactions,
execution_results,
balances.pre_balances,
balances.post_balances,
token_balances.pre_token_balances,
token_balances.post_token_balances,
rent_debits,
) {
if let TransactionExecutionResult::Executed(details) = execution_result {
let TransactionExecutionDetails {
status,
log_messages,
inner_instructions,
durable_nonce_fee,
return_data,
} = details;
let lamports_per_signature = match durable_nonce_fee {
Some(DurableNonceFee::Valid(lamports_per_signature)) => {
Some(lamports_per_signature)
}
Some(DurableNonceFee::Invalid) => None,
None => bank.get_lamports_per_signature_for_blockhash(
transaction.message().recent_blockhash(),
),
}
.expect("lamports_per_signature must be available");
let fee = bank.get_fee_for_message_with_lamports_per_signature(
transaction.message(),
lamports_per_signature,
);
let tx_account_locks = transaction.get_account_locks_unchecked();
let inner_instructions = inner_instructions.map(|inner_instructions| {
inner_instructions
.into_iter()
.enumerate()
.map(|(index, instructions)| InnerInstructions {
index: index as u8,
instructions,
})
.filter(|i| !i.instructions.is_empty())
.collect()
});
let pre_token_balances = Some(pre_token_balances);
let post_token_balances = Some(post_token_balances);
let rewards = Some(
rent_debits
.into_unordered_rewards_iter()
.map(|(pubkey, reward_info)| Reward {
pubkey: pubkey.to_string(),
lamports: reward_info.lamports,
post_balance: reward_info.post_balance,
reward_type: Some(reward_info.reward_type),
commission: reward_info.commission,
})
.collect(),
);
let loaded_addresses = transaction.get_loaded_addresses();
let mut transaction_status_meta = TransactionStatusMeta {
status,
fee,
pre_balances,
post_balances,
inner_instructions,
log_messages,
pre_token_balances,
post_token_balances,
rewards,
loaded_addresses,
return_data,
};
if let Some(transaction_notifier) = transaction_notifier.as_ref() {
transaction_notifier.write().unwrap().notify_transaction(
slot,
transaction.signature(),
&transaction_status_meta,
&transaction,
);
}
if !(enable_extended_tx_metadata_storage || transaction_notifier.is_some())
{
transaction_status_meta.log_messages.take();
transaction_status_meta.inner_instructions.take();
transaction_status_meta.return_data.take();
}
if enable_rpc_transaction_history {
if let Some(memos) = extract_and_fmt_memos(transaction.message()) {
blockstore
.write_transaction_memos(transaction.signature(), memos)
.expect("Expect database write to succeed: TransactionMemos");
}
blockstore
.write_transaction_status(
slot,
*transaction.signature(),
tx_account_locks.writable,
tx_account_locks.readonly,
transaction_status_meta,
)
.expect("Expect database write to succeed: TransactionStatus");
}
}
}
}
TransactionStatusMessage::Freeze(slot) => {
max_complete_transaction_status_slot.fetch_max(slot, Ordering::SeqCst);
}
}
Ok(())
}
pub fn join(self) -> thread::Result<()> {
self.thread_hdl.join()
}
}
#[cfg(test)]
pub(crate) mod tests {
use {
super::*,
crate::transaction_notifier_interface::TransactionNotifier,
crossbeam_channel::unbounded,
dashmap::DashMap,
solana_account_decoder::parse_token::token_amount_to_ui_amount,
solana_ledger::{genesis_utils::create_genesis_config, get_tmp_ledger_path},
solana_runtime::bank::{Bank, NonceFull, NoncePartial, RentDebits, TransactionBalancesSet},
solana_sdk::{
account_utils::StateMut,
clock::Slot,
hash::Hash,
instruction::CompiledInstruction,
message::{Message, MessageHeader, SanitizedMessage},
nonce, nonce_account,
pubkey::Pubkey,
signature::{Keypair, Signature, Signer},
system_transaction,
transaction::{
MessageHash, SanitizedTransaction, SimpleAddressLoader, Transaction,
VersionedTransaction,
},
},
solana_transaction_status::{
token_balances::TransactionTokenBalancesSet, TransactionStatusMeta,
TransactionTokenBalance,
},
std::{
sync::{
atomic::{AtomicBool, Ordering},
Arc, RwLock,
},
thread::sleep,
time::Duration,
},
};
struct TestTransactionNotifier {
notifications: DashMap<(Slot, Signature), (TransactionStatusMeta, SanitizedTransaction)>,
}
impl TestTransactionNotifier {
pub fn new() -> Self {
Self {
notifications: DashMap::default(),
}
}
}
impl TransactionNotifier for TestTransactionNotifier {
fn notify_transaction(
&self,
slot: Slot,
signature: &Signature,
transaction_status_meta: &TransactionStatusMeta,
transaction: &SanitizedTransaction,
) {
self.notifications.insert(
(slot, *signature),
(transaction_status_meta.clone(), transaction.clone()),
);
}
}
fn build_test_transaction_legacy() -> Transaction {
let keypair1 = Keypair::new();
let pubkey1 = keypair1.pubkey();
let zero = Hash::default();
system_transaction::transfer(&keypair1, &pubkey1, 42, zero)
}
fn build_message() -> Message {
Message {
header: MessageHeader {
num_readonly_signed_accounts: 11,
num_readonly_unsigned_accounts: 12,
num_required_signatures: 13,
},
account_keys: vec![Pubkey::new_unique()],
recent_blockhash: Hash::new_unique(),
instructions: vec![CompiledInstruction {
program_id_index: 1,
accounts: vec![1, 2, 3],
data: vec![4, 5, 6],
}],
}
}
#[test]
fn test_notify_transaction() {
let genesis_config = create_genesis_config(2).genesis_config;
let bank = Arc::new(Bank::new_no_wallclock_throttle_for_tests(&genesis_config));
let (transaction_status_sender, transaction_status_receiver) = unbounded();
let ledger_path = get_tmp_ledger_path!();
let blockstore =
Blockstore::open(&ledger_path).expect("Expected to be able to open database ledger");
let blockstore = Arc::new(blockstore);
let transaction = build_test_transaction_legacy();
let transaction = VersionedTransaction::from(transaction);
let transaction = SanitizedTransaction::try_create(
transaction,
MessageHash::Compute,
None,
SimpleAddressLoader::Disabled,
)
.unwrap();
let expected_transaction = transaction.clone();
let pubkey = Pubkey::new_unique();
let mut nonce_account = nonce_account::create_account(1).into_inner();
let data = nonce::state::Data::new(Pubkey::new(&[1u8; 32]), Hash::new(&[42u8; 32]), 42);
nonce_account
.set_state(&nonce::state::Versions::new_current(
nonce::State::Initialized(data),
))
.unwrap();
let message = build_message();
let rollback_partial = NoncePartial::new(pubkey, nonce_account.clone());
let mut rent_debits = RentDebits::default();
rent_debits.insert(&pubkey, 123, 456);
let transaction_result =
TransactionExecutionResult::Executed(TransactionExecutionDetails {
status: Ok(()),
log_messages: None,
inner_instructions: None,
durable_nonce_fee: Some(DurableNonceFee::from(
&NonceFull::from_partial(
rollback_partial,
&SanitizedMessage::Legacy(message),
&[(pubkey, nonce_account)],
&rent_debits,
)
.unwrap(),
)),
return_data: None,
});
let balances = TransactionBalancesSet {
pre_balances: vec![vec![123456]],
post_balances: vec![vec![234567]],
};
let owner = Pubkey::new_unique().to_string();
let token_program_id = Pubkey::new_unique().to_string();
let pre_token_balance = TransactionTokenBalance {
account_index: 0,
mint: Pubkey::new_unique().to_string(),
ui_token_amount: token_amount_to_ui_amount(42, 2),
owner: owner.clone(),
program_id: token_program_id.clone(),
};
let post_token_balance = TransactionTokenBalance {
account_index: 0,
mint: Pubkey::new_unique().to_string(),
ui_token_amount: token_amount_to_ui_amount(58, 2),
owner,
program_id: token_program_id,
};
let token_balances = TransactionTokenBalancesSet {
pre_token_balances: vec![vec![pre_token_balance]],
post_token_balances: vec![vec![post_token_balance]],
};
let slot = bank.slot();
let signature = *transaction.signature();
let transaction_status_batch = TransactionStatusBatch {
bank,
transactions: vec![transaction],
execution_results: vec![transaction_result],
balances,
token_balances,
rent_debits: vec![rent_debits],
};
let test_notifier = Arc::new(RwLock::new(TestTransactionNotifier::new()));
let exit = Arc::new(AtomicBool::new(false));
let transaction_status_service = TransactionStatusService::new(
transaction_status_receiver,
Arc::new(AtomicU64::default()),
false,
Some(test_notifier.clone()),
blockstore,
false,
&exit,
);
transaction_status_sender
.send(TransactionStatusMessage::Batch(transaction_status_batch))
.unwrap();
sleep(Duration::from_millis(500));
exit.store(true, Ordering::Relaxed);
transaction_status_service.join().unwrap();
let notifier = test_notifier.read().unwrap();
assert_eq!(notifier.notifications.len(), 1);
assert!(notifier.notifications.contains_key(&(slot, signature)));
let result = &*notifier.notifications.get(&(slot, signature)).unwrap();
assert_eq!(expected_transaction.signature(), result.1.signature());
}
}
| 39.188679 | 99 | 0.516731 |
62174175670579924be9e8d1ee4a3cda92926ca3 | 4,509 | // Generated from definition io.k8s.api.authorization.v1.SelfSubjectAccessReviewSpec
/// SelfSubjectAccessReviewSpec is a description of the access request. Exactly one of ResourceAuthorizationAttributes and NonResourceAuthorizationAttributes must be set
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SelfSubjectAccessReviewSpec {
/// NonResourceAttributes describes information for a non-resource access request
pub non_resource_attributes: Option<crate::api::authorization::v1::NonResourceAttributes>,
/// ResourceAuthorizationAttributes describes information for a resource access request
pub resource_attributes: Option<crate::api::authorization::v1::ResourceAttributes>,
}
impl<'de> serde::Deserialize<'de> for SelfSubjectAccessReviewSpec {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> {
#[allow(non_camel_case_types)]
enum Field {
Key_non_resource_attributes,
Key_resource_attributes,
Other,
}
impl<'de> serde::Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> {
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = Field;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("field identifier")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error {
Ok(match v {
"nonResourceAttributes" => Field::Key_non_resource_attributes,
"resourceAttributes" => Field::Key_resource_attributes,
_ => Field::Other,
})
}
}
deserializer.deserialize_identifier(Visitor)
}
}
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = SelfSubjectAccessReviewSpec;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("SelfSubjectAccessReviewSpec")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: serde::de::MapAccess<'de> {
let mut value_non_resource_attributes: Option<crate::api::authorization::v1::NonResourceAttributes> = None;
let mut value_resource_attributes: Option<crate::api::authorization::v1::ResourceAttributes> = None;
while let Some(key) = serde::de::MapAccess::next_key::<Field>(&mut map)? {
match key {
Field::Key_non_resource_attributes => value_non_resource_attributes = serde::de::MapAccess::next_value(&mut map)?,
Field::Key_resource_attributes => value_resource_attributes = serde::de::MapAccess::next_value(&mut map)?,
Field::Other => { let _: serde::de::IgnoredAny = serde::de::MapAccess::next_value(&mut map)?; },
}
}
Ok(SelfSubjectAccessReviewSpec {
non_resource_attributes: value_non_resource_attributes,
resource_attributes: value_resource_attributes,
})
}
}
deserializer.deserialize_struct(
"SelfSubjectAccessReviewSpec",
&[
"nonResourceAttributes",
"resourceAttributes",
],
Visitor,
)
}
}
impl serde::Serialize for SelfSubjectAccessReviewSpec {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer {
let mut state = serializer.serialize_struct(
"SelfSubjectAccessReviewSpec",
self.non_resource_attributes.as_ref().map_or(0, |_| 1) +
self.resource_attributes.as_ref().map_or(0, |_| 1),
)?;
if let Some(value) = &self.non_resource_attributes {
serde::ser::SerializeStruct::serialize_field(&mut state, "nonResourceAttributes", value)?;
}
if let Some(value) = &self.resource_attributes {
serde::ser::SerializeStruct::serialize_field(&mut state, "resourceAttributes", value)?;
}
serde::ser::SerializeStruct::end(state)
}
}
| 44.643564 | 170 | 0.592149 |
f9e81a0edd229feea4bf38baa288f59e0c1bd95b | 136 | extern crate lolbench ; # [ test ] fn end_to_end ( ) {
lolbench :: end_to_end_test ( "clap_2_31_2" , "_03_complex::parse_clean" , ) ;
} | 45.333333 | 78 | 0.669118 |
2265ed2f03b6e7600fcab1abdebd2255d64d3401 | 466 |
#[allow(dead_code)]
pub fn set_panic_hook() {
// When the `console_error_panic_hook` feature is enabled, we can call the
// `set_panic_hook` function at least once during initialization, and then
// we will get better error messages if our code ever panics.
//
// For more details see
// https://github.com/rustwasm/console_error_panic_hook#readme
#[cfg(feature = "console_error_panic_hook")]
console_error_panic_hook::set_once();
}
| 35.846154 | 78 | 0.716738 |
696c60d2a60378feb2659218114517fd2a207585 | 6,686 | /*
* Copyright 2021 Datafuse Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
use std::fs::File;
use std::io::Read;
use std::string::String;
use common_base::tokio;
use common_base::Stoppable;
use common_meta_types::Node;
use databend_meta::api::http::v1::cluster_state::nodes_handler;
use databend_meta::api::http::v1::cluster_state::state_handler;
use databend_meta::api::HttpService;
use databend_meta::meta_service::MetaNode;
use poem::get;
use poem::http::Method;
use poem::http::StatusCode;
use poem::http::Uri;
use poem::Endpoint;
use poem::EndpointExt;
use poem::Request;
use poem::Route;
use pretty_assertions::assert_eq;
use crate::init_meta_ut;
use crate::tests::service::MetaSrvTestContext;
use crate::tests::tls_constants::TEST_CA_CERT;
use crate::tests::tls_constants::TEST_CN_NAME;
use crate::tests::tls_constants::TEST_SERVER_CERT;
use crate::tests::tls_constants::TEST_SERVER_KEY;
#[tokio::test]
async fn test_cluster_nodes() -> common_exception::Result<()> {
let (_log_guards, ut_span) = init_meta_ut!();
let _ent = ut_span.enter();
let tc0 = MetaSrvTestContext::new(0);
let mut tc1 = MetaSrvTestContext::new(1);
tc1.config.raft_config.single = false;
tc1.config.raft_config.join = vec![tc0.config.raft_config.raft_api_addr().await?.to_string()];
let meta_node = MetaNode::start(&tc0.config.raft_config).await?;
meta_node.join_cluster(&tc0.config.raft_config).await?;
let meta_node1 = MetaNode::start(&tc1.config.raft_config).await?;
meta_node1.join_cluster(&tc1.config.raft_config).await?;
let cluster_router = Route::new()
.at("/cluster/nodes", get(nodes_handler))
.data(meta_node1.clone());
let response = cluster_router
.call(
Request::builder()
.uri(Uri::from_static("/cluster/nodes"))
.method(Method::GET)
.finish(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = response.into_body().into_vec().await.unwrap();
let nodes: Vec<Node> = serde_json::from_slice(&body).unwrap();
assert_eq!(nodes.len(), 2);
meta_node.stop().await?;
meta_node1.stop().await?;
Ok(())
}
#[tokio::test]
async fn test_cluster_state() -> common_exception::Result<()> {
let (_log_guards, ut_span) = init_meta_ut!();
let _ent = ut_span.enter();
let tc0 = MetaSrvTestContext::new(0);
let mut tc1 = MetaSrvTestContext::new(1);
tc1.config.raft_config.single = false;
tc1.config.raft_config.join = vec![tc0.config.raft_config.raft_api_addr().await?.to_string()];
let meta_node = MetaNode::start(&tc0.config.raft_config).await?;
meta_node.join_cluster(&tc0.config.raft_config).await?;
let meta_node1 = MetaNode::start(&tc1.config.raft_config).await?;
meta_node1.join_cluster(&tc1.config.raft_config).await?;
let cluster_router = Route::new()
.at("/cluster/state", get(state_handler))
.data(meta_node1.clone());
let response = cluster_router
.call(
Request::builder()
.uri(Uri::from_static("/cluster/state"))
.method(Method::GET)
.finish(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = response.into_body().into_vec().await.unwrap();
let state = serde_json::from_str::<serde_json::Value>(String::from_utf8_lossy(&body).as_ref())?;
let voters = state["voters"].as_array().unwrap();
let non_voters = state["non_voters"].as_array().unwrap();
let leader = state["leader"].as_object();
assert_eq!(voters.len(), 2);
assert_eq!(non_voters.len(), 0);
assert_ne!(leader, None);
meta_node.stop().await?;
meta_node1.stop().await?;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 3)]
async fn test_http_service_cluster_state() -> common_exception::Result<()> {
let addr_str = "127.0.0.1:30003";
let (_log_guards, ut_span) = init_meta_ut!();
let _ent = ut_span.enter();
let tc0 = MetaSrvTestContext::new(0);
let mut tc1 = MetaSrvTestContext::new(1);
tc1.config.raft_config.single = false;
tc1.config.raft_config.join = vec![tc0.config.raft_config.raft_api_addr().await?.to_string()];
tc1.config.admin_api_address = addr_str.to_owned();
tc1.config.admin_tls_server_key = TEST_SERVER_KEY.to_owned();
tc1.config.admin_tls_server_cert = TEST_SERVER_CERT.to_owned();
let meta_node = MetaNode::start(&tc0.config.raft_config).await?;
meta_node.join_cluster(&tc0.config.raft_config).await?;
let meta_node1 = MetaNode::start(&tc1.config.raft_config).await?;
meta_node1.join_cluster(&tc1.config.raft_config).await?;
let mut srv = HttpService::create(tc1.config, meta_node1);
// test cert is issued for "localhost"
let state_url = format!("https://{}:30003/v1/cluster/state", TEST_CN_NAME);
let node_url = format!("https://{}:30003/v1/cluster/nodes", TEST_CN_NAME);
// load cert
let mut buf = Vec::new();
File::open(TEST_CA_CERT)?.read_to_end(&mut buf)?;
let cert = reqwest::Certificate::from_pem(&buf).unwrap();
srv.start().await.expect("HTTP: admin api error");
// kick off
let client = reqwest::Client::builder()
.add_root_certificate(cert)
.build()
.unwrap();
let resp = client.get(state_url).send().await;
assert!(resp.is_ok());
let resp = resp.unwrap();
assert!(resp.status().is_success());
assert_eq!("/v1/cluster/state", resp.url().path());
let state_json = resp.json::<serde_json::Value>().await.unwrap();
assert_eq!(state_json["voters"].as_array().unwrap().len(), 2);
assert_eq!(state_json["non_voters"].as_array().unwrap().len(), 0);
assert_ne!(state_json["leader"].as_object(), None);
let resp_nodes = client.get(node_url).send().await;
assert!(resp_nodes.is_ok());
let resp_nodes = resp_nodes.unwrap();
assert!(resp_nodes.status().is_success());
assert_eq!("/v1/cluster/nodes", resp_nodes.url().path());
let result = resp_nodes.json::<Vec<Node>>().await.unwrap();
assert_eq!(result.len(), 2);
Ok(())
}
| 35.754011 | 100 | 0.673347 |
50c021d179e3ee5d0a04a4af0b48c495c9422da3 | 864 | //! Utilities for working with buffers.
//!
//! `io-uring` APIs require passing ownership of buffers to the runtime. The
//! crate defines [`IoBuf`] and [`IoBufMut`] traits which are implemented by buffer
//! types that respect the `io-uring` contract.
mod io_buf;
pub use io_buf::IoBuf;
mod io_buf_mut;
pub use io_buf_mut::IoBufMut;
mod slice;
pub use slice::Slice;
pub(crate) fn deref(buf: &impl IoBuf) -> &[u8] {
// Safety: the `IoBuf` trait is marked as unsafe and is expected to be
// implemented correctly.
unsafe { std::slice::from_raw_parts(buf.stable_ptr(), buf.bytes_init()) }
}
pub(crate) fn deref_mut(buf: &mut impl IoBufMut) -> &mut [u8] {
// Safety: the `IoBufMut` trait is marked as unsafe and is expected to be
// implemented correct.
unsafe { std::slice::from_raw_parts_mut(buf.stable_mut_ptr(), buf.bytes_init()) }
}
| 32 | 85 | 0.696759 |
f59405871fac9463a6bd0f7c13bf2d4d686818e7 | 213 | #![no_std]
#![feature(llvm_asm)]
extern crate alloc;
pub mod debug;
pub mod entry;
pub mod error;
pub mod global_alloc_macro;
pub mod muta_constants;
pub use ckb_allocator;
pub mod high_level;
pub mod syscalls;
| 15.214286 | 27 | 0.765258 |
9ce947c7725de715a317ac044896cf7d045188d3 | 2,592 | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use DOMElement;
use DOMEventTarget;
use DOMHTMLElement;
use DOMNode;
use DOMObject;
use glib::GString;
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::SignalHandlerId;
use glib::signal::connect_raw;
use glib::translate::*;
use glib_sys;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem::transmute;
use webkit2_webextension_sys;
glib_wrapper! {
pub struct DOMHTMLQuoteElement(Object<webkit2_webextension_sys::WebKitDOMHTMLQuoteElement, webkit2_webextension_sys::WebKitDOMHTMLQuoteElementClass, DOMHTMLQuoteElementClass>) @extends DOMHTMLElement, DOMElement, DOMNode, DOMObject, @implements DOMEventTarget;
match fn {
get_type => || webkit2_webextension_sys::webkit_dom_html_quote_element_get_type(),
}
}
pub const NONE_DOMHTML_QUOTE_ELEMENT: Option<&DOMHTMLQuoteElement> = None;
pub trait DOMHTMLQuoteElementExt: 'static {
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_cite(&self) -> Option<GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn set_cite(&self, value: &str);
fn connect_property_cite_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
}
impl<O: IsA<DOMHTMLQuoteElement>> DOMHTMLQuoteElementExt for O {
fn get_cite(&self) -> Option<GString> {
unsafe {
from_glib_full(webkit2_webextension_sys::webkit_dom_html_quote_element_get_cite(self.as_ref().to_glib_none().0))
}
}
fn set_cite(&self, value: &str) {
unsafe {
webkit2_webextension_sys::webkit_dom_html_quote_element_set_cite(self.as_ref().to_glib_none().0, value.to_glib_none().0);
}
}
fn connect_property_cite_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(self.as_ptr() as *mut _, b"notify::cite\0".as_ptr() as *const _,
Some(transmute(notify_cite_trampoline::<Self, F> as usize)), Box_::into_raw(f))
}
}
}
unsafe extern "C" fn notify_cite_trampoline<P, F: Fn(&P) + 'static>(this: *mut webkit2_webextension_sys::WebKitDOMHTMLQuoteElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer)
where P: IsA<DOMHTMLQuoteElement> {
let f: &F = &*(f as *const F);
f(&DOMHTMLQuoteElement::from_glib_borrow(this).unsafe_cast())
}
impl fmt::Display for DOMHTMLQuoteElement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "DOMHTMLQuoteElement")
}
}
| 34.56 | 264 | 0.697917 |
ff6872add5d1029fa79be27ddea798ef297631d4 | 1,334 |
macro_rules! str_enum {
(
$enum_access: vis enum $enum_name: ident {
$error_access: vis type Err = $error_name: ident;
$( $variant_name: ident ( $variant_str: literal ) ),* $(,)?
}
) => {
#[derive(::core::cmp::Eq, ::core::cmp::PartialEq)]
$enum_access enum $enum_name {
$($variant_name,)*
}
impl ::core::fmt::Display for $enum_name {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
match self {
$(Self::$variant_name => f.write_str($variant_str),)*
}
}
}
impl ::core::fmt::Debug for $enum_name {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
::core::fmt::Display::fmt(self, f)
}
}
impl ::core::str::FromStr for $enum_name {
type Err = $error_name;
fn from_str(s: &str) -> ::core::result::Result<Self, Self::Err> {
match s {
$($variant_str => Ok(Self::$variant_name),)*
other => Err($error_name(other.to_owned()))
}
}
}
#[derive(::core::fmt::Debug)]
$error_access struct $error_name(String);
};
}
| 31.023256 | 86 | 0.455772 |
1c779a3aeb11a880d4562f5685c7a58ad7130e2c | 6,913 | use crate::core::ribosome::error::RibosomeError;
use crate::core::ribosome::CallContext;
use crate::core::ribosome::RibosomeT;
use crate::core::workflow::call_zome_workflow::CallZomeWorkspace;
use crate::core::workflow::integrate_dht_ops_workflow::integrate_to_authored;
use holochain_cascade::error::CascadeResult;
use holochain_types::prelude::*;
use holochain_wasmer_host::prelude::WasmError;
use std::sync::Arc;
#[allow(clippy::extra_unused_lifetimes)]
pub fn delete_link<'a>(
_ribosome: Arc<impl RibosomeT>,
call_context: Arc<CallContext>,
input: HeaderHash,
) -> Result<HeaderHash, WasmError> {
// get the base address from the add link header
// don't allow the wasm developer to get this wrong
// it is never valid to have divergent base address for add/remove links
// the subconscious will validate the base address match but we need to fetch it here to
// include it in the remove link header
let network = call_context.host_access.network().clone();
let address = input.clone();
let call_context_2 = call_context.clone();
// handle timeouts at the network layer
let maybe_add_link: Option<SignedHeaderHashed> =
tokio_helper::block_forever_on(async move {
CascadeResult::Ok(
call_context_2
.clone()
.host_access
.workspace()
.write()
.await
.cascade(network)
.dht_get(address.into(), GetOptions::content())
.await?
.map(|el| el.into_inner().0),
)
})
.map_err(|cascade_error| WasmError::Host(cascade_error.to_string()))?;
let base_address = match maybe_add_link {
Some(add_link_signed_header_hash) => {
match add_link_signed_header_hash.header() {
Header::CreateLink(link_add_header) => Ok(link_add_header.base_address.clone()),
// the add link header hash provided was found but didn't point to an AddLink
// header (it is something else) so we cannot proceed
_ => Err(RibosomeError::ElementDeps(input.clone().into())),
}
}
// the add link header hash could not be found
// it's unlikely that a wasm call would have a valid add link header hash from "somewhere"
// that isn't also discoverable in either the cache or DHT, but it _is_ possible so we have
// to fail in that case (e.g. the local cache could have GC'd at the same moment the
// network connection dropped out)
None => Err(RibosomeError::ElementDeps(input.clone().into())),
}
.map_err(|ribosome_error| WasmError::Host(ribosome_error.to_string()))?;
let workspace_lock = call_context.host_access.workspace();
// handle timeouts at the source chain layer
// add a DeleteLink to the source chain
tokio_helper::block_forever_on(async move {
let mut guard = workspace_lock.write().await;
let workspace: &mut CallZomeWorkspace = &mut guard;
let source_chain = &mut workspace.source_chain;
let header_builder = builder::DeleteLink {
link_add_address: input,
base_address,
};
let header_hash = source_chain
.put(header_builder, None)
.await
.map_err(|source_chain_error| WasmError::Host(source_chain_error.to_string()))?;
let element = source_chain
.get_element(&header_hash)
.map_err(|source_chain_error| WasmError::Host(source_chain_error.to_string()))?
.expect("Element we just put in SourceChain must be gettable");
integrate_to_authored(
&element,
workspace.source_chain.elements(),
&mut workspace.meta_authored,
)
.map_err(|dht_op_convert_error| WasmError::Host(dht_op_convert_error.to_string()))?;
Ok(header_hash)
})
}
#[cfg(test)]
#[cfg(feature = "slow_tests")]
pub mod slow_tests {
use crate::fixt::ZomeCallHostAccessFixturator;
use ::fixt::prelude::*;
use holo_hash::HeaderHash;
use holochain_wasm_test_utils::TestWasm;
use holochain_zome_types::link::Links;
#[tokio::test(flavor = "multi_thread")]
async fn ribosome_delete_link_add_remove() {
let test_env = holochain_lmdb::test_utils::test_cell_env();
let env = test_env.env();
let mut workspace =
crate::core::workflow::CallZomeWorkspace::new(env.clone().into()).unwrap();
// commits fail validation if we don't do genesis
crate::core::workflow::fake_genesis(&mut workspace.source_chain)
.await
.unwrap();
let workspace_lock = crate::core::workflow::CallZomeWorkspaceLock::new(workspace);
let mut host_access = fixt!(ZomeCallHostAccess);
host_access.workspace = workspace_lock;
// links should start empty
let links: Links = crate::call_test_ribosome!(host_access, TestWasm::Link, "get_links", ());
assert!(links.into_inner().len() == 0);
// add a couple of links
let link_one: HeaderHash =
crate::call_test_ribosome!(host_access, TestWasm::Link, "create_link", ());
// add a couple of links
let link_two: HeaderHash =
crate::call_test_ribosome!(host_access, TestWasm::Link, "create_link", ());
let links: Links = crate::call_test_ribosome!(host_access, TestWasm::Link, "get_links", ());
assert!(links.into_inner().len() == 2);
// remove a link
let _: HeaderHash =
crate::call_test_ribosome!(host_access, TestWasm::Link, "delete_link", link_one);
let links: Links = crate::call_test_ribosome!(host_access, TestWasm::Link, "get_links", ());
assert!(links.into_inner().len() == 1);
// remove a link
let _: HeaderHash =
crate::call_test_ribosome!(host_access, TestWasm::Link, "delete_link", link_two);
let links: Links = crate::call_test_ribosome!(host_access, TestWasm::Link, "get_links", ());
assert!(links.into_inner().len() == 0);
// Add some links then delete them all
let _h: HeaderHash =
crate::call_test_ribosome!(host_access, TestWasm::Link, "create_link", ());
let _h: HeaderHash =
crate::call_test_ribosome!(host_access, TestWasm::Link, "create_link", ());
let links: Links = crate::call_test_ribosome!(host_access, TestWasm::Link, "get_links", ());
assert!(links.into_inner().len() == 2);
crate::call_test_ribosome!(host_access, TestWasm::Link, "delete_all_links", ());
// Should be no links left
let links: Links = crate::call_test_ribosome!(host_access, TestWasm::Link, "get_links", ());
assert!(links.into_inner().len() == 0);
}
}
| 40.664706 | 100 | 0.634457 |
0aec737a6d0f55b221a4f953c7ed40aadada4f8d | 7,678 | use crate::common::{
configuration::{
genesis_model::{Fund, GenesisYaml, Initial, LinearFees},
jormungandr_config::JormungandrConfig,
node_config_model::{Log, LogEntry, NodeConfig, TrustedPeer},
secret_model::SecretModel,
},
file_utils, jcli_wrapper,
startup::build_genesis_block,
};
use jormungandr_lib::interfaces::Mempool;
pub struct ConfigurationBuilder {
funds: Vec<Fund>,
trusted_peers: Option<Vec<TrustedPeer>>,
public_address: Option<String>,
listen_address: Option<String>,
block0_hash: Option<String>,
block0_consensus: Option<String>,
log: Option<Log>,
bft_slots_ratio: Option<String>,
consensus_genesis_praos_active_slot_coeff: Option<String>,
slots_per_epoch: Option<u32>,
slot_duration: Option<u32>,
epoch_stability_depth: Option<u32>,
kes_update_speed: u32,
linear_fees: LinearFees,
certs: Vec<String>,
consensus_leader_ids: Vec<String>,
mempool: Option<Mempool>,
}
impl ConfigurationBuilder {
pub fn new() -> Self {
ConfigurationBuilder {
funds: vec![],
certs: vec![],
consensus_leader_ids: vec![],
trusted_peers: None,
listen_address: None,
public_address: None,
block0_hash: None,
block0_consensus: Some("bft".to_string()),
slots_per_epoch: None,
slot_duration: None,
epoch_stability_depth: None,
log: Some(Log(vec![LogEntry {
level: Some("info".to_string()),
format: Some("json".to_string()),
}])),
linear_fees: LinearFees {
constant: 0,
coefficient: 0,
certificate: 0,
},
bft_slots_ratio: Some("0.222".to_owned()),
consensus_genesis_praos_active_slot_coeff: Some("0.1".to_owned()),
kes_update_speed: 12 * 3600,
mempool: None,
}
}
pub fn with_slots_per_epoch(&mut self, slots_per_epoch: u32) -> &mut Self {
self.slots_per_epoch = Some(slots_per_epoch);
self
}
pub fn with_slot_duration(&mut self, slot_duration: u32) -> &mut Self {
self.slot_duration = Some(slot_duration);
self
}
pub fn with_epoch_stability_depth(&mut self, epoch_stability_depth: u32) -> &mut Self {
self.epoch_stability_depth = Some(epoch_stability_depth);
self
}
pub fn with_kes_update_speed(&mut self, kes_update_speed: u32) -> &mut Self {
self.kes_update_speed = kes_update_speed;
self
}
pub fn with_linear_fees(&mut self, linear_fees: LinearFees) -> &mut Self {
self.linear_fees = linear_fees;
self
}
pub fn with_consensus_leaders_ids(&mut self, consensus_leader_ids: Vec<String>) -> &mut Self {
self.consensus_leader_ids = consensus_leader_ids;
self
}
pub fn with_initial_certs(&mut self, certs: Vec<String>) -> &mut Self {
self.certs = certs;
self
}
pub fn with_block0_consensus(&mut self, consensus: &str) -> &mut Self {
self.block0_consensus = Some(consensus.to_string());
self
}
pub fn with_consensus_genesis_praos_active_slot_coeff(
&mut self,
active_slot_coeff: &str,
) -> &mut Self {
self.consensus_genesis_praos_active_slot_coeff = Some(active_slot_coeff.to_string());
self
}
pub fn with_bft_slots_ratio(&mut self, slots_ratio: String) -> &mut Self {
self.bft_slots_ratio = Some(slots_ratio);
self
}
pub fn with_funds(&mut self, funds: Vec<Fund>) -> &mut Self {
self.funds = funds.clone();
self
}
pub fn with_log(&mut self, log: Log) -> &mut Self {
self.log = Some(log.clone());
self
}
pub fn with_trusted_peers(&mut self, trusted_peers: Vec<TrustedPeer>) -> &mut Self {
self.trusted_peers = Some(trusted_peers.clone());
self
}
pub fn with_public_address(&mut self, public_address: String) -> &mut Self {
self.public_address = Some(public_address.clone());
self
}
pub fn with_listen_address(&mut self, listen_address: String) -> &mut Self {
self.listen_address = Some(listen_address.clone());
self
}
pub fn with_block_hash(&mut self, block0_hash: String) -> &mut Self {
self.block0_hash = Some(block0_hash.clone());
self
}
pub fn with_mempool(&mut self, mempool: Mempool) -> &mut Self {
self.mempool = Some(mempool);
self
}
pub fn build(&self) -> JormungandrConfig {
let mut node_config = NodeConfig::new();
if let Some(listen_address) = &self.listen_address {
node_config.p2p.listen_address = listen_address.to_string();
}
if let Some(public_address) = &self.public_address {
node_config.p2p.public_address = public_address.to_string();
}
if let Some(mempool) = &self.mempool {
node_config.mempool = mempool.clone();
}
node_config.p2p.trusted_peers = self.trusted_peers.clone();
node_config.log = self.log.clone();
let node_config_path = NodeConfig::serialize(&node_config);
let secret_key = jcli_wrapper::assert_key_generate("ed25519");
let public_key = jcli_wrapper::assert_key_to_public_default(&secret_key);
let mut genesis_model = GenesisYaml::new_with_funds(&self.funds);
let mut leaders_ids = vec![public_key];
leaders_ids.append(&mut self.consensus_leader_ids.clone());
genesis_model.blockchain_configuration.consensus_leader_ids = Some(leaders_ids.clone());
genesis_model.blockchain_configuration.block0_consensus = self.block0_consensus.clone();
genesis_model.blockchain_configuration.bft_slots_ratio = self.bft_slots_ratio.clone();
genesis_model.blockchain_configuration.kes_update_speed = self.kes_update_speed.clone();
if self.slots_per_epoch.is_some() {
genesis_model.blockchain_configuration.slots_per_epoch = self.slots_per_epoch;
}
if self.slot_duration.is_some() {
genesis_model.blockchain_configuration.slot_duration = self.slot_duration;
}
if self.epoch_stability_depth.is_some() {
genesis_model.blockchain_configuration.epoch_stability_depth =
self.epoch_stability_depth;
}
genesis_model
.blockchain_configuration
.consensus_genesis_praos_active_slot_coeff =
self.consensus_genesis_praos_active_slot_coeff.clone();
genesis_model.blockchain_configuration.linear_fees = self.linear_fees.clone();
let certs = self.certs.iter().cloned().map(Initial::Cert);
genesis_model.initial.extend(certs);
let path_to_output_block = build_genesis_block(&genesis_model);
let mut config = JormungandrConfig::from(genesis_model, node_config);
let secret_model = SecretModel::new_bft(&secret_key);
let secret_model_path = SecretModel::serialize(&secret_model);
config.secret_model = secret_model;
config.secret_model_path = secret_model_path;
config.genesis_block_path = path_to_output_block.clone();
config.node_config_path = node_config_path;
config.log_file_path = file_utils::get_path_in_temp("log_file.log");
config.genesis_block_hash = match self.block0_hash {
Some(ref value) => value.clone(),
None => jcli_wrapper::assert_genesis_hash(&path_to_output_block),
};
config
}
}
| 34.9 | 98 | 0.644569 |
56678e701d4947de687159aa92ab80e71d4c1dcc | 3,732 | use crate::consts::KeyNumber;
use core::fmt::{self, Display};
#[cfg(feature = "std")]
extern crate std;
/// The error type which is returned when some `signify` operation fails.
#[derive(Debug, PartialEq)]
pub enum Error {
/// Not enough data was found to parse a structure.
InsufficentData,
/// Parsing a structure's data yielded an error.
InvalidFormat(FormatError),
/// The key algorithm used was unknown and unsupported.
UnsupportedAlgorithm,
/// Attempted to verify a signature with the wrong public key.
MismatchedKey {
/// ID of the key which created the signature.
expected: KeyNumber,
/// ID of the key that tried to verify the signature, but was wrong.
found: KeyNumber,
},
/// The signature didn't match the expected result.
///
/// This could be the result of data corruption or malicious tampering.
///
/// The contents of the message should not be trusted if this is encountered.
BadSignature,
/// Provided password was empty or couldn't decrypt a private key.
BadPassword,
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::InsufficentData => f.write_str("insufficent data while parsing structure"),
Error::InvalidFormat(e) => Display::fmt(e, f),
Error::UnsupportedAlgorithm => f.write_str("encountered unsupported key algorithm"),
Error::MismatchedKey { expected, found } => {
write!(f,
"failed to verify signature: the wrong key was used. Expected {:?}, but found {:?}",
expected,
found,
)
}
Error::BadSignature => f.write_str("signature verification failed"),
Error::BadPassword => f.write_str("password was empty or incorrect for key"),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for Error {}
/// The error that is returned when a file's contents didn't adhere
/// to the `signify` file container format.
#[derive(Debug, PartialEq)]
pub enum FormatError {
/// A comment line exceeded the maximum length or a data line was empty.
LineLength,
/// File was missing the required `untrusted comment: ` preamble.
Comment {
/// The expected comment header.
expected: &'static str,
},
/// File was missing a required line or wasn't correctly newline terminated.
MissingNewline,
/// Provided data wasn't valid base64.
Base64,
}
impl Display for FormatError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
FormatError::LineLength => {
f.write_str("encountered an invalidly formatted line of data")
}
FormatError::Comment { expected } => {
write!(f, "line missing comment; expected {}", expected)
}
FormatError::MissingNewline => f.write_str("expected newline was not found"),
FormatError::Base64 => f.write_str("encountered invalid base64 data"),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for FormatError {}
impl From<FormatError> for Error {
fn from(e: FormatError) -> Self {
Self::InvalidFormat(e)
}
}
#[cfg(test)]
mod tests {
use super::*;
use core::fmt::{Debug, Display};
use static_assertions::assert_impl_all;
#[cfg(feature = "std")]
assert_impl_all!(Error: std::error::Error);
#[cfg(feature = "std")]
assert_impl_all!(FormatError: std::error::Error);
assert_impl_all!(Error: Debug, Display, PartialEq, Send, Sync);
assert_impl_all!(FormatError: Debug, Display, PartialEq, Send, Sync);
}
| 33.927273 | 100 | 0.625134 |
117053e9cd27215cd5cf7be915afeb430d11137e | 30,203 | // Generated from definition io.k8s.api.storage.v1.VolumeAttachment
/// VolumeAttachment captures the intent to attach or detach the specified volume to/from the specified node.
///
/// VolumeAttachment objects are non-namespaced.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct VolumeAttachment {
/// Standard object metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
pub metadata: crate::apimachinery::pkg::apis::meta::v1::ObjectMeta,
/// Specification of the desired attach/detach volume behavior. Populated by the Kubernetes system.
pub spec: crate::api::storage::v1::VolumeAttachmentSpec,
/// Status of the VolumeAttachment request. Populated by the entity completing the attach or detach operation, i.e. the external-attacher.
pub status: Option<crate::api::storage::v1::VolumeAttachmentStatus>,
}
// Begin storage.k8s.io/v1/VolumeAttachment
// Generated from operation createStorageV1VolumeAttachment
impl VolumeAttachment {
/// create a VolumeAttachment
///
/// Use the returned [`crate::ResponseBody`]`<`[`crate::CreateResponse`]`<Self>>` constructor, or [`crate::CreateResponse`]`<Self>` directly, to parse the HTTP response.
///
/// # Arguments
///
/// * `body`
///
/// * `optional`
///
/// Optional parameters. Use `Default::default()` to not pass any.
#[cfg(feature = "api")]
pub fn create_volume_attachment(
body: &crate::api::storage::v1::VolumeAttachment,
optional: crate::CreateOptional<'_>,
) -> Result<(crate::http::Request<Vec<u8>>, fn(crate::http::StatusCode) -> crate::ResponseBody<crate::CreateResponse<Self>>), crate::RequestError> {
let __url = "/apis/storage.k8s.io/v1/volumeattachments?".to_owned();
let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url);
optional.__serialize(&mut __query_pairs);
let __url = __query_pairs.finish();
let __request = crate::http::Request::post(__url);
let __body = crate::serde_json::to_vec(body).map_err(crate::RequestError::Json)?;
let __request = __request.header(crate::http::header::CONTENT_TYPE, crate::http::header::HeaderValue::from_static("application/json"));
match __request.body(__body) {
Ok(request) => Ok((request, crate::ResponseBody::new)),
Err(err) => Err(crate::RequestError::Http(err)),
}
}
}
// Generated from operation deleteStorageV1CollectionVolumeAttachment
impl VolumeAttachment {
/// delete collection of VolumeAttachment
///
/// Use the returned [`crate::ResponseBody`]`<`[`crate::DeleteResponse`]`<`[`crate::List`]`<Self>>>` constructor, or [`crate::DeleteResponse`]`<`[`crate::List`]`<Self>>` directly, to parse the HTTP response.
///
/// # Arguments
///
/// * `delete_optional`
///
/// Delete options. Use `Default::default()` to not pass any.
///
/// * `list_optional`
///
/// List options. Use `Default::default()` to not pass any.
#[cfg(feature = "api")]
pub fn delete_collection_volume_attachment(
delete_optional: crate::DeleteOptional<'_>,
list_optional: crate::ListOptional<'_>,
) -> Result<(crate::http::Request<Vec<u8>>, fn(crate::http::StatusCode) -> crate::ResponseBody<crate::DeleteResponse<crate::List<Self>>>), crate::RequestError> {
let __url = "/apis/storage.k8s.io/v1/volumeattachments?".to_owned();
let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url);
list_optional.__serialize(&mut __query_pairs);
let __url = __query_pairs.finish();
let __request = crate::http::Request::delete(__url);
let __body = crate::serde_json::to_vec(&delete_optional).map_err(crate::RequestError::Json)?;
let __request = __request.header(crate::http::header::CONTENT_TYPE, crate::http::header::HeaderValue::from_static("application/json"));
match __request.body(__body) {
Ok(request) => Ok((request, crate::ResponseBody::new)),
Err(err) => Err(crate::RequestError::Http(err)),
}
}
}
// Generated from operation deleteStorageV1VolumeAttachment
impl VolumeAttachment {
/// delete a VolumeAttachment
///
/// Use the returned [`crate::ResponseBody`]`<`[`crate::DeleteResponse`]`<Self>>` constructor, or [`crate::DeleteResponse`]`<Self>` directly, to parse the HTTP response.
///
/// # Arguments
///
/// * `name`
///
/// name of the VolumeAttachment
///
/// * `optional`
///
/// Optional parameters. Use `Default::default()` to not pass any.
#[cfg(feature = "api")]
pub fn delete_volume_attachment(
name: &str,
optional: crate::DeleteOptional<'_>,
) -> Result<(crate::http::Request<Vec<u8>>, fn(crate::http::StatusCode) -> crate::ResponseBody<crate::DeleteResponse<Self>>), crate::RequestError> {
let __url = format!("/apis/storage.k8s.io/v1/volumeattachments/{name}",
name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET),
);
let __request = crate::http::Request::delete(__url);
let __body = crate::serde_json::to_vec(&optional).map_err(crate::RequestError::Json)?;
let __request = __request.header(crate::http::header::CONTENT_TYPE, crate::http::header::HeaderValue::from_static("application/json"));
match __request.body(__body) {
Ok(request) => Ok((request, crate::ResponseBody::new)),
Err(err) => Err(crate::RequestError::Http(err)),
}
}
}
// Generated from operation listStorageV1VolumeAttachment
impl VolumeAttachment {
/// list or watch objects of kind VolumeAttachment
///
/// This operation only supports listing all items of this type.
///
/// Use the returned [`crate::ResponseBody`]`<`[`crate::ListResponse`]`<Self>>` constructor, or [`crate::ListResponse`]`<Self>` directly, to parse the HTTP response.
///
/// # Arguments
///
/// * `optional`
///
/// Optional parameters. Use `Default::default()` to not pass any.
#[cfg(feature = "api")]
pub fn list_volume_attachment(
optional: crate::ListOptional<'_>,
) -> Result<(crate::http::Request<Vec<u8>>, fn(crate::http::StatusCode) -> crate::ResponseBody<crate::ListResponse<Self>>), crate::RequestError> {
let __url = "/apis/storage.k8s.io/v1/volumeattachments?".to_owned();
let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url);
optional.__serialize(&mut __query_pairs);
let __url = __query_pairs.finish();
let __request = crate::http::Request::get(__url);
let __body = vec![];
match __request.body(__body) {
Ok(request) => Ok((request, crate::ResponseBody::new)),
Err(err) => Err(crate::RequestError::Http(err)),
}
}
}
// Generated from operation patchStorageV1VolumeAttachment
impl VolumeAttachment {
/// partially update the specified VolumeAttachment
///
/// Use the returned [`crate::ResponseBody`]`<`[`crate::PatchResponse`]`<Self>>` constructor, or [`crate::PatchResponse`]`<Self>` directly, to parse the HTTP response.
///
/// # Arguments
///
/// * `name`
///
/// name of the VolumeAttachment
///
/// * `body`
///
/// * `optional`
///
/// Optional parameters. Use `Default::default()` to not pass any.
#[cfg(feature = "api")]
pub fn patch_volume_attachment(
name: &str,
body: &crate::apimachinery::pkg::apis::meta::v1::Patch,
optional: crate::PatchOptional<'_>,
) -> Result<(crate::http::Request<Vec<u8>>, fn(crate::http::StatusCode) -> crate::ResponseBody<crate::PatchResponse<Self>>), crate::RequestError> {
let __url = format!("/apis/storage.k8s.io/v1/volumeattachments/{name}?",
name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET),
);
let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url);
optional.__serialize(&mut __query_pairs);
let __url = __query_pairs.finish();
let __request = crate::http::Request::patch(__url);
let __body = crate::serde_json::to_vec(body).map_err(crate::RequestError::Json)?;
let __request = __request.header(crate::http::header::CONTENT_TYPE, crate::http::header::HeaderValue::from_static(match body {
crate::apimachinery::pkg::apis::meta::v1::Patch::Json(_) => "application/json-patch+json",
crate::apimachinery::pkg::apis::meta::v1::Patch::Merge(_) => "application/merge-patch+json",
crate::apimachinery::pkg::apis::meta::v1::Patch::StrategicMerge(_) => "application/strategic-merge-patch+json",
}));
match __request.body(__body) {
Ok(request) => Ok((request, crate::ResponseBody::new)),
Err(err) => Err(crate::RequestError::Http(err)),
}
}
}
// Generated from operation patchStorageV1VolumeAttachmentStatus
impl VolumeAttachment {
/// partially update status of the specified VolumeAttachment
///
/// Use the returned [`crate::ResponseBody`]`<`[`crate::PatchResponse`]`<Self>>` constructor, or [`crate::PatchResponse`]`<Self>` directly, to parse the HTTP response.
///
/// # Arguments
///
/// * `name`
///
/// name of the VolumeAttachment
///
/// * `body`
///
/// * `optional`
///
/// Optional parameters. Use `Default::default()` to not pass any.
#[cfg(feature = "api")]
pub fn patch_volume_attachment_status(
name: &str,
body: &crate::apimachinery::pkg::apis::meta::v1::Patch,
optional: crate::PatchOptional<'_>,
) -> Result<(crate::http::Request<Vec<u8>>, fn(crate::http::StatusCode) -> crate::ResponseBody<crate::PatchResponse<Self>>), crate::RequestError> {
let __url = format!("/apis/storage.k8s.io/v1/volumeattachments/{name}/status?",
name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET),
);
let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url);
optional.__serialize(&mut __query_pairs);
let __url = __query_pairs.finish();
let __request = crate::http::Request::patch(__url);
let __body = crate::serde_json::to_vec(body).map_err(crate::RequestError::Json)?;
let __request = __request.header(crate::http::header::CONTENT_TYPE, crate::http::header::HeaderValue::from_static(match body {
crate::apimachinery::pkg::apis::meta::v1::Patch::Json(_) => "application/json-patch+json",
crate::apimachinery::pkg::apis::meta::v1::Patch::Merge(_) => "application/merge-patch+json",
crate::apimachinery::pkg::apis::meta::v1::Patch::StrategicMerge(_) => "application/strategic-merge-patch+json",
}));
match __request.body(__body) {
Ok(request) => Ok((request, crate::ResponseBody::new)),
Err(err) => Err(crate::RequestError::Http(err)),
}
}
}
// Generated from operation readStorageV1VolumeAttachment
impl VolumeAttachment {
/// read the specified VolumeAttachment
///
/// Use the returned [`crate::ResponseBody`]`<`[`ReadVolumeAttachmentResponse`]`>` constructor, or [`ReadVolumeAttachmentResponse`] directly, to parse the HTTP response.
///
/// # Arguments
///
/// * `name`
///
/// name of the VolumeAttachment
///
/// * `optional`
///
/// Optional parameters. Use `Default::default()` to not pass any.
#[cfg(feature = "api")]
pub fn read_volume_attachment(
name: &str,
optional: ReadVolumeAttachmentOptional<'_>,
) -> Result<(crate::http::Request<Vec<u8>>, fn(crate::http::StatusCode) -> crate::ResponseBody<ReadVolumeAttachmentResponse>), crate::RequestError> {
let ReadVolumeAttachmentOptional {
exact,
export,
pretty,
} = optional;
let __url = format!("/apis/storage.k8s.io/v1/volumeattachments/{name}?",
name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET),
);
let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url);
if let Some(exact) = exact {
__query_pairs.append_pair("exact", &exact.to_string());
}
if let Some(export) = export {
__query_pairs.append_pair("export", &export.to_string());
}
if let Some(pretty) = pretty {
__query_pairs.append_pair("pretty", pretty);
}
let __url = __query_pairs.finish();
let __request = crate::http::Request::get(__url);
let __body = vec![];
match __request.body(__body) {
Ok(request) => Ok((request, crate::ResponseBody::new)),
Err(err) => Err(crate::RequestError::Http(err)),
}
}
}
/// Optional parameters of [`VolumeAttachment::read_volume_attachment`]
#[cfg(feature = "api")]
#[derive(Clone, Copy, Debug, Default)]
pub struct ReadVolumeAttachmentOptional<'a> {
/// Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'.
pub exact: Option<bool>,
/// Should this value be exported. Export strips fields that a user can not specify.
pub export: Option<bool>,
/// If 'true', then the output is pretty printed.
pub pretty: Option<&'a str>,
}
/// Use `<ReadVolumeAttachmentResponse as Response>::try_from_parts` to parse the HTTP response body of [`VolumeAttachment::read_volume_attachment`]
#[cfg(feature = "api")]
#[derive(Debug)]
pub enum ReadVolumeAttachmentResponse {
Ok(crate::api::storage::v1::VolumeAttachment),
Other(Result<Option<crate::serde_json::Value>, crate::serde_json::Error>),
}
#[cfg(feature = "api")]
impl crate::Response for ReadVolumeAttachmentResponse {
fn try_from_parts(status_code: crate::http::StatusCode, buf: &[u8]) -> Result<(Self, usize), crate::ResponseError> {
match status_code {
crate::http::StatusCode::OK => {
let result = match crate::serde_json::from_slice(buf) {
Ok(value) => value,
Err(ref err) if err.is_eof() => return Err(crate::ResponseError::NeedMoreData),
Err(err) => return Err(crate::ResponseError::Json(err)),
};
Ok((ReadVolumeAttachmentResponse::Ok(result), buf.len()))
},
_ => {
let (result, read) =
if buf.is_empty() {
(Ok(None), 0)
}
else {
match crate::serde_json::from_slice(buf) {
Ok(value) => (Ok(Some(value)), buf.len()),
Err(ref err) if err.is_eof() => return Err(crate::ResponseError::NeedMoreData),
Err(err) => (Err(err), 0),
}
};
Ok((ReadVolumeAttachmentResponse::Other(result), read))
},
}
}
}
// Generated from operation readStorageV1VolumeAttachmentStatus
impl VolumeAttachment {
/// read status of the specified VolumeAttachment
///
/// Use the returned [`crate::ResponseBody`]`<`[`ReadVolumeAttachmentStatusResponse`]`>` constructor, or [`ReadVolumeAttachmentStatusResponse`] directly, to parse the HTTP response.
///
/// # Arguments
///
/// * `name`
///
/// name of the VolumeAttachment
///
/// * `optional`
///
/// Optional parameters. Use `Default::default()` to not pass any.
#[cfg(feature = "api")]
pub fn read_volume_attachment_status(
name: &str,
optional: ReadVolumeAttachmentStatusOptional<'_>,
) -> Result<(crate::http::Request<Vec<u8>>, fn(crate::http::StatusCode) -> crate::ResponseBody<ReadVolumeAttachmentStatusResponse>), crate::RequestError> {
let ReadVolumeAttachmentStatusOptional {
pretty,
} = optional;
let __url = format!("/apis/storage.k8s.io/v1/volumeattachments/{name}/status?",
name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET),
);
let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url);
if let Some(pretty) = pretty {
__query_pairs.append_pair("pretty", pretty);
}
let __url = __query_pairs.finish();
let __request = crate::http::Request::get(__url);
let __body = vec![];
match __request.body(__body) {
Ok(request) => Ok((request, crate::ResponseBody::new)),
Err(err) => Err(crate::RequestError::Http(err)),
}
}
}
/// Optional parameters of [`VolumeAttachment::read_volume_attachment_status`]
#[cfg(feature = "api")]
#[derive(Clone, Copy, Debug, Default)]
pub struct ReadVolumeAttachmentStatusOptional<'a> {
/// If 'true', then the output is pretty printed.
pub pretty: Option<&'a str>,
}
/// Use `<ReadVolumeAttachmentStatusResponse as Response>::try_from_parts` to parse the HTTP response body of [`VolumeAttachment::read_volume_attachment_status`]
#[cfg(feature = "api")]
#[derive(Debug)]
pub enum ReadVolumeAttachmentStatusResponse {
Ok(crate::api::storage::v1::VolumeAttachment),
Other(Result<Option<crate::serde_json::Value>, crate::serde_json::Error>),
}
#[cfg(feature = "api")]
impl crate::Response for ReadVolumeAttachmentStatusResponse {
fn try_from_parts(status_code: crate::http::StatusCode, buf: &[u8]) -> Result<(Self, usize), crate::ResponseError> {
match status_code {
crate::http::StatusCode::OK => {
let result = match crate::serde_json::from_slice(buf) {
Ok(value) => value,
Err(ref err) if err.is_eof() => return Err(crate::ResponseError::NeedMoreData),
Err(err) => return Err(crate::ResponseError::Json(err)),
};
Ok((ReadVolumeAttachmentStatusResponse::Ok(result), buf.len()))
},
_ => {
let (result, read) =
if buf.is_empty() {
(Ok(None), 0)
}
else {
match crate::serde_json::from_slice(buf) {
Ok(value) => (Ok(Some(value)), buf.len()),
Err(ref err) if err.is_eof() => return Err(crate::ResponseError::NeedMoreData),
Err(err) => (Err(err), 0),
}
};
Ok((ReadVolumeAttachmentStatusResponse::Other(result), read))
},
}
}
}
// Generated from operation replaceStorageV1VolumeAttachment
impl VolumeAttachment {
/// replace the specified VolumeAttachment
///
/// Use the returned [`crate::ResponseBody`]`<`[`crate::ReplaceResponse`]`<Self>>` constructor, or [`crate::ReplaceResponse`]`<Self>` directly, to parse the HTTP response.
///
/// # Arguments
///
/// * `name`
///
/// name of the VolumeAttachment
///
/// * `body`
///
/// * `optional`
///
/// Optional parameters. Use `Default::default()` to not pass any.
#[cfg(feature = "api")]
pub fn replace_volume_attachment(
name: &str,
body: &crate::api::storage::v1::VolumeAttachment,
optional: crate::ReplaceOptional<'_>,
) -> Result<(crate::http::Request<Vec<u8>>, fn(crate::http::StatusCode) -> crate::ResponseBody<crate::ReplaceResponse<Self>>), crate::RequestError> {
let __url = format!("/apis/storage.k8s.io/v1/volumeattachments/{name}?",
name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET),
);
let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url);
optional.__serialize(&mut __query_pairs);
let __url = __query_pairs.finish();
let __request = crate::http::Request::put(__url);
let __body = crate::serde_json::to_vec(body).map_err(crate::RequestError::Json)?;
let __request = __request.header(crate::http::header::CONTENT_TYPE, crate::http::header::HeaderValue::from_static("application/json"));
match __request.body(__body) {
Ok(request) => Ok((request, crate::ResponseBody::new)),
Err(err) => Err(crate::RequestError::Http(err)),
}
}
}
// Generated from operation replaceStorageV1VolumeAttachmentStatus
impl VolumeAttachment {
/// replace status of the specified VolumeAttachment
///
/// Use the returned [`crate::ResponseBody`]`<`[`crate::ReplaceResponse`]`<Self>>` constructor, or [`crate::ReplaceResponse`]`<Self>` directly, to parse the HTTP response.
///
/// # Arguments
///
/// * `name`
///
/// name of the VolumeAttachment
///
/// * `body`
///
/// * `optional`
///
/// Optional parameters. Use `Default::default()` to not pass any.
#[cfg(feature = "api")]
pub fn replace_volume_attachment_status(
name: &str,
body: &crate::api::storage::v1::VolumeAttachment,
optional: crate::ReplaceOptional<'_>,
) -> Result<(crate::http::Request<Vec<u8>>, fn(crate::http::StatusCode) -> crate::ResponseBody<crate::ReplaceResponse<Self>>), crate::RequestError> {
let __url = format!("/apis/storage.k8s.io/v1/volumeattachments/{name}/status?",
name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET),
);
let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url);
optional.__serialize(&mut __query_pairs);
let __url = __query_pairs.finish();
let __request = crate::http::Request::put(__url);
let __body = crate::serde_json::to_vec(body).map_err(crate::RequestError::Json)?;
let __request = __request.header(crate::http::header::CONTENT_TYPE, crate::http::header::HeaderValue::from_static("application/json"));
match __request.body(__body) {
Ok(request) => Ok((request, crate::ResponseBody::new)),
Err(err) => Err(crate::RequestError::Http(err)),
}
}
}
// Generated from operation watchStorageV1VolumeAttachment
impl VolumeAttachment {
/// list or watch objects of kind VolumeAttachment
///
/// This operation only supports watching one item, or a list of items, of this type for changes.
///
/// Use the returned [`crate::ResponseBody`]`<`[`crate::WatchResponse`]`<Self>>` constructor, or [`crate::WatchResponse`]`<Self>` directly, to parse the HTTP response.
///
/// # Arguments
///
/// * `optional`
///
/// Optional parameters. Use `Default::default()` to not pass any.
#[cfg(feature = "api")]
pub fn watch_volume_attachment(
optional: crate::WatchOptional<'_>,
) -> Result<(crate::http::Request<Vec<u8>>, fn(crate::http::StatusCode) -> crate::ResponseBody<crate::WatchResponse<Self>>), crate::RequestError> {
let __url = "/apis/storage.k8s.io/v1/volumeattachments?".to_owned();
let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url);
optional.__serialize(&mut __query_pairs);
let __url = __query_pairs.finish();
let __request = crate::http::Request::get(__url);
let __body = vec![];
match __request.body(__body) {
Ok(request) => Ok((request, crate::ResponseBody::new)),
Err(err) => Err(crate::RequestError::Http(err)),
}
}
}
// End storage.k8s.io/v1/VolumeAttachment
impl crate::Resource for VolumeAttachment {
const API_VERSION: &'static str = "storage.k8s.io/v1";
const GROUP: &'static str = "storage.k8s.io";
const KIND: &'static str = "VolumeAttachment";
const VERSION: &'static str = "v1";
}
impl crate::ListableResource for VolumeAttachment {
const LIST_KIND: &'static str = "VolumeAttachmentList";
}
impl crate::Metadata for VolumeAttachment {
type Ty = crate::apimachinery::pkg::apis::meta::v1::ObjectMeta;
fn metadata(&self) -> &<Self as crate::Metadata>::Ty {
&self.metadata
}
fn metadata_mut(&mut self) -> &mut<Self as crate::Metadata>::Ty {
&mut self.metadata
}
}
impl<'de> crate::serde::Deserialize<'de> for VolumeAttachment {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: crate::serde::Deserializer<'de> {
#[allow(non_camel_case_types)]
enum Field {
Key_api_version,
Key_kind,
Key_metadata,
Key_spec,
Key_status,
Other,
}
impl<'de> crate::serde::Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: crate::serde::Deserializer<'de> {
struct Visitor;
impl<'de> crate::serde::de::Visitor<'de> for Visitor {
type Value = Field;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("field identifier")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: crate::serde::de::Error {
Ok(match v {
"apiVersion" => Field::Key_api_version,
"kind" => Field::Key_kind,
"metadata" => Field::Key_metadata,
"spec" => Field::Key_spec,
"status" => Field::Key_status,
_ => Field::Other,
})
}
}
deserializer.deserialize_identifier(Visitor)
}
}
struct Visitor;
impl<'de> crate::serde::de::Visitor<'de> for Visitor {
type Value = VolumeAttachment;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(<Self::Value as crate::Resource>::KIND)
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: crate::serde::de::MapAccess<'de> {
let mut value_metadata: Option<crate::apimachinery::pkg::apis::meta::v1::ObjectMeta> = None;
let mut value_spec: Option<crate::api::storage::v1::VolumeAttachmentSpec> = None;
let mut value_status: Option<crate::api::storage::v1::VolumeAttachmentStatus> = None;
while let Some(key) = crate::serde::de::MapAccess::next_key::<Field>(&mut map)? {
match key {
Field::Key_api_version => {
let value_api_version: String = crate::serde::de::MapAccess::next_value(&mut map)?;
if value_api_version != <Self::Value as crate::Resource>::API_VERSION {
return Err(crate::serde::de::Error::invalid_value(crate::serde::de::Unexpected::Str(&value_api_version), &<Self::Value as crate::Resource>::API_VERSION));
}
},
Field::Key_kind => {
let value_kind: String = crate::serde::de::MapAccess::next_value(&mut map)?;
if value_kind != <Self::Value as crate::Resource>::KIND {
return Err(crate::serde::de::Error::invalid_value(crate::serde::de::Unexpected::Str(&value_kind), &<Self::Value as crate::Resource>::KIND));
}
},
Field::Key_metadata => value_metadata = Some(crate::serde::de::MapAccess::next_value(&mut map)?),
Field::Key_spec => value_spec = Some(crate::serde::de::MapAccess::next_value(&mut map)?),
Field::Key_status => value_status = crate::serde::de::MapAccess::next_value(&mut map)?,
Field::Other => { let _: crate::serde::de::IgnoredAny = crate::serde::de::MapAccess::next_value(&mut map)?; },
}
}
Ok(VolumeAttachment {
metadata: value_metadata.ok_or_else(|| crate::serde::de::Error::missing_field("metadata"))?,
spec: value_spec.ok_or_else(|| crate::serde::de::Error::missing_field("spec"))?,
status: value_status,
})
}
}
deserializer.deserialize_struct(
<Self as crate::Resource>::KIND,
&[
"apiVersion",
"kind",
"metadata",
"spec",
"status",
],
Visitor,
)
}
}
impl crate::serde::Serialize for VolumeAttachment {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: crate::serde::Serializer {
let mut state = serializer.serialize_struct(
<Self as crate::Resource>::KIND,
4 +
self.status.as_ref().map_or(0, |_| 1),
)?;
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "apiVersion", <Self as crate::Resource>::API_VERSION)?;
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "kind", <Self as crate::Resource>::KIND)?;
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "metadata", &self.metadata)?;
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "spec", &self.spec)?;
if let Some(value) = &self.status {
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "status", value)?;
}
crate::serde::ser::SerializeStruct::end(state)
}
}
| 43.96361 | 211 | 0.601099 |
67c42eee25662bcaed207ff839a89df08afd9ed6 | 8,570 | // Copyright (c) 2017-2018 ETH Zurich
// Fabian Schuiki <[email protected]>
//! A git repository and context for command execution.
#![deny(missing_docs)]
use std::path::Path;
use std::process::Command;
use std::ffi::OsStr;
use futures::Future;
use futures::future;
use tokio_process::CommandExt;
use error::*;
use sess::SessionIo;
/// A git repository.
///
/// This struct is used to interact with git repositories on disk. It makes
/// heavy use of futures to execute the different tasks.
#[derive(Copy, Clone)]
pub struct Git<'io, 'sess: 'io, 'ctx: 'sess> {
/// The path to the repository.
pub path: &'ctx Path,
/// The session within which commands will be executed.
pub sess: &'io SessionIo<'sess, 'ctx>,
}
impl<'git, 'io, 'sess: 'io, 'ctx: 'sess> Git<'io, 'sess, 'ctx> {
/// Create a new git context.
pub fn new(path: &'ctx Path, sess: &'io SessionIo<'sess, 'ctx>) -> Git<'io, 'sess, 'ctx> {
Git {
path: path,
sess: sess,
}
}
/// Create a new git command.
///
/// The command will have the form `git <subcommand>` and be pre-configured
/// to operate in the repository's path.
pub fn command(self, subcommand: &str) -> Command {
let mut cmd = Command::new(&self.sess.sess.config.git);
cmd.arg(subcommand);
cmd.current_dir(&self.path);
cmd
}
/// Schedule a command for execution.
///
/// Configures the command's stdout and stderr to be captured and wires up
/// appropriate error handling. In case the command fails, the exact
/// arguments to the command are emitted together with the captured output.
/// The command is spawned asynchronously on the session's reactor core.
/// Returns a future that will resolve to the command's stdout.
///
/// If `check` is false, the stdout will be returned regardless of the
/// command's exit code.
pub fn spawn(self, mut cmd: Command, check: bool) -> GitFuture<'io, String> {
let output = cmd
.output_async(&self.sess.handle)
.map_err(|cause| Error::chain(
"Failed to spawn child process.",
cause
));
let result = output.and_then(move |output|{
debugln!("git: {:?} in {:?}", cmd, self.path);
if output.status.success() || !check {
String::from_utf8(output.stdout).map_err(|cause| Error::chain(
format!("Output of git command ({:?}) in directory {:?} is not valid UTF-8.", cmd, self.path),
cause
))
} else {
let mut msg = format!("Git command ({:?}) in directory {:?}", cmd, self.path);
match output.status.code() {
Some(code) => msg.push_str(&format!(" failed with exit code {}", code)),
None => msg.push_str(" failed"),
};
match String::from_utf8(output.stderr) {
Ok(txt) => {
msg.push_str(":\n\n");
msg.push_str(&txt);
}
Err(err) => msg.push_str(&format!(". Stderr is not valid UTF-8, {}.", err)),
};
Err(Error::new(msg))
}
});
Box::new(result)
}
/// Assemble a command and schedule it for execution.
///
/// This is a convenience function that creates a command, passses it to the
/// closure `f` for configuration, then passes it to the `spawn` function
/// and returns the future.
pub fn spawn_with<F>(self, f: F) -> GitFuture<'io, String>
where F: FnOnce(&mut Command) -> &mut Command
{
let mut cmd = Command::new(&self.sess.sess.config.git);
cmd.current_dir(&self.path);
f(&mut cmd);
self.spawn(cmd, true)
}
/// Assemble a command and schedule it for execution.
///
/// This is the same as `spawn_with()`, but returns the stdout regardless of
/// whether the command failed or not.
pub fn spawn_unchecked_with<F>(self, f: F) -> GitFuture<'io, String>
where F: FnOnce(&mut Command) -> &mut Command
{
let mut cmd = Command::new(&self.sess.sess.config.git);
cmd.current_dir(&self.path);
f(&mut cmd);
self.spawn(cmd, false)
}
/// Fetch the tags and refs of a remote.
pub fn fetch(self, remote: &str) -> GitFuture<'io, ()> {
let r1 = String::from(remote);
let r2 = String::from(remote);
Box::new(self.spawn_with(move |c| c
.arg("fetch")
.arg("--prune")
.arg(r1)
).and_then(move |_| self.spawn_with(|c| c
.arg("fetch")
.arg("--tags")
.arg("--prune")
.arg(r2)
)).map(|_| ()))
}
/// List all refs and their hashes.
pub fn list_refs(self) -> GitFuture<'io, Vec<(String, String)>> {
Box::new(self.spawn_unchecked_with(|c|
c.arg("show-ref")
).and_then(move |raw| {
future::join_all(raw.lines().map(|line|{
// Parse the line.
let mut fields = line.split_whitespace().map(String::from);
// TODO: Handle the case where the line might not contain enough
// information or is missing some fields.
let mut rev = fields.next().unwrap();
let rf = fields.next().unwrap();
rev.push_str("^{commit}");
// Parse the ref. This is needed since the ref for an annotated
// tag points to the hash of the tag itself, rather than the
// underlying commit. By callign `git rev-parse` with the ref
// augmented with `^{commit}`, we can ensure that we always end
// up with a commit hash.
self.spawn_with(|c| c.arg("rev-parse").arg("--verify").arg(rev))
.map(|rev| (rev.trim().into(), rf))
}).collect::<Vec<_>>())
}))
}
/// List all revisions.
pub fn list_revs(self) -> GitFuture<'io, Vec<String>> {
Box::new(
self.spawn_with(|c| c.arg("rev-list").arg("--all").arg("--date-order"))
.map(|raw| raw.lines().map(String::from).collect())
)
}
/// Determine the currently checked out revision.
pub fn current_checkout(self) -> GitFuture<'io, Option<String>> {
Box::new(
self.spawn_with(|c| c
.arg("rev-parse")
.arg("--revs-only")
.arg("HEAD^{commit}"))
.map(|raw| raw.lines().take(1).map(String::from).next())
)
}
/// List files in the directory.
///
/// Calls `git ls-tree` under the hood.
pub fn list_files<R: AsRef<OsStr>, P: AsRef<OsStr>>(
self,
rev: R,
path: Option<P>
) -> GitFuture<'io, Vec<TreeEntry>> {
Box::new(
self.spawn_with(|c| {
c.arg("ls-tree").arg(rev);
if let Some(p) = path {
c.arg(p);
}
c
}).map(|raw| raw.lines().map(TreeEntry::parse).collect())
)
}
/// Read the content of a file.
pub fn cat_file<O: AsRef<OsStr>>(self, hash: O) -> GitFuture<'io, String> {
Box::new(
self.spawn_with(|c| c
.arg("cat-file")
.arg("blob")
.arg(hash))
)
}
}
/// A future returned from any of the git functions.
pub type GitFuture<'io, T> = Box<Future<Item=T, Error=Error> + 'io>;
/// A single entry in a git tree.
///
/// The `list_files` command returns a vector of these.
pub struct TreeEntry {
/// The name of the file.
pub name: String,
/// The hash of the entry.
pub hash: String,
/// The kind of the entry. Usually `blob` or `tree`.
pub kind: String,
/// The mode of the entry, i.e. its permissions.
pub mode: String,
}
impl TreeEntry {
/// Parse a single line of output of `git ls-tree`.
pub fn parse(input: &str) -> TreeEntry {
let tab = input.find('\t').unwrap();
let (metadata, name) = input.split_at(tab);
let mut iter = metadata.split(' ');
let mode = iter.next().unwrap();
let kind = iter.next().unwrap();
let hash = iter.next().unwrap();
TreeEntry {
name: name.into(),
hash: hash.into(),
kind: kind.into(),
mode: mode.into(),
}
}
}
| 34.979592 | 114 | 0.531272 |
1d460fbfc7b67e7307d76665749586998bb24c5d | 20,219 | #[cfg(feature = "actix-multipart")]
use super::schema::TypedData;
use super::{
models::{
DefaultOperationRaw, DefaultSchemaRaw, Either, Items, Parameter, ParameterIn, Response,
SecurityScheme,
},
schema::{Apiv2Errors, Apiv2Operation, Apiv2Schema},
};
use crate::util::{ready, Ready};
use actix_web::{
http::StatusCode,
web::{Bytes, Data, Form, Json, Path, Payload, Query},
Error, HttpRequest, HttpResponse, Responder,
};
use pin_project::pin_project;
use serde::Serialize;
#[cfg(feature = "serde_qs")]
use serde_qs::actix::QsQuery;
use std::{
collections::BTreeMap,
fmt,
future::Future,
pin::Pin,
task::{Context, Poll},
};
/// Actix-specific trait for indicating that this entity can modify an operation
/// and/or update the global map of definitions.
pub trait OperationModifier: Apiv2Schema + Sized {
/// Update the parameters list in the given operation (if needed).
fn update_parameter(_op: &mut DefaultOperationRaw) {}
/// Update the responses map in the given operation (if needed).
fn update_response(_op: &mut DefaultOperationRaw) {}
/// Update the definitions map (if needed).
fn update_definitions(map: &mut BTreeMap<String, DefaultSchemaRaw>) {
update_definitions_from_schema_type::<Self>(map);
}
/// Update the security map in the given operation (if needed).
fn update_security(op: &mut DefaultOperationRaw) {
update_security::<Self>(op);
}
/// Update the security definition map (if needed).
fn update_security_definitions(map: &mut BTreeMap<String, SecurityScheme>) {
update_security_definitions::<Self>(map);
}
}
/// All schema types default to updating the definitions map.
#[cfg(feature = "nightly")]
impl<T> OperationModifier for T
where
T: Apiv2Schema,
{
default fn update_parameter(_op: &mut DefaultOperationRaw) {}
default fn update_response(_op: &mut DefaultOperationRaw) {}
default fn update_definitions(map: &mut BTreeMap<String, DefaultSchemaRaw>) {
update_definitions_from_schema_type::<Self>(map);
}
default fn update_security(op: &mut DefaultOperationRaw) {
update_security::<Self>(op);
}
default fn update_security_definitions(map: &mut BTreeMap<String, SecurityScheme>) {
update_security_definitions::<Self>(map);
}
}
impl<T> OperationModifier for Option<T>
where
T: OperationModifier,
{
fn update_parameter(op: &mut DefaultOperationRaw) {
T::update_parameter(op);
}
fn update_response(op: &mut DefaultOperationRaw) {
T::update_response(op);
}
fn update_definitions(map: &mut BTreeMap<String, DefaultSchemaRaw>) {
T::update_definitions(map);
}
fn update_security(op: &mut DefaultOperationRaw) {
T::update_security(op);
}
fn update_security_definitions(map: &mut BTreeMap<String, SecurityScheme>) {
T::update_security_definitions(map);
}
}
#[cfg(feature = "nightly")]
impl<T, E> OperationModifier for Result<T, E>
where
T: OperationModifier,
{
default fn update_parameter(op: &mut DefaultOperationRaw) {
T::update_parameter(op);
}
default fn update_response(op: &mut DefaultOperationRaw) {
T::update_response(op);
}
default fn update_definitions(map: &mut BTreeMap<String, DefaultSchemaRaw>) {
T::update_definitions(map);
}
default fn update_security_definitions(map: &mut BTreeMap<String, SecurityScheme>) {
T::update_security_definitions(map);
}
}
impl<T, E> OperationModifier for Result<T, E>
where
T: OperationModifier,
E: Apiv2Errors,
{
fn update_parameter(op: &mut DefaultOperationRaw) {
T::update_parameter(op);
}
fn update_response(op: &mut DefaultOperationRaw) {
T::update_response(op);
E::update_error_definitions(op);
}
fn update_definitions(map: &mut BTreeMap<String, DefaultSchemaRaw>) {
T::update_definitions(map);
E::update_definitions(map);
}
fn update_security_definitions(map: &mut BTreeMap<String, SecurityScheme>) {
T::update_security_definitions(map);
}
}
// We don't know what we should do with these abstractions
// as they could be anything.
impl<T> Apiv2Schema for Data<T> {}
#[cfg(not(feature = "nightly"))]
impl<T> OperationModifier for Data<T> {}
macro_rules! impl_empty({ $($ty:ty),+ } => {
$(
impl Apiv2Schema for $ty {}
#[cfg(not(feature = "nightly"))]
impl OperationModifier for $ty {}
)+
});
impl Apiv2Operation for HttpResponse {
fn operation() -> DefaultOperationRaw {
Default::default()
}
fn security_definitions() -> BTreeMap<String, SecurityScheme> {
Default::default()
}
fn definitions() -> BTreeMap<String, DefaultSchemaRaw> {
Default::default()
}
}
impl_empty!(HttpRequest, HttpResponse, Bytes, Payload);
#[cfg(not(feature = "nightly"))]
mod manual_impl {
use super::OperationModifier;
impl<'a> OperationModifier for &'a str {}
impl<'a, T: OperationModifier> OperationModifier for &'a [T] {}
macro_rules! impl_simple({ $ty:ty } => {
impl OperationModifier for $ty {}
});
impl_simple!(char);
impl_simple!(String);
impl_simple!(bool);
impl_simple!(f32);
impl_simple!(f64);
impl_simple!(i8);
impl_simple!(i16);
impl_simple!(i32);
impl_simple!(u8);
impl_simple!(u16);
impl_simple!(u32);
impl_simple!(i64);
impl_simple!(i128);
impl_simple!(isize);
impl_simple!(u64);
impl_simple!(u128);
impl_simple!(usize);
#[cfg(feature = "chrono")]
impl_simple!(chrono::NaiveDateTime);
#[cfg(feature = "rust_decimal")]
impl_simple!(rust_decimal::Decimal);
#[cfg(feature = "uuid")]
impl_simple!(uuid::Uuid);
}
#[cfg(feature = "chrono")]
impl<T: chrono::TimeZone> OperationModifier for chrono::DateTime<T> {}
// Other extractors
#[cfg(feature = "nightly")]
impl<T> Apiv2Schema for Json<T> {
default const NAME: Option<&'static str> = None;
default fn raw_schema() -> DefaultSchemaRaw {
Default::default()
}
}
/// JSON needs specialization because it updates the global definitions.
impl<T: Apiv2Schema> Apiv2Schema for Json<T> {
const NAME: Option<&'static str> = T::NAME;
fn raw_schema() -> DefaultSchemaRaw {
T::raw_schema()
}
}
impl<T> OperationModifier for Json<T>
where
T: Apiv2Schema,
{
fn update_parameter(op: &mut DefaultOperationRaw) {
op.parameters.push(Either::Right(Parameter {
description: None,
in_: ParameterIn::Body,
name: "body".into(),
required: true,
schema: Some({
let mut def = T::schema_with_ref();
def.retain_ref();
def
}),
..Default::default()
}));
}
fn update_response(op: &mut DefaultOperationRaw) {
op.responses.insert(
"200".into(),
Either::Right(Response {
// TODO: Support configuring other 2xx codes using macro attribute.
description: Some("OK".into()),
schema: Some({
let mut def = T::schema_with_ref();
def.retain_ref();
def
}),
..Default::default()
}),
);
}
}
#[cfg(feature = "actix-multipart")]
impl OperationModifier for actix_multipart::Multipart {
fn update_parameter(op: &mut DefaultOperationRaw) {
op.parameters.push(Either::Right(Parameter {
description: None,
in_: ParameterIn::FormData,
name: "file_data".into(),
required: true,
data_type: Some(<actix_multipart::Multipart as TypedData>::data_type()),
format: <actix_multipart::Multipart as TypedData>::format(),
..Default::default()
}));
}
}
#[cfg(feature = "actix-session")]
impl OperationModifier for actix_session::Session {
fn update_definitions(_map: &mut BTreeMap<String, DefaultSchemaRaw>) {}
}
#[cfg(feature = "actix-files")]
impl OperationModifier for actix_files::NamedFile {
fn update_definitions(_map: &mut BTreeMap<String, DefaultSchemaRaw>) {}
}
macro_rules! impl_param_extractor ({ $ty:ty => $container:ident } => {
#[cfg(feature = "nightly")]
impl<T> Apiv2Schema for $ty {
default const NAME: Option<&'static str> = None;
default fn raw_schema() -> DefaultSchemaRaw {
Default::default()
}
}
#[cfg(not(feature = "nightly"))]
impl<T: Apiv2Schema> Apiv2Schema for $ty {}
impl<T: Apiv2Schema> OperationModifier for $ty {
fn update_parameter(op: &mut DefaultOperationRaw) {
let def = T::raw_schema();
// If there aren't any properties and if it's a path parameter,
// then add a parameter whose name will be overridden later.
if def.properties.is_empty() && ParameterIn::$container == ParameterIn::Path {
op.parameters.push(Either::Right(Parameter {
name: String::new(),
in_: ParameterIn::Path,
required: true,
data_type: def.data_type,
format: def.format,
enum_: def.enum_,
description: def.description,
..Default::default()
}));
}
for (k, v) in def.properties {
op.parameters.push(Either::Right(Parameter {
in_: ParameterIn::$container,
required: def.required.contains(&k),
data_type: v.data_type,
format: v.format,
enum_: v.enum_,
description: v.description,
collection_format: None, // this defaults to csv
items: v.items.as_deref().map(map_schema_to_items),
name: k,
..Default::default()
}));
}
}
// These don't require updating definitions, as we use them only
// to get their properties.
fn update_definitions(_map: &mut BTreeMap<String, DefaultSchemaRaw>) {}
}
});
fn map_schema_to_items(schema: &DefaultSchemaRaw) -> Items {
Items {
data_type: schema.data_type,
format: schema.format.clone(),
collection_format: None, // this defaults to csv
enum_: schema.enum_.clone(),
items: schema
.items
.as_deref()
.map(|schema| Box::new(map_schema_to_items(schema))),
..Default::default() // range fields are not emitted
}
}
/// `formData` can refer to the global definitions.
#[cfg(feature = "nightly")]
impl<T: Apiv2Schema> Apiv2Schema for Form<T> {
const NAME: Option<&'static str> = T::NAME;
fn raw_schema() -> DefaultSchemaRaw {
T::raw_schema()
}
}
impl_param_extractor!(Path<T> => Path);
impl_param_extractor!(Query<T> => Query);
impl_param_extractor!(Form<T> => FormData);
#[cfg(feature = "serde_qs")]
impl_param_extractor!(QsQuery<T> => Query);
macro_rules! impl_path_tuple ({ $($ty:ident),+ } => {
#[cfg(feature = "nightly")]
impl<$($ty,)+> Apiv2Schema for Path<($($ty,)+)> {}
#[cfg(not(feature = "nightly"))]
impl<$($ty: Apiv2Schema,)+> Apiv2Schema for Path<($($ty,)+)> {}
impl<$($ty,)+> OperationModifier for Path<($($ty,)+)>
where $($ty: Apiv2Schema,)+
{
fn update_parameter(op: &mut DefaultOperationRaw) {
$(
let def = $ty::raw_schema();
if def.properties.is_empty() {
op.parameters.push(Either::Right(Parameter {
// NOTE: We're setting empty name, because we don't know
// the name in this context. We'll get it when we add services.
name: String::new(),
in_: ParameterIn::Path,
required: true,
data_type: def.data_type,
format: def.format,
enum_: def.enum_,
description: def.description,
..Default::default()
}));
}
for (k, v) in def.properties {
op.parameters.push(Either::Right(Parameter {
in_: ParameterIn::Path,
required: def.required.contains(&k),
data_type: v.data_type,
format: v.format,
enum_: v.enum_,
description: v.description,
collection_format: None, // this defaults to csv
items: v.items.as_deref().map(map_schema_to_items),
name: k,
..Default::default()
}));
}
)+
}
}
});
impl_path_tuple!(A);
impl_path_tuple!(A, B);
impl_path_tuple!(A, B, C);
impl_path_tuple!(A, B, C, D);
impl_path_tuple!(A, B, C, D, E);
/// Wrapper for wrapping over `impl Responder` thingies (to avoid breakage).
pub struct ResponderWrapper<T>(pub T);
#[cfg(feature = "nightly")]
impl<T: Responder> Apiv2Schema for ResponderWrapper<T> {
default const NAME: Option<&'static str> = None;
default fn raw_schema() -> DefaultSchemaRaw {
DefaultSchemaRaw::default()
}
}
#[cfg(not(feature = "nightly"))]
impl<T: Responder> Apiv2Schema for ResponderWrapper<T> {}
#[cfg(not(feature = "nightly"))]
impl<T: Responder> OperationModifier for ResponderWrapper<T> {}
impl<T: Responder> Responder for ResponderWrapper<T> {
type Error = T::Error;
type Future = T::Future;
#[inline]
fn respond_to(self, req: &HttpRequest) -> Self::Future {
self.0.respond_to(req)
}
}
/// Wrapper for all response types from handlers. This holds the actual value
/// returned by the handler and a unit struct (autogenerated by the plugin) which
/// is used for generating operation information.
#[pin_project]
pub struct ResponseWrapper<T, H>(#[pin] pub T, pub H);
impl<T: Responder, H> Responder for ResponseWrapper<T, H> {
type Error = <T as Responder>::Error;
type Future = <T as Responder>::Future;
#[inline]
fn respond_to(self, req: &HttpRequest) -> Self::Future {
self.0.respond_to(req)
}
}
impl<F, T, H> Future for ResponseWrapper<F, H>
where
F: Future<Output = T>,
T: OperationModifier + Responder,
H: Apiv2Operation,
{
type Output = T;
#[inline]
fn poll(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.as_mut().project();
this.0.poll(ctx)
}
}
impl<F, T, H> Apiv2Operation for ResponseWrapper<F, H>
where
F: Future<Output = T>,
T: OperationModifier + Responder,
H: Apiv2Operation,
{
fn operation() -> DefaultOperationRaw {
H::operation()
}
fn security_definitions() -> BTreeMap<String, SecurityScheme> {
H::security_definitions()
}
fn definitions() -> BTreeMap<String, DefaultSchemaRaw> {
H::definitions()
}
}
/// Given the schema type, recursively update the map of definitions.
fn update_definitions_from_schema_type<T>(map: &mut BTreeMap<String, DefaultSchemaRaw>)
where
T: Apiv2Schema,
{
let mut schema = T::schema_with_ref();
loop {
if let Some(s) = schema.items {
schema = *s;
continue;
} else if let Some(Either::Right(s)) = schema.extra_props {
schema = *s;
continue;
} else if let Some(n) = schema.name.take() {
schema.remove_refs();
map.insert(n, schema);
}
break;
}
}
/// Add security requirements to operation.
fn update_security<T>(op: &mut DefaultOperationRaw)
where
T: Apiv2Schema,
{
if let (Some(name), Some(scheme)) = (T::NAME, T::security_scheme()) {
let mut security_map = BTreeMap::new();
let scopes = scheme.scopes.keys().map(String::clone).collect();
security_map.insert(name.into(), scopes);
op.security.push(security_map);
}
}
/// Merge security scheme into existing security definitions or add new.
fn update_security_definitions<T>(map: &mut BTreeMap<String, SecurityScheme>)
where
T: Apiv2Schema,
{
if let (Some(name), Some(new)) = (T::NAME, T::security_scheme()) {
new.update_definitions(name, map);
}
}
macro_rules! json_with_status {
($name:ident => $status:expr) => {
pub struct $name<T: Serialize + Apiv2Schema>(pub T);
impl<T> fmt::Debug for $name<T>
where
T: fmt::Debug + Serialize + Apiv2Schema,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let status: StatusCode = $status;
let status_str = status.canonical_reason().unwrap_or(status.as_str());
write!(f, "{} Json: {:?}", status_str, self.0)
}
}
impl<T> fmt::Display for $name<T>
where
T: fmt::Display + Serialize + Apiv2Schema,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
impl<T> Responder for $name<T>
where
T: Serialize + Apiv2Schema,
{
type Error = Error;
type Future = Ready<Result<HttpResponse, Error>>;
fn respond_to(self, _: &HttpRequest) -> Self::Future {
let status: StatusCode = $status;
let body = match serde_json::to_string(&self.0) {
Ok(body) => body,
Err(e) => return ready(Err(e.into())),
};
ready(Ok(HttpResponse::build(status)
.content_type("application/json")
.body(body)))
}
}
impl<T> Apiv2Schema for $name<T>
where
T: Serialize + Apiv2Schema,
{
const NAME: Option<&'static str> = T::NAME;
fn raw_schema() -> DefaultSchemaRaw {
T::raw_schema()
}
}
impl<T> OperationModifier for $name<T>
where
T: Serialize + Apiv2Schema,
{
fn update_response(op: &mut DefaultOperationRaw) {
let status: StatusCode = $status;
op.responses.insert(
status.as_str().into(),
Either::Right(Response {
description: status.canonical_reason().map(ToString::to_string),
schema: Some({
let mut def = T::schema_with_ref();
def.retain_ref();
def
}),
..Default::default()
}),
);
}
}
};
}
json_with_status!(CreatedJson => StatusCode::CREATED);
json_with_status!(AcceptedJson => StatusCode::ACCEPTED);
#[derive(Debug)]
pub struct NoContent;
impl fmt::Display for NoContent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("No Content")
}
}
impl Responder for NoContent {
type Error = Error;
type Future = Ready<Result<HttpResponse, Error>>;
fn respond_to(self, _: &HttpRequest) -> Self::Future {
ready(Ok(HttpResponse::build(StatusCode::NO_CONTENT)
.content_type("application/json")
.finish()))
}
}
impl Apiv2Schema for NoContent {}
impl OperationModifier for NoContent {
fn update_response(op: &mut DefaultOperationRaw) {
let status = StatusCode::NO_CONTENT;
op.responses.insert(
status.as_str().into(),
Either::Right(Response {
description: status.canonical_reason().map(ToString::to_string),
schema: None,
..Default::default()
}),
);
}
}
| 30.087798 | 95 | 0.578861 |
fe096fa6e6c8d418feb388a7bf32010dd3682e8d | 6,173 | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use super::MVHashMap;
use proptest::{collection::vec, prelude::*, sample::Index, strategy::Strategy};
use std::{
collections::{BTreeMap, HashMap},
fmt::Debug,
hash::Hash,
sync::atomic::{AtomicUsize, Ordering},
};
const DEFAULT_TIMEOUT: u64 = 30;
#[derive(Debug, Clone)]
enum Operator<V: Debug + Clone> {
Insert(V),
Remove,
Skip,
Read,
}
#[derive(Debug, Clone, PartialEq)]
enum ExpectedOutput<V: Debug + Clone + PartialEq> {
NotInMap,
Deleted,
Value(V),
}
struct Baseline<K, V>(HashMap<K, BTreeMap<usize, Option<V>>>);
impl<K, V> Baseline<K, V>
where
K: Hash + Eq + Clone,
V: Clone + Debug + PartialEq,
{
pub fn new(txns: &[(K, Operator<V>)]) -> Self {
let mut baseline: HashMap<K, BTreeMap<usize, Option<V>>> = HashMap::new();
for (idx, (k, op)) in txns.iter().enumerate() {
let value_to_update = match op {
Operator::Insert(v) => Some(v.clone()),
Operator::Remove => None,
Operator::Skip | Operator::Read => continue,
};
baseline
.entry(k.clone())
.or_insert_with(BTreeMap::new)
.insert(idx, value_to_update);
}
Self(baseline)
}
pub fn get(&self, key: &K, version: usize) -> ExpectedOutput<V> {
match self
.0
.get(key)
.and_then(|tree| tree.range(..version).last())
{
None => ExpectedOutput::NotInMap,
Some((_, Some(v))) => ExpectedOutput::Value(v.clone()),
Some((_, None)) => ExpectedOutput::Deleted,
}
}
}
fn operator_strategy<V: Arbitrary + Clone>() -> impl Strategy<Value = Operator<V>> {
prop_oneof![
2 => any::<V>().prop_map(Operator::Insert),
1 => Just(Operator::Remove),
1 => Just(Operator::Skip),
4 => Just(Operator::Read),
]
}
fn run_and_assert<K, V>(
universe: Vec<K>,
transaction_gens: Vec<(Index, Operator<V>)>,
) -> Result<(), TestCaseError>
where
K: PartialOrd + Send + Clone + Hash + Eq + Sync,
V: Send + Debug + Clone + PartialEq + Sync,
{
let transactions: Vec<(K, Operator<V>)> = transaction_gens
.into_iter()
.map(|(idx, op)| (idx.get(&universe).clone(), op))
.collect::<Vec<_>>();
let versions_to_write = transactions
.iter()
.enumerate()
.filter_map(|(idx, (key, op))| match op {
Operator::Read => None,
Operator::Insert(_) | Operator::Skip | Operator::Remove => Some((key.clone(), idx)),
})
.collect::<Vec<_>>();
let baseline = Baseline::new(transactions.as_slice());
let (map, _) = MVHashMap::<K, Option<V>>::new_from_parallel(versions_to_write);
let curent_idx = AtomicUsize::new(0);
// Spawn a few threads in parallel to commit each operator.
rayon::scope(|s| {
for _ in 0..universe.len() {
s.spawn(|_| loop {
// Each thread will eagerly fetch an Operator to execute.
let idx = curent_idx.fetch_add(1, Ordering::Relaxed);
if idx >= transactions.len() {
// Abort when all transactions are processed.
break;
}
let key = &transactions[idx].0;
match &transactions[idx].1 {
Operator::Read => {
let baseline = baseline.get(key, idx);
let mut retry_attempts = 0;
loop {
match map.read(key, idx) {
Ok(Some(v)) => {
assert_eq!(
baseline,
ExpectedOutput::Value(v.clone()),
"{:?}",
idx
);
break;
}
Ok(None) => {
assert_eq!(baseline, ExpectedOutput::Deleted, "{:?}", idx);
break;
}
Err(None) => {
assert_eq!(baseline, ExpectedOutput::NotInMap, "{:?}", idx);
break;
}
Err(Some(_i)) => (),
}
retry_attempts += 1;
if retry_attempts > DEFAULT_TIMEOUT {
panic!("Failed to get value for {:?}", idx);
}
std::thread::sleep(std::time::Duration::from_millis(100));
}
}
Operator::Skip => {
map.skip(key, idx).unwrap();
}
Operator::Remove => {
map.write(key, idx, None).unwrap();
}
Operator::Insert(v) => {
map.write(key, idx, Some(v.clone())).unwrap();
}
}
})
}
});
Ok(())
}
proptest! {
#[test]
fn single_key_proptest(
universe in vec(any::<[u8; 32]>(), 1),
transactions in vec((any::<Index>(), operator_strategy::<[u8; 32]>()), 100),
) {
run_and_assert(universe, transactions)?;
}
#[test]
fn single_key_large_transactions(
universe in vec(any::<[u8; 32]>(), 1),
transactions in vec((any::<Index>(), operator_strategy::<[u8; 32]>()), 2000),
) {
run_and_assert(universe, transactions)?;
}
#[test]
fn multi_key_proptest(
universe in vec(any::<[u8; 32]>(), 10),
transactions in vec((any::<Index>(), operator_strategy::<[u8; 32]>()), 100),
) {
run_and_assert(universe, transactions)?;
}
}
| 33.010695 | 96 | 0.45132 |
dd580ce207f23e6e5c265765787ebdef2bd4b311 | 3,802 | // Copyright 2019 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Module with available running modes for Supervisor.
//!
//! Currently two modes are available:
//! - Simple mode. Within simple mode, the amount of checks performed by the Supervisor
//! is reduced to the minimum: the only requirement is that every request is sent
//! by the validator.
//! - Decentralized mode. Within decentralized mode, deploy requests
//! and config proposals should be approved by at least (2/3+1) validators.
use serde_derive::{Deserialize, Serialize};
use exonum::helpers::byzantine_quorum;
use exonum_crypto::Hash;
use exonum_merkledb::access::Access;
use exonum_proto::ProtobufConvert;
use super::{multisig::MultisigIndex, proto, DeployRequest};
/// Supervisor operating mode.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Mode {
/// Simple supervisor mode: to deploy service one have to send
/// one request to any of the validators.
Simple,
/// Decentralized supervisor mode: to deploy service a request should be
/// sent to **every** validator before it will be executed.
/// For configs, a byzantine majority of validators should vote for it.
Decentralized,
}
impl ProtobufConvert for Mode {
type ProtoStruct = proto::SupervisorMode;
fn to_pb(&self) -> Self::ProtoStruct {
match self {
Mode::Simple => proto::SupervisorMode::SIMPLE,
Mode::Decentralized => proto::SupervisorMode::DECENTRALIZED,
}
}
fn from_pb(pb: Self::ProtoStruct) -> Result<Self, failure::Error> {
let result = match pb {
proto::SupervisorMode::SIMPLE => Mode::Simple,
proto::SupervisorMode::DECENTRALIZED => Mode::Decentralized,
};
Ok(result)
}
}
impl Mode {
/// Checks whether deploy should be performed within the network.
pub fn deploy_approved<T: Access>(
&self,
deploy: &DeployRequest,
deploy_requests: &MultisigIndex<T, DeployRequest>,
validators: usize,
) -> bool {
match self {
Mode::Simple => {
// For simple supervisor request from 1 validator is enough.
deploy_requests.confirmations(deploy) >= 1
}
Mode::Decentralized => {
// Approve deploy in case 2/3+1 validators confirmed it.
let confirmations = deploy_requests.confirmations(&deploy);
confirmations >= byzantine_quorum(validators)
}
}
}
/// Checks whether config can be applied for the network.
pub fn config_approved<T: Access>(
&self,
config_hash: &Hash,
config_confirms: &MultisigIndex<T, Hash>,
validators: usize,
) -> bool {
match self {
Mode::Simple => {
// For simple supervisor one confirmation (from us) is enough.
config_confirms.confirmations(&config_hash) >= 1
}
Mode::Decentralized => {
// Apply pending config in case 2/3+1 validators voted for it.
let confirmations = config_confirms.confirmations(&config_hash);
confirmations >= byzantine_quorum(validators)
}
}
}
}
| 35.867925 | 87 | 0.646502 |
d614fadb1682a2e2b04cbf7c0c2c0bf07fcfbd75 | 93 | pub type c_char = i8;
pub type wchar_t = i16;
pub type c_long = i64;
pub type c_ulong = u64;
| 18.6 | 23 | 0.698925 |
fc09be913dc4260d682b7a1cc09a626ddb8b21af | 549 | use std::convert::TryInto;
use std::mem;
use liblumen_alloc::badarg;
use liblumen_alloc::erts::exception::Exception;
pub fn decode(bytes: &[u8]) -> Result<(u32, &[u8]), Exception> {
const U32_BYTE_LEN: usize = mem::size_of::<u32>();
if U32_BYTE_LEN <= bytes.len() {
let (len_bytes, after_len_bytes) = bytes.split_at(U32_BYTE_LEN);
let len_array = len_bytes.try_into().unwrap();
let len_u32 = u32::from_be_bytes(len_array);
Ok((len_u32, after_len_bytes))
} else {
Err(badarg!().into())
}
}
| 27.45 | 72 | 0.635701 |
481edb8c66cf841fef661808f03ea19af69692ce | 19,825 | //! Parallel iterator types for `IndexSet` with [rayon](https://docs.rs/rayon/1.0/rayon).
//!
//! You will rarely need to interact with this module directly unless you need to name one of the
//! iterator types.
//!
//! Requires crate feature `"rayon"`.
use super::collect;
use super::rayon::iter::plumbing::{Consumer, ProducerCallback, UnindexedConsumer};
use super::rayon::prelude::*;
use std::cmp::Ordering;
use std::fmt;
use std::hash::BuildHasher;
use std::hash::Hash;
use Entries;
use IndexSet;
type Bucket<T> = ::Bucket<T, ()>;
/// Requires crate feature `"rayon"`.
impl<T, S> IntoParallelIterator for IndexSet<T, S>
where
T: Hash + Eq + Send,
S: BuildHasher,
{
type Item = T;
type Iter = IntoParIter<T>;
fn into_par_iter(self) -> Self::Iter {
IntoParIter {
entries: self.into_entries(),
}
}
}
/// A parallel owning iterator over the items of a `IndexSet`.
///
/// This `struct` is created by the [`into_par_iter`] method on [`IndexSet`]
/// (provided by rayon's `IntoParallelIterator` trait). See its documentation for more.
///
/// [`IndexSet`]: ../struct.IndexSet.html
/// [`into_par_iter`]: ../struct.IndexSet.html#method.into_par_iter
pub struct IntoParIter<T> {
entries: Vec<Bucket<T>>,
}
impl<T: fmt::Debug> fmt::Debug for IntoParIter<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let iter = self.entries.iter().map(Bucket::key_ref);
f.debug_list().entries(iter).finish()
}
}
impl<T: Send> ParallelIterator for IntoParIter<T> {
type Item = T;
parallel_iterator_methods!(Bucket::key);
}
impl<T: Send> IndexedParallelIterator for IntoParIter<T> {
indexed_parallel_iterator_methods!(Bucket::key);
}
/// Requires crate feature `"rayon"`.
impl<'a, T, S> IntoParallelIterator for &'a IndexSet<T, S>
where
T: Hash + Eq + Sync,
S: BuildHasher,
{
type Item = &'a T;
type Iter = ParIter<'a, T>;
fn into_par_iter(self) -> Self::Iter {
ParIter {
entries: self.as_entries(),
}
}
}
/// A parallel iterator over the items of a `IndexSet`.
///
/// This `struct` is created by the [`par_iter`] method on [`IndexSet`]
/// (provided by rayon's `IntoParallelRefIterator` trait). See its documentation for more.
///
/// [`IndexSet`]: ../struct.IndexSet.html
/// [`par_iter`]: ../struct.IndexSet.html#method.par_iter
pub struct ParIter<'a, T: 'a> {
entries: &'a [Bucket<T>],
}
impl<'a, T> Clone for ParIter<'a, T> {
fn clone(&self) -> Self {
ParIter { ..*self }
}
}
impl<'a, T: fmt::Debug> fmt::Debug for ParIter<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let iter = self.entries.iter().map(Bucket::key_ref);
f.debug_list().entries(iter).finish()
}
}
impl<'a, T: Sync> ParallelIterator for ParIter<'a, T> {
type Item = &'a T;
parallel_iterator_methods!(Bucket::key_ref);
}
impl<'a, T: Sync> IndexedParallelIterator for ParIter<'a, T> {
indexed_parallel_iterator_methods!(Bucket::key_ref);
}
/// Parallel iterator methods and other parallel methods.
///
/// The following methods **require crate feature `"rayon"`**.
///
/// See also the `IntoParallelIterator` implementations.
impl<T, S> IndexSet<T, S>
where
T: Hash + Eq + Sync,
S: BuildHasher + Sync,
{
/// Return a parallel iterator over the values that are in `self` but not `other`.
///
/// While parallel iterators can process items in any order, their relative order
/// in the `self` set is still preserved for operations like `reduce` and `collect`.
pub fn par_difference<'a, S2>(
&'a self,
other: &'a IndexSet<T, S2>,
) -> ParDifference<'a, T, S, S2>
where
S2: BuildHasher + Sync,
{
ParDifference {
set1: self,
set2: other,
}
}
/// Return a parallel iterator over the values that are in `self` or `other`,
/// but not in both.
///
/// While parallel iterators can process items in any order, their relative order
/// in the sets is still preserved for operations like `reduce` and `collect`.
/// Values from `self` are produced in their original order, followed by
/// values from `other` in their original order.
pub fn par_symmetric_difference<'a, S2>(
&'a self,
other: &'a IndexSet<T, S2>,
) -> ParSymmetricDifference<'a, T, S, S2>
where
S2: BuildHasher + Sync,
{
ParSymmetricDifference {
set1: self,
set2: other,
}
}
/// Return a parallel iterator over the values that are in both `self` and `other`.
///
/// While parallel iterators can process items in any order, their relative order
/// in the `self` set is still preserved for operations like `reduce` and `collect`.
pub fn par_intersection<'a, S2>(
&'a self,
other: &'a IndexSet<T, S2>,
) -> ParIntersection<'a, T, S, S2>
where
S2: BuildHasher + Sync,
{
ParIntersection {
set1: self,
set2: other,
}
}
/// Return a parallel iterator over all values that are in `self` or `other`.
///
/// While parallel iterators can process items in any order, their relative order
/// in the sets is still preserved for operations like `reduce` and `collect`.
/// Values from `self` are produced in their original order, followed by
/// values that are unique to `other` in their original order.
pub fn par_union<'a, S2>(&'a self, other: &'a IndexSet<T, S2>) -> ParUnion<'a, T, S, S2>
where
S2: BuildHasher + Sync,
{
ParUnion {
set1: self,
set2: other,
}
}
/// Returns `true` if `self` contains all of the same values as `other`,
/// regardless of each set's indexed order, determined in parallel.
pub fn par_eq<S2>(&self, other: &IndexSet<T, S2>) -> bool
where
S2: BuildHasher + Sync,
{
self.len() == other.len() && self.par_is_subset(other)
}
/// Returns `true` if `self` has no elements in common with `other`,
/// determined in parallel.
pub fn par_is_disjoint<S2>(&self, other: &IndexSet<T, S2>) -> bool
where
S2: BuildHasher + Sync,
{
if self.len() <= other.len() {
self.par_iter().all(move |value| !other.contains(value))
} else {
other.par_iter().all(move |value| !self.contains(value))
}
}
/// Returns `true` if all elements of `other` are contained in `self`,
/// determined in parallel.
pub fn par_is_superset<S2>(&self, other: &IndexSet<T, S2>) -> bool
where
S2: BuildHasher + Sync,
{
other.par_is_subset(self)
}
/// Returns `true` if all elements of `self` are contained in `other`,
/// determined in parallel.
pub fn par_is_subset<S2>(&self, other: &IndexSet<T, S2>) -> bool
where
S2: BuildHasher + Sync,
{
self.len() <= other.len() && self.par_iter().all(move |value| other.contains(value))
}
}
/// A parallel iterator producing elements in the difference of `IndexSet`s.
///
/// This `struct` is created by the [`par_difference`] method on [`IndexSet`].
/// See its documentation for more.
///
/// [`IndexSet`]: ../struct.IndexSet.html
/// [`par_difference`]: ../struct.IndexSet.html#method.par_difference
pub struct ParDifference<'a, T: 'a, S1: 'a, S2: 'a> {
set1: &'a IndexSet<T, S1>,
set2: &'a IndexSet<T, S2>,
}
impl<'a, T, S1, S2> Clone for ParDifference<'a, T, S1, S2> {
fn clone(&self) -> Self {
ParDifference { ..*self }
}
}
impl<'a, T, S1, S2> fmt::Debug for ParDifference<'a, T, S1, S2>
where
T: fmt::Debug + Eq + Hash,
S1: BuildHasher,
S2: BuildHasher,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list()
.entries(self.set1.difference(&self.set2))
.finish()
}
}
impl<'a, T, S1, S2> ParallelIterator for ParDifference<'a, T, S1, S2>
where
T: Hash + Eq + Sync,
S1: BuildHasher + Sync,
S2: BuildHasher + Sync,
{
type Item = &'a T;
fn drive_unindexed<C>(self, consumer: C) -> C::Result
where
C: UnindexedConsumer<Self::Item>,
{
let Self { set1, set2 } = self;
set1.par_iter()
.filter(move |&item| !set2.contains(item))
.drive_unindexed(consumer)
}
}
/// A parallel iterator producing elements in the intersection of `IndexSet`s.
///
/// This `struct` is created by the [`par_intersection`] method on [`IndexSet`].
/// See its documentation for more.
///
/// [`IndexSet`]: ../struct.IndexSet.html
/// [`par_intersection`]: ../struct.IndexSet.html#method.par_intersection
pub struct ParIntersection<'a, T: 'a, S1: 'a, S2: 'a> {
set1: &'a IndexSet<T, S1>,
set2: &'a IndexSet<T, S2>,
}
impl<'a, T, S1, S2> Clone for ParIntersection<'a, T, S1, S2> {
fn clone(&self) -> Self {
ParIntersection { ..*self }
}
}
impl<'a, T, S1, S2> fmt::Debug for ParIntersection<'a, T, S1, S2>
where
T: fmt::Debug + Eq + Hash,
S1: BuildHasher,
S2: BuildHasher,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list()
.entries(self.set1.intersection(&self.set2))
.finish()
}
}
impl<'a, T, S1, S2> ParallelIterator for ParIntersection<'a, T, S1, S2>
where
T: Hash + Eq + Sync,
S1: BuildHasher + Sync,
S2: BuildHasher + Sync,
{
type Item = &'a T;
fn drive_unindexed<C>(self, consumer: C) -> C::Result
where
C: UnindexedConsumer<Self::Item>,
{
let Self { set1, set2 } = self;
set1.par_iter()
.filter(move |&item| set2.contains(item))
.drive_unindexed(consumer)
}
}
/// A parallel iterator producing elements in the symmetric difference of `IndexSet`s.
///
/// This `struct` is created by the [`par_symmetric_difference`] method on
/// [`IndexSet`]. See its documentation for more.
///
/// [`IndexSet`]: ../struct.IndexSet.html
/// [`par_symmetric_difference`]: ../struct.IndexSet.html#method.par_symmetric_difference
pub struct ParSymmetricDifference<'a, T: 'a, S1: 'a, S2: 'a> {
set1: &'a IndexSet<T, S1>,
set2: &'a IndexSet<T, S2>,
}
impl<'a, T, S1, S2> Clone for ParSymmetricDifference<'a, T, S1, S2> {
fn clone(&self) -> Self {
ParSymmetricDifference { ..*self }
}
}
impl<'a, T, S1, S2> fmt::Debug for ParSymmetricDifference<'a, T, S1, S2>
where
T: fmt::Debug + Eq + Hash,
S1: BuildHasher,
S2: BuildHasher,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list()
.entries(self.set1.symmetric_difference(&self.set2))
.finish()
}
}
impl<'a, T, S1, S2> ParallelIterator for ParSymmetricDifference<'a, T, S1, S2>
where
T: Hash + Eq + Sync,
S1: BuildHasher + Sync,
S2: BuildHasher + Sync,
{
type Item = &'a T;
fn drive_unindexed<C>(self, consumer: C) -> C::Result
where
C: UnindexedConsumer<Self::Item>,
{
let Self { set1, set2 } = self;
set1.par_difference(set2)
.chain(set2.par_difference(set1))
.drive_unindexed(consumer)
}
}
/// A parallel iterator producing elements in the union of `IndexSet`s.
///
/// This `struct` is created by the [`par_union`] method on [`IndexSet`].
/// See its documentation for more.
///
/// [`IndexSet`]: ../struct.IndexSet.html
/// [`par_union`]: ../struct.IndexSet.html#method.par_union
pub struct ParUnion<'a, T: 'a, S1: 'a, S2: 'a> {
set1: &'a IndexSet<T, S1>,
set2: &'a IndexSet<T, S2>,
}
impl<'a, T, S1, S2> Clone for ParUnion<'a, T, S1, S2> {
fn clone(&self) -> Self {
ParUnion { ..*self }
}
}
impl<'a, T, S1, S2> fmt::Debug for ParUnion<'a, T, S1, S2>
where
T: fmt::Debug + Eq + Hash,
S1: BuildHasher,
S2: BuildHasher,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list().entries(self.set1.union(&self.set2)).finish()
}
}
impl<'a, T, S1, S2> ParallelIterator for ParUnion<'a, T, S1, S2>
where
T: Hash + Eq + Sync,
S1: BuildHasher + Sync,
S2: BuildHasher + Sync,
{
type Item = &'a T;
fn drive_unindexed<C>(self, consumer: C) -> C::Result
where
C: UnindexedConsumer<Self::Item>,
{
let Self { set1, set2 } = self;
set1.par_iter()
.chain(set2.par_difference(set1))
.drive_unindexed(consumer)
}
}
/// Parallel sorting methods.
///
/// The following methods **require crate feature `"rayon"`**.
impl<T, S> IndexSet<T, S>
where
T: Hash + Eq + Send,
S: BuildHasher + Send,
{
/// Sort the set’s values in parallel by their default ordering.
pub fn par_sort(&mut self)
where
T: Ord,
{
self.with_entries(|entries| {
entries.par_sort_by(|a, b| T::cmp(&a.key, &b.key));
});
}
/// Sort the set’s values in place and in parallel, using the comparison function `compare`.
pub fn par_sort_by<F>(&mut self, cmp: F)
where
F: Fn(&T, &T) -> Ordering + Sync,
{
self.with_entries(|entries| {
entries.par_sort_by(move |a, b| cmp(&a.key, &b.key));
});
}
/// Sort the values of the set in parallel and return a by value parallel iterator of
/// the values with the result.
pub fn par_sorted_by<F>(self, cmp: F) -> IntoParIter<T>
where
F: Fn(&T, &T) -> Ordering + Sync,
{
let mut entries = self.into_entries();
entries.par_sort_by(move |a, b| cmp(&a.key, &b.key));
IntoParIter { entries }
}
}
/// Requires crate feature `"rayon"`.
impl<T, S> FromParallelIterator<T> for IndexSet<T, S>
where
T: Eq + Hash + Send,
S: BuildHasher + Default + Send,
{
fn from_par_iter<I>(iter: I) -> Self
where
I: IntoParallelIterator<Item = T>,
{
let list = collect(iter);
let len = list.iter().map(Vec::len).sum();
let mut set = Self::with_capacity_and_hasher(len, S::default());
for vec in list {
set.extend(vec);
}
set
}
}
/// Requires crate feature `"rayon"`.
impl<T, S> ParallelExtend<(T)> for IndexSet<T, S>
where
T: Eq + Hash + Send,
S: BuildHasher + Send,
{
fn par_extend<I>(&mut self, iter: I)
where
I: IntoParallelIterator<Item = T>,
{
for vec in collect(iter) {
self.extend(vec);
}
}
}
/// Requires crate feature `"rayon"`.
impl<'a, T: 'a, S> ParallelExtend<&'a T> for IndexSet<T, S>
where
T: Copy + Eq + Hash + Send + Sync,
S: BuildHasher + Send,
{
fn par_extend<I>(&mut self, iter: I)
where
I: IntoParallelIterator<Item = &'a T>,
{
for vec in collect(iter) {
self.extend(vec);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn insert_order() {
let insert = [0, 4, 2, 12, 8, 7, 11, 5, 3, 17, 19, 22, 23];
let mut set = IndexSet::new();
for &elt in &insert {
set.insert(elt);
}
assert_eq!(set.par_iter().count(), set.len());
assert_eq!(set.par_iter().count(), insert.len());
insert.par_iter().zip(&set).for_each(|(a, b)| {
assert_eq!(a, b);
});
(0..insert.len())
.into_par_iter()
.zip(&set)
.for_each(|(i, v)| {
assert_eq!(set.get_index(i).unwrap(), v);
});
}
#[test]
fn partial_eq_and_eq() {
let mut set_a = IndexSet::new();
set_a.insert(1);
set_a.insert(2);
let mut set_b = set_a.clone();
assert!(set_a.par_eq(&set_b));
set_b.swap_remove(&1);
assert!(!set_a.par_eq(&set_b));
set_b.insert(3);
assert!(!set_a.par_eq(&set_b));
let set_c: IndexSet<_> = set_b.into_par_iter().collect();
assert!(!set_a.par_eq(&set_c));
assert!(!set_c.par_eq(&set_a));
}
#[test]
fn extend() {
let mut set = IndexSet::new();
set.par_extend(vec![&1, &2, &3, &4]);
set.par_extend(vec![5, 6]);
assert_eq!(
set.into_par_iter().collect::<Vec<_>>(),
vec![1, 2, 3, 4, 5, 6]
);
}
#[test]
fn comparisons() {
let set_a: IndexSet<_> = (0..3).collect();
let set_b: IndexSet<_> = (3..6).collect();
let set_c: IndexSet<_> = (0..6).collect();
let set_d: IndexSet<_> = (3..9).collect();
assert!(!set_a.par_is_disjoint(&set_a));
assert!(set_a.par_is_subset(&set_a));
assert!(set_a.par_is_superset(&set_a));
assert!(set_a.par_is_disjoint(&set_b));
assert!(set_b.par_is_disjoint(&set_a));
assert!(!set_a.par_is_subset(&set_b));
assert!(!set_b.par_is_subset(&set_a));
assert!(!set_a.par_is_superset(&set_b));
assert!(!set_b.par_is_superset(&set_a));
assert!(!set_a.par_is_disjoint(&set_c));
assert!(!set_c.par_is_disjoint(&set_a));
assert!(set_a.par_is_subset(&set_c));
assert!(!set_c.par_is_subset(&set_a));
assert!(!set_a.par_is_superset(&set_c));
assert!(set_c.par_is_superset(&set_a));
assert!(!set_c.par_is_disjoint(&set_d));
assert!(!set_d.par_is_disjoint(&set_c));
assert!(!set_c.par_is_subset(&set_d));
assert!(!set_d.par_is_subset(&set_c));
assert!(!set_c.par_is_superset(&set_d));
assert!(!set_d.par_is_superset(&set_c));
}
#[test]
fn iter_comparisons() {
use std::iter::empty;
fn check<'a, I1, I2>(iter1: I1, iter2: I2)
where
I1: ParallelIterator<Item = &'a i32>,
I2: Iterator<Item = i32>,
{
let v1: Vec<_> = iter1.cloned().collect();
let v2: Vec<_> = iter2.collect();
assert_eq!(v1, v2);
}
let set_a: IndexSet<_> = (0..3).collect();
let set_b: IndexSet<_> = (3..6).collect();
let set_c: IndexSet<_> = (0..6).collect();
let set_d: IndexSet<_> = (3..9).rev().collect();
check(set_a.par_difference(&set_a), empty());
check(set_a.par_symmetric_difference(&set_a), empty());
check(set_a.par_intersection(&set_a), 0..3);
check(set_a.par_union(&set_a), 0..3);
check(set_a.par_difference(&set_b), 0..3);
check(set_b.par_difference(&set_a), 3..6);
check(set_a.par_symmetric_difference(&set_b), 0..6);
check(set_b.par_symmetric_difference(&set_a), (3..6).chain(0..3));
check(set_a.par_intersection(&set_b), empty());
check(set_b.par_intersection(&set_a), empty());
check(set_a.par_union(&set_b), 0..6);
check(set_b.par_union(&set_a), (3..6).chain(0..3));
check(set_a.par_difference(&set_c), empty());
check(set_c.par_difference(&set_a), 3..6);
check(set_a.par_symmetric_difference(&set_c), 3..6);
check(set_c.par_symmetric_difference(&set_a), 3..6);
check(set_a.par_intersection(&set_c), 0..3);
check(set_c.par_intersection(&set_a), 0..3);
check(set_a.par_union(&set_c), 0..6);
check(set_c.par_union(&set_a), 0..6);
check(set_c.par_difference(&set_d), 0..3);
check(set_d.par_difference(&set_c), (6..9).rev());
check(
set_c.par_symmetric_difference(&set_d),
(0..3).chain((6..9).rev()),
);
check(
set_d.par_symmetric_difference(&set_c),
(6..9).rev().chain(0..3),
);
check(set_c.par_intersection(&set_d), 3..6);
check(set_d.par_intersection(&set_c), (3..6).rev());
check(set_c.par_union(&set_d), (0..6).chain((6..9).rev()));
check(set_d.par_union(&set_c), (3..9).rev().chain(0..3));
}
}
| 29.326923 | 97 | 0.581236 |
28c7a466dd06e838035138e5df26236abe12b041 | 3,155 | use super::*;
fn inline_list_kserds<'a, E: CxErr<'a>>(i: &'a str) -> IResult<&'a str, Vec<Kserd<'a>>, E> {
context(
"comma separated kserds",
separated_list0(
ignore_inline_whitespace(char(',')),
ignore_inline_whitespace(kserd_inline),
),
)(i)
}
/// Concise lists are separated by new lines. This can become problematic since
/// there may be multiple new lines and whitespace before you get to the next item.
/// The way to control for this is to allow whitespace all around the items.
///
/// TODO: Show one of the tuple examples.
fn concise_list_kserds<'a, E: CxErr<'a>>(i: &'a str) -> IResult<&'a str, Vec<Kserd<'a>>, E> {
preceded(
multiline_whitespace,
cut(terminated(
separated_list0(multiline_whitespace, kserd_concise),
multiline_whitespace,
)),
)(i)
}
/// Parse as a tuple. Will `Fail` if delimited by opening paren `(`.
/// Tries to determine if the stream is in `Concise` or `Inline` format using
/// simple heuristics. The decision can be overridden by forcing `Inline` format.
pub(super) fn tuple<'a, E: CxErr<'a>>(
force_inline: bool,
) -> impl Fn(&'a str) -> IResult<&'a str, Kserd<'a>, E> {
move |i: &'a str| {
let (i, ident) = opt(ident(false))(i)?;
let (i, _) = ignore_inline_whitespace(char('('))(i)?; // open with paren
// we manually work out if should be treating as inline or concise
let concise = recognise_concise(i) && !force_inline;
let parser = if concise {
concise_list_kserds
} else {
inline_list_kserds
};
let ctx = if concise {
"multi-line (concise) tuple"
} else {
"inline tuple"
};
let (i, value) = context(
ctx,
cut(terminated(parser, ignore_inline_whitespace(char(')')))),
)(i)?;
let value = Value::Tuple(value);
Ok((i, kserd_ctor(ident, value)))
}
}
/// Parse as a sequence. Will `Fail` if delimited by opening bracket `[`.
/// Tries to determine if the stream is in `Concise` or `Inline` format using
/// simple heuristics. The decision can be overridden by forcing `Inline` format.
pub(super) fn seq_delimited<'a, E: CxErr<'a>>(
force_inline: bool,
) -> impl Fn(&'a str) -> IResult<&'a str, Kserd<'a>, E> {
move |i: &'a str| {
let (i, ident) = opt(ident(false))(i)?;
let (i, _) = ignore_inline_whitespace(char('['))(i)?; // open with bracket
// we manually work out if should be treating as inline or concise
let concise = recognise_concise(i) && !force_inline;
let parser = if concise {
concise_list_kserds
} else {
inline_list_kserds
};
let ctx = if concise {
"multi-line (concise) sequence"
} else {
"inline sequence"
};
let (i, value) = context(
ctx,
cut(terminated(parser, ignore_inline_whitespace(char(']')))),
)(i)?;
let value = Value::Seq(value);
Ok((i, kserd_ctor(ident, value)))
}
}
| 31.237624 | 93 | 0.577179 |
ab37628a6b9c001412df26c19e135f4b9119076a | 10,057 | use crate::signatures::SignatureRegistry;
use crate::{Config, Trap};
use anyhow::Result;
#[cfg(feature = "parallel-compilation")]
use rayon::prelude::*;
use std::sync::Arc;
#[cfg(feature = "cache")]
use wasmtime_cache::CacheConfig;
use wasmtime_runtime::{debug_builtins, InstanceAllocator};
/// An `Engine` which is a global context for compilation and management of wasm
/// modules.
///
/// An engine can be safely shared across threads and is a cheap cloneable
/// handle to the actual engine. The engine itself will be deallocated once all
/// references to it have gone away.
///
/// Engines store global configuration preferences such as compilation settings,
/// enabled features, etc. You'll likely only need at most one of these for a
/// program.
///
/// ## Engines and `Clone`
///
/// Using `clone` on an `Engine` is a cheap operation. It will not create an
/// entirely new engine, but rather just a new reference to the existing engine.
/// In other words it's a shallow copy, not a deep copy.
///
/// ## Engines and `Default`
///
/// You can create an engine with default configuration settings using
/// `Engine::default()`. Be sure to consult the documentation of [`Config`] for
/// default settings.
#[derive(Clone)]
pub struct Engine {
inner: Arc<EngineInner>,
}
struct EngineInner {
config: Config,
#[cfg(compiler)]
compiler: Box<dyn wasmtime_environ::Compiler>,
allocator: Box<dyn InstanceAllocator>,
signatures: SignatureRegistry,
}
impl Engine {
/// Creates a new [`Engine`] with the specified compilation and
/// configuration settings.
pub fn new(config: &Config) -> Result<Engine> {
// Ensure that wasmtime_runtime's signal handlers are configured. This
// is the per-program initialization required for handling traps, such
// as configuring signals, vectored exception handlers, etc.
wasmtime_runtime::init_traps(crate::module::GlobalModuleRegistry::is_wasm_pc);
debug_builtins::ensure_exported();
let registry = SignatureRegistry::new();
let mut config = config.clone();
let allocator = config.build_allocator()?;
allocator.adjust_tunables(&mut config.tunables);
Ok(Engine {
inner: Arc::new(EngineInner {
#[cfg(compiler)]
compiler: config.compiler.build(),
config,
allocator,
signatures: registry,
}),
})
}
/// Eagerly initialize thread-local functionality shared by all [`Engine`]s.
///
/// Wasmtime's implementation on some platforms may involve per-thread
/// setup that needs to happen whenever WebAssembly is invoked. This setup
/// can take on the order of a few hundred microseconds, whereas the
/// overhead of calling WebAssembly is otherwise on the order of a few
/// nanoseconds. This setup cost is paid once per-OS-thread. If your
/// application is sensitive to the latencies of WebAssembly function
/// calls, even those that happen first on a thread, then this function
/// can be used to improve the consistency of each call into WebAssembly
/// by explicitly frontloading the cost of the one-time setup per-thread.
///
/// Note that this function is not required to be called in any embedding.
/// Wasmtime will automatically initialize thread-local-state as necessary
/// on calls into WebAssembly. This is provided for use cases where the
/// latency of WebAssembly calls are extra-important, which is not
/// necessarily true of all embeddings.
pub fn tls_eager_initialize() -> Result<(), Trap> {
wasmtime_runtime::tls_eager_initialize().map_err(Trap::from_runtime)
}
/// Returns the configuration settings that this engine is using.
#[inline]
pub fn config(&self) -> &Config {
&self.inner.config
}
#[cfg(compiler)]
pub(crate) fn compiler(&self) -> &dyn wasmtime_environ::Compiler {
&*self.inner.compiler
}
pub(crate) fn allocator(&self) -> &dyn InstanceAllocator {
self.inner.allocator.as_ref()
}
#[cfg(feature = "cache")]
pub(crate) fn cache_config(&self) -> &CacheConfig {
&self.config().cache_config
}
/// Returns whether the engine `a` and `b` refer to the same configuration.
pub fn same(a: &Engine, b: &Engine) -> bool {
Arc::ptr_eq(&a.inner, &b.inner)
}
pub(crate) fn signatures(&self) -> &SignatureRegistry {
&self.inner.signatures
}
/// Ahead-of-time (AOT) compiles a WebAssembly module.
///
/// The `bytes` provided must be in one of two formats:
///
/// * A [binary-encoded][binary] WebAssembly module. This is always supported.
/// * A [text-encoded][text] instance of the WebAssembly text format.
/// This is only supported when the `wat` feature of this crate is enabled.
/// If this is supplied then the text format will be parsed before validation.
/// Note that the `wat` feature is enabled by default.
///
/// This method may be used to compile a module for use with a different target
/// host. The output of this method may be used with
/// [`Module::deserialize`](crate::Module::deserialize) on hosts compatible
/// with the [`Config`] associated with this [`Engine`].
///
/// The output of this method is safe to send to another host machine for later
/// execution. As the output is already a compiled module, translation and code
/// generation will be skipped and this will improve the performance of constructing
/// a [`Module`](crate::Module) from the output of this method.
///
/// [binary]: https://webassembly.github.io/spec/core/binary/index.html
/// [text]: https://webassembly.github.io/spec/core/text/index.html
#[cfg(compiler)]
#[cfg_attr(nightlydoc, doc(cfg(feature = "cranelift")))] // see build.rs
pub fn precompile_module(&self, bytes: &[u8]) -> Result<Vec<u8>> {
#[cfg(feature = "wat")]
let bytes = wat::parse_bytes(&bytes)?;
let (_, artifacts, types) = crate::Module::build_artifacts(self, &bytes)?;
crate::module::SerializedModule::from_artifacts(self, &artifacts, &types).to_bytes()
}
pub(crate) fn run_maybe_parallel<
A: Send,
B: Send,
E: Send,
F: Fn(A) -> Result<B, E> + Send + Sync,
>(
&self,
input: Vec<A>,
f: F,
) -> Result<Vec<B>, E> {
if self.config().parallel_compilation {
#[cfg(feature = "parallel-compilation")]
return input
.into_par_iter()
.map(|a| f(a))
.collect::<Result<Vec<B>, E>>();
}
// In case the parallel-compilation feature is disabled or the parallel_compilation config
// was turned off dynamically fallback to the non-parallel version.
input
.into_iter()
.map(|a| f(a))
.collect::<Result<Vec<B>, E>>()
}
}
impl Default for Engine {
fn default() -> Engine {
Engine::new(&Config::default()).unwrap()
}
}
#[cfg(test)]
mod tests {
use crate::{Config, Engine, Module, OptLevel};
use anyhow::Result;
use tempfile::TempDir;
#[test]
fn cache_accounts_for_opt_level() -> Result<()> {
let td = TempDir::new()?;
let config_path = td.path().join("config.toml");
std::fs::write(
&config_path,
&format!(
"
[cache]
enabled = true
directory = '{}'
",
td.path().join("cache").display()
),
)?;
let mut cfg = Config::new();
cfg.cranelift_opt_level(OptLevel::None)
.cache_config_load(&config_path)?;
let engine = Engine::new(&cfg)?;
Module::new(&engine, "(module (func))")?;
assert_eq!(engine.config().cache_config.cache_hits(), 0);
assert_eq!(engine.config().cache_config.cache_misses(), 1);
Module::new(&engine, "(module (func))")?;
assert_eq!(engine.config().cache_config.cache_hits(), 1);
assert_eq!(engine.config().cache_config.cache_misses(), 1);
let mut cfg = Config::new();
cfg.cranelift_opt_level(OptLevel::Speed)
.cache_config_load(&config_path)?;
let engine = Engine::new(&cfg)?;
Module::new(&engine, "(module (func))")?;
assert_eq!(engine.config().cache_config.cache_hits(), 0);
assert_eq!(engine.config().cache_config.cache_misses(), 1);
Module::new(&engine, "(module (func))")?;
assert_eq!(engine.config().cache_config.cache_hits(), 1);
assert_eq!(engine.config().cache_config.cache_misses(), 1);
let mut cfg = Config::new();
cfg.cranelift_opt_level(OptLevel::SpeedAndSize)
.cache_config_load(&config_path)?;
let engine = Engine::new(&cfg)?;
Module::new(&engine, "(module (func))")?;
assert_eq!(engine.config().cache_config.cache_hits(), 0);
assert_eq!(engine.config().cache_config.cache_misses(), 1);
Module::new(&engine, "(module (func))")?;
assert_eq!(engine.config().cache_config.cache_hits(), 1);
assert_eq!(engine.config().cache_config.cache_misses(), 1);
// FIXME(#1523) need debuginfo on aarch64 before we run this test there
if !cfg!(target_arch = "aarch64") {
let mut cfg = Config::new();
cfg.debug_info(true).cache_config_load(&config_path)?;
let engine = Engine::new(&cfg)?;
Module::new(&engine, "(module (func))")?;
assert_eq!(engine.config().cache_config.cache_hits(), 0);
assert_eq!(engine.config().cache_config.cache_misses(), 1);
Module::new(&engine, "(module (func))")?;
assert_eq!(engine.config().cache_config.cache_hits(), 1);
assert_eq!(engine.config().cache_config.cache_misses(), 1);
}
Ok(())
}
}
| 39.285156 | 98 | 0.621259 |
0efe6ece6e87250d755e37357ef69f09ab7301c0 | 2,959 | use parking_lot::RwLock;
use std::collections::{HashMap, VecDeque};
use std::hash::Hash;
use std::sync::Arc;
#[derive(Clone)]
pub struct NamedMap<K, V>
where
K: Clone + Eq + Hash,
V: Clone,
{
inner: Arc<RwLock<InnerMap<K, V>>>,
}
#[derive(Default)]
struct InnerMap<K, V>
where
K: Clone + Eq + Hash,
V: Clone,
{
map: HashMap<u64, V>,
name_id: HashMap<K, u64>,
id_name: HashMap<u64, Vec<K>>,
free: VecDeque<u64>,
}
impl<K, V> InnerMap<K, V>
where
K: Clone + Eq + Hash,
V: Clone,
{
fn new() -> Self {
Self {
map: HashMap::new(),
name_id: HashMap::new(),
id_name: HashMap::new(),
free: VecDeque::new(),
}
}
pub fn insert(&mut self, value: V) -> u64 {
let id = if let Some(id) = self.free.pop_front() {
id
} else {
self.map.len() as u64 + 1
};
self.map.insert(id, value);
id
}
pub fn insert_with_name(&mut self, value: V, name: K) -> u64 {
let id = self.insert(value);
self.set_name(id, name);
id
}
pub fn set_name(&mut self, id: u64, key: K) {
self.name_id.insert(key.clone(), id);
self.id_name
.entry(id)
.and_modify(|names| names.push(key.clone()))
.or_insert_with(|| vec![key]);
}
// pub fn remove(&mut self, id: &u64) -> Option<V> {
// if let Some(item) = self.map.remove(id) {
// if let Some(names) = self.id_name.get(id) {
// for name in names {
// self.name_id.remove(name);
// }
// self.id_name.remove(id);
// }
// self.free.push_back(*id);
// Some(item)
// } else {
// None
// }
// }
}
impl<K, V> NamedMap<K, V>
where
K: Clone + Eq + Hash,
V: Clone,
{
pub fn new() -> Self {
let inner = InnerMap::new();
let inner = Arc::new(RwLock::new(inner));
Self { inner }
}
// pub fn insert(&mut self, value: V) -> u64 {
// self.inner.write().insert(value)
// }
pub fn insert_with_name(&mut self, value: V, name: K) -> u64 {
self.inner.write().insert_with_name(value, name)
}
pub fn get(&self, id: u64) -> Option<V> {
let inner = self.inner.read();
let value = inner.map.get(&id).map(|v| v.clone());
value
}
pub fn get_by_name(&self, key: &K) -> Option<V> {
let inner = self.inner.read();
let id = inner.name_id.get(&key);
match id {
None => None,
Some(id) => inner.map.get(id).map(|v| v.clone()),
}
}
pub fn set_name(&mut self, id: u64, key: K) {
let mut inner = self.inner.write();
inner.set_name(id, key);
}
// pub fn remove(&mut self, id: &u64) -> Option<V> {
// self.inner.write().remove(id)
// }
}
| 24.056911 | 66 | 0.487665 |
21060576f2ec5f9085d80898ba764501c3e17161 | 661 | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
// pretty-expanded FIXME #23616
trait A {
fn dummy(&self) { }
}
struct B;
impl A for B {}
fn foo(_: &mut A) {}
pub fn main() {
let mut b = B;
foo(&mut b as &mut A);
}
| 25.423077 | 68 | 0.683812 |
22a1c976887ef889d2e4b3ee3abda8c4d25715ad | 72,988 | use core::fmt;
use std::{cmp::{self, Reverse}, collections::HashMap, convert::TryFrom, error::Error};
use log::{debug, info, warn};
use screeps::{Attackable, ConstructionSite, FindOptions, HasId, HasPosition, HasStore, MoveToOptions, ObjectId, Part, Path, Position, RawObjectId, Resource, ResourceType, ReturnCode, Room, RoomName, RoomObjectProperties, Ruin, SharedCreepProperties, Source, Structure, StructureContainer, StructureExtension, StructureSpawn, StructureStorage, StructureTerminal, StructureTower, creep, find, game::get_object_typed, look, memory::MemoryReference};
use crate::{constants::{CREEP_ID_BITCH, CREEP_ID_BUILDER, CREEP_ID_FARMER, CREEP_ID_RUNNER, CREEP_ID_UNKNOWN, MEM_ASSIGNED_SOURCE, MEM_FARM_POSITION_X, MEM_FARM_POSITION_Y, MEM_HARVESTING, MEM_KIND, MEM_POST, MEM_RESOURCE_PROVIDER_ID, TERMINAL_TRADE_BUFFER}, rooms::{FarmPosition, MyRoom, PathOptionUnwrapper, RoomMaintenance, resource_provider::{ResourceData, ResourceProvider, RoomObjectData, TakeResourceResult}, room_ext::RoomExt, room_state::{RoomState, SetupBaseStateVisibility}}, state::{BWContext, UniqId}, utils::HexStr};
use self::{jobs::OokCreepJob, races::{OokRace, OokRaceKind}};
use anyhow::anyhow;
pub mod harvesting;
pub mod races;
pub mod tasks;
pub mod utils;
pub mod jobs;
#[derive(thiserror::Error, Debug)]
pub enum CreepError {
#[error("Could not convert creep")]
CreepNotConvertible(),
#[error("[Creep] Could not find object {0}")]
ObjectNotFound(String),
#[error("Could not find room for creep")]
RoomNotFound(),
#[error("Could not find source {0}")]
SourceNotFound(String),
#[error("Creep {0} has no post")]
MissingPost(String),
#[error("Creep {0} has no assigned_source")]
MissingAssignedSource(String),
#[error("Creep {0} has no correct farm position")]
MissingFarmPosition(String),
#[error("Trying to repair target {0}, but its not attackable")]
RepairNotAttackable(String),
#[error("Trying to load resource provider id failed")]
ResourceProviderIdNotStored,
}
#[derive(Clone, Debug )]
pub enum CreepKind {
Bitch(CreepBitch),
Builder(CreepBuilder),
Farmer(CreepFarmer),
Runner(CreepRunner),
Unknown(CreepUnknown),
}
trait HandlesResource {
fn calc_next_fetch<'a>(
&mut self,
rooms_state: &'a HashMap<RoomName, RoomState>,
) -> Result<Option<(&'a ResourceProvider, ResourceType, u32)>, Box<dyn Error>>;
// fn select_target_provider(states: RoomState) -> Result<(ResourceProvider, ResourceType, u32), Box<dyn Error>>;
}
impl CreepKind {
// fn ident(&self) -> &str {
// use CreepKind::*;
// match self {
// Bitch(_) => CREEP_ID_BITCH,
// Builder(_) => CREEP_ID_BUILDER,
// Farmer(_) => CREEP_ID_FARMER,
// Runner(_) => CREEP_ID_RUNNER,
// Unknown(_) => CREEP_ID_UNKNOWN,
// }
// }
//
// pub fn get_creep(&self) -> &screeps::Creep {
// use CreepKind::*;
// match self {
// Bitch(data) => &data.creep,
// Builder(data) => &data.creep,
// Farmer(data) => &data.creep,
// Runner(data) => &data.creep,
// Unknown(data) => &data.creep,
// }
// }
pub fn set_creep(&mut self, creep: screeps::Creep) {
use CreepKind::*;
match self {
Bitch(data) => data.creep = creep,
Builder(data) => data.creep = creep,
Farmer(data) => data.creep = creep,
Runner(data) => data.creep = creep,
Unknown(data) => data.creep = creep,
};
}
}
impl TryFrom<screeps::objects::Creep> for CreepKind {
type Error = Box<dyn std::error::Error>;
fn try_from(creep: screeps::objects::Creep) -> Result<Self, Self::Error> {
let mem = creep.memory();
if let Some(kind_str) = mem.string(MEM_KIND)? {
let my_room = MyRoom::by_room_name(
creep
.room()
.ok_or(Box::new(CreepError::RoomNotFound()))?
.name(),
)
.ok_or(Box::new(CreepError::RoomNotFound()))?;
Ok(match kind_str.as_str() {
k if k == CREEP_ID_BITCH => CreepKind::Bitch(CreepBitch {
my_room,
id: creep.id(),
post: mem
.string(MEM_POST)?
.ok_or(Box::new(CreepError::MissingPost(format!("{}", creep.id()))))?,
creep,
}),
k if k == CREEP_ID_BUILDER => CreepKind::Builder(CreepBuilder {
my_room,
id: creep.id(),
post: mem
.string(MEM_POST)?
.ok_or(Box::new(CreepError::MissingPost(format!("{}", creep.id()))))?,
creep,
harvesting: mem.bool(MEM_HARVESTING),
target: None,
}),
k if k == CREEP_ID_FARMER => {
let assigned_source = ObjectId::from(RawObjectId::from_hex_string(
&mem.string(MEM_ASSIGNED_SOURCE)?.ok_or(Box::new(
CreepError::MissingAssignedSource(format!("{}", creep.id())),
))?,
)?);
let room = creep.room().ok_or(Box::new(CreepError::RoomNotFound()))?;
CreepKind::Farmer(CreepFarmer {
my_room,
id: creep.id(),
post: mem
.string(MEM_POST)?
.ok_or(Box::new(CreepError::MissingPost(format!("{}", creep.id()))))?,
creep: creep.clone(),
assigned_source,
farm_position: FarmPosition::from_basic(
mem.i32(MEM_FARM_POSITION_X)?.ok_or(Box::new(
CreepError::MissingFarmPosition(format!("{}", creep.id())),
))? as u32,
mem.i32(MEM_FARM_POSITION_Y)?.ok_or(Box::new(
CreepError::MissingFarmPosition(format!("{}", creep.id())),
))? as u32,
assigned_source,
room,
),
})
}
k if k == CREEP_ID_RUNNER => {
CreepKind::Runner(CreepRunner {
my_room,
id: creep.id(),
post: mem
.string(MEM_POST)?
.ok_or(Box::new(CreepError::MissingPost(format!("{}", creep.id()))))?,
creep: creep.clone(),
state: None,
})
}
k if k == CREEP_ID_UNKNOWN => CreepKind::Unknown(CreepUnknown {
creep: creep.clone(),
}),
_ => CreepKind::Unknown(CreepUnknown {
creep: creep.clone(),
}),
})
} else {
Err(Box::new(CreepError::CreepNotConvertible()))
}
}
}
pub trait Creep {}
#[derive(Clone)]
pub struct CreepBitch {
pub id: ObjectId<screeps::objects::Creep>,
/// Identifier for the creep behaviour to link it to the RoomSettings
pub post: String,
pub my_room: MyRoom,
creep: screeps::Creep,
}
impl fmt::Debug for CreepBitch {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CreepBitch")
.field("id", &self.id)
.field("post", &self.post)
.field("my_room", &self.my_room)
.finish()
}
}
impl CreepBitch {
// pub fn memory_for_spawn(post: String) -> MemoryReference {
// let memory = MemoryReference::new();
// memory.set(MEM_POST, post.clone());
// memory.set(MEM_KIND, CREEP_ID_BITCH);
// memory.set(MEM_HARVESTING, false);
// memory
// }
//
// pub fn name_prefix() -> String {
// CREEP_ID_BITCH.into()
// }
//
pub fn run(&mut self) -> Result<(), Box<dyn Error>> {
if self.creep.memory().bool(MEM_HARVESTING) {
if self.creep.store_free_capacity(Some(ResourceType::Energy)) == 0 {
self.creep.memory().set(MEM_HARVESTING, false);
self.creep.memory().del(MEM_RESOURCE_PROVIDER_ID);
}
} else {
self.creep.say("ᕕ( ᐛ )ᕗ", true);
if self.creep.store_used_capacity(None) == 0 {
let context = BWContext::get();
let state = context.state()?;
if let Some(fetch_target) = self.calc_next_fetch(&state.room_states)? {
self.creep.memory().set(MEM_HARVESTING, true);
self.creep
.memory()
.set(MEM_RESOURCE_PROVIDER_ID, fetch_target.0.ident());
}
}
}
if self.creep.memory().bool(MEM_HARVESTING) {
let context = BWContext::get();
let state = context.state()?;
let resource_provider_id = self
.creep
.memory()
.string(MEM_RESOURCE_PROVIDER_ID)?
.ok_or(Box::new(CreepError::ResourceProviderIdNotStored))?;
let resource_provider = state
.room_states
.get(&self.my_room.room()?.name())
.map(|room_state| room_state.resource_provider(&resource_provider_id));
if let Some(Some(resource_provider)) = resource_provider {
if self.creep.pos().is_near_to(&resource_provider.pos()?) {
let res = resource_provider.creep_get_resource(
&self.creep,
ResourceType::Energy,
self.creep.store_free_capacity(Some(ResourceType::Energy)) as u32,
);
match res {
Ok(TakeResourceResult::Withdraw {
tried_amount: 0, ..
}) => {
info!("Got 0 amount while withdrawing, resetting...");
self.creep.memory().set(MEM_HARVESTING, false);
self.creep.memory().del(MEM_RESOURCE_PROVIDER_ID);
}
Ok(TakeResourceResult::Withdraw {
return_code: ReturnCode::NotEnough,
..
}) => {
info!("Return code NotEnough while Withdrawing, resetting...");
self.creep.memory().set(MEM_HARVESTING, false);
self.creep.memory().del(MEM_RESOURCE_PROVIDER_ID);
}
Ok(TakeResourceResult::Withdraw {
return_code: ReturnCode::Ok,
..
}) => {}
Ok(TakeResourceResult::Pickup {
return_code: ReturnCode::Ok,
}) => {}
Ok(TakeResourceResult::Harvest {
return_code: ReturnCode::Ok,
}) => {}
Ok(res) => {
warn!("Unhandled TakeResoult {:?}", res);
}
Err(err) => {
warn!(
"Error getting resource: {}. Resetting resource_provider",
err
);
self.creep.memory().set(MEM_HARVESTING, false);
self.creep.memory().del(MEM_RESOURCE_PROVIDER_ID);
}
};
} else {
self.creep.move_to_with_options(&resource_provider.pos()?, MoveToOptions::new().ignore_creeps(true));
}
} else {
warn!("Room provider missing, resetting Bitch {}", self.creep.id());
self.creep.memory().set(MEM_HARVESTING, false);
self.creep.memory().del(MEM_RESOURCE_PROVIDER_ID);
}
} else {
if let Some(c) = self
.creep
.room()
.expect("room is not visible to you")
.controller()
{
let r = self.creep.upgrade_controller(&c);
if r == ReturnCode::NotInRange {
self.creep.move_to(&c);
} else if r != ReturnCode::Ok {
warn!("couldn't upgrade: {:?}", r);
}
} else {
warn!("creep room has no controller!");
}
}
Ok(())
}
}
impl HandlesResource for CreepBitch {
fn calc_next_fetch<'a>(
&mut self,
rooms_state: &'a HashMap<RoomName, RoomState>,
) -> Result<Option<(&'a ResourceProvider, ResourceType, u32)>, Box<dyn Error>> {
let room = self.my_room.room()?;
let room_state = rooms_state
.get(&room.name())
.ok_or_else(|| Box::new(CreepError::RoomNotFound()))?;
let amount = self.creep.store_free_capacity(Some(ResourceType::Energy));
match room_state {
RoomState::Base(room_state) => {
let working_providers: Vec<&ResourceProvider> = room_state
.resource_providers
.iter()
.filter_map(|(_id, p)| match p.creep_can_use(&self.creep) {
Ok(true) => Some(p),
Ok(false) => None,
Err(err) => {
warn!("Could not check for `creep_can_use`: {}", err);
None
}
})
.collect();
let prioed = generic_creep_fetch_from_provider_prio(
&room,
self.creep.pos(),
working_providers,
)?;
match prioed {
Some(prov) => Ok(Some((prov, ResourceType::Energy, amount as u32))),
None => Ok(None),
}
}
RoomState::SetupBase(room_state) => {
if let SetupBaseStateVisibility::Visible{ref resource_providers, ..} = room_state.state {
let working_providers: Vec<&ResourceProvider> = resource_providers
.iter()
.filter_map(|(_id, p)| match p.creep_can_use(&self.creep) {
Ok(true) => Some(p),
Ok(false) => None,
Err(err) => {
warn!("Could not check for `creep_can_use`: {}", err);
None
}
})
.collect();
let prioed = generic_creep_fetch_from_provider_prio(
&room,
self.creep.pos(),
working_providers,
)?;
match prioed {
Some(prov) => Ok(Some((prov, ResourceType::Energy, amount as u32))),
None => Ok(None),
}
} else {
Ok(None)
}
},
}
}
}
fn generic_creep_fetch_from_provider_prio<'a>(
room: &Room,
creep_pos: Position,
working_providers: Vec<&'a ResourceProvider>,
) -> anyhow::Result<Option<&'a ResourceProvider>> {
let mut sorted = working_providers.clone();
sorted.sort_by_cached_key(|a| {
Reverse(generic_working_providers_points(room, a, &creep_pos)
.unwrap_or(Some(-10000))
.unwrap_or(-10000))
});
// sorted.sort_by(|a, b| {
// let a_p = generic_working_providers_points(room, a, &creep_pos)
// .unwrap_or(Some(-10000))
// .unwrap_or(-10000);
// let b_p = generic_working_providers_points(room, b, &creep_pos)
// .unwrap_or(Some(-10000))
// .unwrap_or(-10000);
// a_p.cmp(&b_p).reverse()
// });
Ok(sorted.first().map(|s| *s))
}
// TODO needs to know the resource type!
fn generic_working_providers_points(
room: &Room,
prov: &ResourceProvider,
for_pos: &Position,
) -> Result<Option<i32>, Box<dyn Error>> {
let mut points: i32 = 0;
match prov {
ResourceProvider::EnergyFarm { resource_farm_data } => {
points += 100;
// if let Some(source) = get_object_typed(resource_farm_data.obj_id)? {
// points += (source.energy() as f32 / 1000.).ceil() as i32;
// }
let path = resource_farm_data
.pos()?
.find_path_to(for_pos, FindOptions::default());
let vec_path = match path {
Path::Serialized(p) => room.deserialize_path(&p),
Path::Vectorized(p) => p,
};
points -= vec_path.len() as i32;
}
ResourceProvider::SourceDump { room_object_data } => {
points += 200;
// TODO Doesnt check which type of resoure yet
let resource_amount = match room_object_data {
RoomObjectData::StorageStructure { obj_id } => {
let obj = get_object_typed(*obj_id)?.ok_or_else(|| {
Box::new(CreepError::ObjectNotFound(format!("{}", *obj_id)))
})?;
obj.as_has_store()
.map(|s| s.store_used_capacity(Some(ResourceType::Energy)))
.unwrap_or(0)
}
RoomObjectData::Litter { obj_id } => {
let obj = get_object_typed(*obj_id)?.ok_or_else(|| {
Box::new(CreepError::ObjectNotFound(format!("{}", *obj_id)))
})?;
obj.amount()
}
};
// Poor man's curve
if resource_amount == 0 {
points = 0;
} else if resource_amount < 100 {
points -= resource_amount as i32;
} else if resource_amount < 500 {
points -= (resource_amount as f32 / 5.).round() as i32;
} else {
points += (resource_amount as f32 / 100.).round() as i32;
}
let path = room_object_data
.pos()?
.find_path_to(for_pos, FindOptions::default());
let vec_path = match path {
Path::Serialized(p) => room.deserialize_path(&p),
Path::Vectorized(p) => p,
};
points -= vec_path.len() as i32 * 3;
}
ResourceProvider::BufferControllerUpgrade { room_object_data } => {
points += 200;
// TODO Doesnt check which type of resoure yet
let obj = get_object_typed(room_object_data.obj_id)?.ok_or_else(|| {
Box::new(CreepError::ObjectNotFound(format!(
"{}",
room_object_data.obj_id
)))
})?;
let resource_amount = obj
.as_has_store()
.map(|s| s.store_used_capacity(Some(ResourceType::Energy)))
.unwrap_or(0);
// Poor man's curve
if resource_amount == 0 {
points = 0;
} else if resource_amount < 100 {
points -= resource_amount as i32;
} else if resource_amount < 500 {
points -= 50 - (resource_amount as f32 / 5.).round() as i32;
} else {
points += (resource_amount as f32 / 100.).round() as i32;
}
let path = room_object_data
.pos()?
.find_path_to(for_pos, FindOptions::default());
let vec_path = match path {
Path::Serialized(p) => room.deserialize_path(&p),
Path::Vectorized(p) => p,
};
points -= vec_path.len() as i32 * 3;
}
ResourceProvider::LongTermStorage { room_object_data } => {
points += 200;
// TODO Doesnt check which type of resoure yet
let obj = get_object_typed(room_object_data.obj_id)?.ok_or_else(|| {
Box::new(CreepError::ObjectNotFound(format!(
"{}",
room_object_data.obj_id
)))
})?;
let resource_amount = obj
.as_has_store()
.map(|s| s.store_used_capacity(Some(ResourceType::Energy)))
.unwrap_or(0);
if resource_amount < 20000 {
// Ensure minimum of energy
points = 1;
}
let path = room_object_data
.pos()?
.find_path_to(for_pos, FindOptions::default());
let vec_path = match path {
Path::Serialized(p) => room.deserialize_path(&p),
Path::Vectorized(p) => p,
};
points -= vec_path.len() as i32 * 3;
}
ResourceProvider::TerminalOverflow { room_object_data } => {
points += 150;
// TODO Doesnt check which type of resoure yet
let obj = get_object_typed(room_object_data.obj_id)?.ok_or_else(|| {
Box::new(CreepError::ObjectNotFound(format!(
"{}",
room_object_data.obj_id
)))
})?;
let resource_amount = obj
.as_has_store()
.map(|s| s.store_used_capacity(Some(ResourceType::Energy)))
.unwrap_or(0);
let overflow_resource_amount = resource_amount as i32 - TERMINAL_TRADE_BUFFER as i32;
if overflow_resource_amount < 0 {
// Ensure minimum of energy
points = -100;
} else if overflow_resource_amount > 1000 {
points += cmp::max((overflow_resource_amount as f32 / 10000.).round() as i32, 5);
}
let path = room_object_data
.pos()?
.find_path_to(for_pos, FindOptions::default());
let vec_path = match path {
Path::Serialized(p) => room.deserialize_path(&p),
Path::Vectorized(p) => p,
};
points -= vec_path.len() as i32 * 3;
}
_ => return Ok(None),
};
return Ok(Some(points));
}
#[derive(Clone)]
pub struct CreepBuilder {
pub id: ObjectId<screeps::objects::Creep>,
/// Identifier for the creep behaviour to link it to the RoomSettings
pub post: String,
pub my_room: MyRoom,
pub harvesting: bool,
// pub settings_ref:
creep: screeps::Creep,
target: Option<CreepBuilderTarget>,
}
impl fmt::Debug for CreepBuilder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CreepBuilder")
.field("id", &self.id)
.field("post", &self.post)
.field("my_room", &self.my_room)
.field("my_room", &self.my_room)
.field("target", &self.target)
.finish()
}
}
impl HandlesResource for CreepBuilder {
fn calc_next_fetch<'a>(
&mut self,
rooms_state: &'a HashMap<RoomName, RoomState>,
) -> Result<Option<(&'a ResourceProvider, ResourceType, u32)>, Box<dyn Error>> {
let room = self.my_room.room()?;
let room_state = rooms_state
.get(&room.name())
.ok_or_else(|| Box::new(CreepError::RoomNotFound()))?;
let amount = self.creep.store_free_capacity(Some(ResourceType::Energy));
match room_state {
RoomState::Base(room_state) => {
let working_providers: Vec<&ResourceProvider> = room_state
.resource_providers
.iter()
.filter_map(|(_id, p)| match p.creep_can_use(&self.creep) {
Ok(true) => Some(p),
Ok(false) => None,
Err(err) => {
warn!("Could not check for `creep_can_use`: {}", err);
None
}
})
.collect();
let prioed = generic_creep_fetch_from_provider_prio(
&room,
self.creep.pos(),
working_providers,
)?;
match prioed {
Some(prov) => Ok(Some((prov, ResourceType::Energy, amount as u32))),
None => Ok(None),
}
}
RoomState::SetupBase(room_state) => {
if let SetupBaseStateVisibility::Visible{ref resource_providers, ..} = room_state.state {
let working_providers: Vec<&ResourceProvider> = resource_providers
.iter()
.filter_map(|(_id, p)| match p.creep_can_use(&self.creep) {
Ok(true) => Some(p),
Ok(false) => None,
Err(err) => {
warn!("Could not check for `creep_can_use`: {}", err);
None
}
})
.collect();
let prioed = generic_creep_fetch_from_provider_prio(
&room,
self.creep.pos(),
working_providers,
)?;
match prioed {
Some(prov) => Ok(Some((prov, ResourceType::Energy, amount as u32))),
None => Ok(None),
}
} else {
Ok(None)
}
},
}
}
}
#[derive(Clone, Debug)]
enum CreepBuilderTarget {
Build(ObjectId<ConstructionSite>),
Repair(ObjectId<Structure>),
}
impl CreepBuilder {
pub fn memory_for_spawn(post: String) -> MemoryReference {
let memory = MemoryReference::new();
memory.set(MEM_POST, post.clone());
memory.set(MEM_KIND, CREEP_ID_BUILDER);
memory.set(MEM_HARVESTING, false);
memory
}
pub fn name_prefix() -> String {
CREEP_ID_BUILDER.into()
}
fn set_getting_resource(&mut self, resource_provider: Option<&ResourceProvider>) {
self.creep
.memory()
.set(MEM_HARVESTING, resource_provider.is_some());
self.harvesting = resource_provider.is_some();
if let Some(resource_provider) = resource_provider {
self.creep
.memory()
.set(MEM_RESOURCE_PROVIDER_ID, resource_provider.ident());
} else {
self.creep.memory().del(MEM_RESOURCE_PROVIDER_ID);
}
}
fn set_target(&mut self, target: Option<CreepBuilderTarget>) {
// TODO Serialization of RawObjectId
// self.creep.memory().set(MEM_BUILD_TARGET, harvesting);
self.target = target;
}
pub fn harvest_check(&mut self) -> Result<(), Box<dyn Error>> {
if self.harvesting {
if self.creep.store_free_capacity(Some(ResourceType::Energy)) == 0 {
self.set_getting_resource(None);
}
} else {
self.creep.say("ᕕ( ᐛ )ᕗ", true);
if self.creep.store_used_capacity(None) == 0 {
let context = BWContext::get();
let state = context.state()?;
if let Some(fetch_target) = self.calc_next_fetch(&state.room_states)? {
self.set_getting_resource(Some(fetch_target.0));
}
}
}
Ok(())
}
pub fn harvest(&mut self) -> Result<(), Box<dyn Error>> {
let context = BWContext::get();
let state = context.state()?;
let resource_provider_id = self.creep.memory().string(MEM_RESOURCE_PROVIDER_ID)?;
let resource_provider_id = match resource_provider_id {
Some(id) => id,
None => {
warn!(
"Room provider not found for id, resetting Builder {}",
self.creep.id()
);
self.set_getting_resource(None);
return Err(Box::new(CreepError::ResourceProviderIdNotStored));
}
};
let resource_provider = state
.room_states
.get(&self.my_room.room()?.name())
.map(|room_state| room_state.resource_provider(&resource_provider_id));
if let Some(Some(resource_provider)) = resource_provider {
if self.creep.pos().is_near_to(&resource_provider.pos()?) {
let res = resource_provider.creep_get_resource(
&self.creep,
ResourceType::Energy,
self.creep.store_free_capacity(Some(ResourceType::Energy)) as u32,
);
match res {
Ok(TakeResourceResult::Withdraw {
tried_amount: 0, ..
}) => {
info!("Got 0 amount while withdrawing, resetting...");
self.set_getting_resource(None);
}
Ok(TakeResourceResult::Withdraw {
return_code: ReturnCode::NotEnough,
..
}) => {
info!("Return code NotEnough while Withdrawing, resetting...");
self.set_getting_resource(None);
}
Ok(TakeResourceResult::Withdraw {
return_code: ReturnCode::Ok,
..
}) => {}
Ok(TakeResourceResult::Pickup {
return_code: ReturnCode::Ok,
}) => {}
Ok(TakeResourceResult::Harvest {
return_code: ReturnCode::Ok,
}) => {}
Ok(res) => {
warn!("Unhandled TakeResoult {:?}", res);
}
Err(err) => {
warn!(
"Error getting resource: {}. Resetting resource_provider",
err
);
self.set_getting_resource(None);
}
};
} else {
self.creep.move_to(&resource_provider.pos()?);
}
} else {
warn!(
"Room provider missing, resetting Builder {}",
self.creep.id()
);
self.set_getting_resource(None);
}
Ok(())
}
pub fn build(&mut self) -> Result<(), Box<dyn Error>> {
let room = &self
.creep
.room()
.ok_or(Box::new(CreepError::RoomNotFound()))?;
// Precursory checks
match &self.target {
Some(_target) => {}
None => {
// Get new target
let context = BWContext::get();
let state = context.state()?;
let room_settings = state
.room_settings
.get(&self.my_room)
.ok_or(Box::new(CreepError::RoomNotFound()))?;
match (
get_prio_repair_target(room)?,
room_settings.maintenance.priority_item()?,
) {
// TODO Use `RoomMaintenance also for repairs
(Some(RepairTarget::Important { target }), _) => {
self.set_target(Some(CreepBuilderTarget::Repair(target.id().into())));
}
(Some(RepairTarget::Arbeitsbeschaffung { .. }), Some(item)) => {
match item {
RoomMaintenance::NewBuild { object_id } => {
self.set_target(Some(CreepBuilderTarget::Build(
object_id.to_owned(),
)));
}
RoomMaintenance::Repair { object_id } => {
// TODO Better way of getting an ObjectId<Structure> from the
// `RoomMaintenance` object
let structure =
get_object_typed::<Structure>(object_id.to_owned().into());
if let Ok(Some(structure)) = structure {
self.set_target(Some(CreepBuilderTarget::Repair(
structure.id(),
)));
} else {
warn!("Unknown repair `object_id` {:?}", object_id);
}
}
}
}
(Some(RepairTarget::Arbeitsbeschaffung { target }), None) => {
self.set_target(Some(CreepBuilderTarget::Repair(target.id().into())));
}
(None, Some(item)) => {
match item {
RoomMaintenance::NewBuild { object_id } => {
self.set_target(Some(CreepBuilderTarget::Build(
object_id.to_owned(),
)));
}
RoomMaintenance::Repair { object_id } => {
// TODO Better way of getting an ObjectId<Structure> from the
// `RoomMaintenance` object
let structure =
get_object_typed::<Structure>(object_id.to_owned().into());
if let Ok(Some(structure)) = structure {
self.set_target(Some(CreepBuilderTarget::Repair(
structure.id(),
)));
} else {
warn!("Unknown repair `object_id` {:?}", object_id);
}
}
}
}
_ => {}
};
}
}
// Move & build/repair
if let Some(target) = &self.target {
match target {
CreepBuilderTarget::Build(build_target) => {
let object = get_object_typed(build_target.to_owned().into());
match object {
Ok(Some(target)) => {
if self.creep.pos().is_near_to(&target) {
let r = self.creep.build(&target);
if r != ReturnCode::Ok {
warn!("couldn't build: {:?}", r);
self.set_target(None);
}
} else {
self.creep.move_to(&target);
}
}
Ok(None) => {
warn!("Build target missing");
self.set_target(None);
}
Err(_) => {
// Object not with the expected type
warn!("Build target unexpected type");
self.set_target(None);
}
}
}
CreepBuilderTarget::Repair(repair_target) => {
let object = get_object_typed(repair_target.to_owned().into())?;
match object {
Some(target) => {
if let Some(attackable_target) = target.as_attackable() {
if self.creep.pos().in_range_to(&target, 3) {
let r = self.creep.repair(&target);
if r != ReturnCode::Ok {
warn!("couldn't repair: {:?}", r);
self.set_target(None);
}
} else {
self.creep.move_to(&target);
}
if attackable_target.hits() == attackable_target.hits_max() {
self.set_target(None);
}
} else {
Err(CreepError::RepairNotAttackable(format!("{}", target.id())))?;
}
}
None => {
warn!("Repair target missing");
self.set_target(None);
}
};
}
}
}
Ok(())
}
}
#[derive(Clone)]
pub enum RepairTarget {
Arbeitsbeschaffung { target: Structure },
Important { target: Structure },
}
const HIGHER_NUM: f64 = 1_000_000_000_000.;
// const HIGHER_NUM: f32 = 10.;
pub fn get_prio_repair_target(room: &Room) -> Result<Option<RepairTarget>, Box<dyn Error>> {
let mut repairable_structures: Vec<Structure> = room
.find(find::STRUCTURES)
.into_iter()
.filter(|struc| match struc {
Structure::Road(road) => road.hits() < (road.hits_max() as f32 * 0.5).round() as u32,
Structure::Container(container) => {
container.hits() < (container.hits_max() as f32 * 0.7).round() as u32
}
Structure::Wall(_) => true,
Structure::Rampart(_) => true,
_ => false,
})
.collect();
repairable_structures.sort_by_cached_key(|a| {
-get_structure_prio_val(a)
});
Ok(repairable_structures.first().map(|s| {
if get_structure_prio_val(s) < HIGHER_NUM as i64 + 10 {
RepairTarget::Arbeitsbeschaffung { target: s.clone() }
} else {
RepairTarget::Important { target: s.clone() }
}
}))
}
const TARGET_WALLING: f64 = 10_000_000.;
fn get_structure_prio_val(structure: &Structure) -> i64 {
match structure {
Structure::Road(road) => (HIGHER_NUM
+ ((1. - road.hits() as f64 / road.hits_max() as f64) * 100.))
.round() as i64,
Structure::Container(container) => (HIGHER_NUM
+ ((1. - container.hits() as f64 / container.hits_max() as f64) * 100.))
.round() as i64,
Structure::Rampart(rampart) => (HIGHER_NUM
+ ((1. - rampart.hits() as f64 / TARGET_WALLING as f64) * 1.01))
.round() as i64,
Structure::Wall(wall) => {
(HIGHER_NUM * ((1. - wall.hits() as f64 / TARGET_WALLING) * 1.)).round() as i64
}
_ => -1,
}
}
#[derive(Clone)]
pub struct CreepFarmer {
pub id: ObjectId<screeps::objects::Creep>,
/// Identifier for the creep behaviour to link it to the RoomSettings
pub post: String,
pub my_room: MyRoom,
creep: screeps::Creep,
assigned_source: ObjectId<Source>,
farm_position: FarmPosition,
}
impl fmt::Debug for CreepFarmer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CreepFarmer")
.field("id", &self.id)
.field("post", &self.post)
.field("my_room", &self.my_room)
.field("assigned_source", &self.assigned_source)
.field("farm_position", &self.farm_position)
.finish()
}
}
impl CreepFarmer {
pub fn memory_for_spawn(post: String, farm_position: &FarmPosition) -> MemoryReference {
let memory = MemoryReference::new();
memory.set(MEM_POST, post.clone());
memory.set(MEM_KIND, CREEP_ID_FARMER);
memory.set(MEM_FARM_POSITION_X, farm_position.position().x());
memory.set(MEM_FARM_POSITION_Y, farm_position.position().y());
memory.set(
MEM_ASSIGNED_SOURCE,
RawObjectId::from(farm_position.for_source()).to_hex_string(),
);
memory
}
pub fn name_prefix() -> String {
CREEP_ID_FARMER.into()
}
//
// fn set_assigned_source(&mut self, assigned_source: ObjectId<Source>) {
// // TODO Serialization of RawObjectId
// // self.creep.memory().set(MEM_assigned_source, harvesting);
// self.assigned_source = assigned_source;
// }
pub fn harvest(&mut self) -> Result<(), Box<dyn Error>> {
let source = get_object_typed(self.assigned_source)?.ok_or_else(|| {
Box::new(CreepError::SourceNotFound(format!(
"{}",
self.assigned_source
)))
})?;
let target_pos = self.farm_position.position();
if self.creep.pos() == target_pos {
let r = self.creep.harvest(&source);
if r != ReturnCode::Ok {
warn!("couldn't harvest: {:?}", r);
}
} else {
self.creep.move_to(&target_pos);
}
Ok(())
}
}
#[derive(Clone)]
pub struct CreepRunner {
pub id: ObjectId<screeps::objects::Creep>,
/// Identifier for the creep behaviour to link it to the RoomSettings
pub post: String,
pub my_room: MyRoom,
pub state: Option<CreepRunnerState>,
creep: screeps::Creep,
}
impl fmt::Debug for CreepRunner {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CreepRunner")
.field("id", &self.id)
.field("post", &self.post)
.field("my_room", &self.my_room)
.field("state", &self.state)
.finish()
}
}
#[derive(Clone, Debug)]
pub enum CreepRunnerState {
Fetching {
from: CreepRunnerFetchTarget,
to: CreepRunnerDeliverTarget,
},
Delivering {
to: CreepRunnerDeliverTarget,
provided: u32,
},
}
impl CreepRunner {
pub fn memory_for_spawn(post: String) -> MemoryReference {
let memory = MemoryReference::new();
memory.set(MEM_POST, post.clone());
memory.set(MEM_KIND, CREEP_ID_RUNNER);
memory
}
pub fn name_prefix() -> String {
CREEP_ID_RUNNER.into()
}
pub fn run(&mut self) -> Result<(), Box<dyn Error>> {
let room = self.my_room.room()?;
if let Some(state) = &self.state {
match state {
CreepRunnerState::Fetching { to, .. } => {
if self.creep.store_free_capacity(Some(ResourceType::Energy)) == 0
|| self.creep.store_used_capacity(Some(ResourceType::Energy))
>= to.requested()
{
warn!("to deliver");
self.state = Some(CreepRunnerState::Delivering {
to: to.clone(),
provided: 0,
});
}
}
CreepRunnerState::Delivering { to, provided } => {
if self.creep.store_used_capacity(Some(ResourceType::Energy)) == 0
|| *provided >= to.requested()
{
warn!("deliver to new");
self.new_run()?;
}
}
}
} else {
warn!("no state to new");
self.new_run()?;
}
if let Some(state) = &mut self.state {
match state {
CreepRunnerState::Fetching { from, .. } => {
if self.creep.pos().is_near_to(&from.pos()) {
match from {
CreepRunnerFetchTarget::PermanentFarmerContainer { id, .. } => {
let obj = get_object_typed(*id)?.ok_or(Box::new(
CreepError::ObjectNotFound(format!("{}", id)),
))?;
let amount = cmp::min(
// to.requested(),
self.creep.store_free_capacity(Some(ResourceType::Energy)) as u32,
obj.store_used_capacity(Some(ResourceType::Energy)),
);
self.creep
.withdraw_amount(&obj, ResourceType::Energy, amount);
}
CreepRunnerFetchTarget::Ruin { id, .. } => {
let obj = get_object_typed(*id)?.ok_or(Box::new(
CreepError::ObjectNotFound(format!("{}", id)),
))?;
let amount = cmp::min(
self.creep.store_free_capacity(Some(ResourceType::Energy))
as u32,
// HACK stupid if I fill one extension requesting 50 energy
// cmp::min(
// to.requested(),
obj.store_used_capacity(Some(ResourceType::Energy)),
// ),
);
self.creep
.withdraw_amount(&obj, ResourceType::Energy, amount);
}
CreepRunnerFetchTarget::DroppedSource { id, pos, .. } => {
let obj = get_object_typed(*id)?;
let farmer_container =
room.look_for_at(look::STRUCTURES, pos);
if let Some(obj) = obj {
info!("We have object, also container?");
if obj.amount() < 200 && farmer_container.len() > 0 {
self.creep.pickup(&obj);
// HACK Remove me breaks taking energy
// We might not have picked up enough, and there might be a
// container from a farmer underneath with more
if let Some(Structure::Container(container)) =
farmer_container.first()
{
let container_amount = cmp::min(
// to.requested(),
// HACK Based on the run, it should take all or ony
// some energy
self.creep
.store_free_capacity(Some(ResourceType::Energy)),
container
.store_used_capacity(Some(ResourceType::Energy)) as i32,
) - obj.amount() as i32;
info!("Grabbing from Container: {} // Amount: {}", farmer_container.len(), container_amount);
if container_amount > 0 {
self.creep.withdraw_amount(
container,
ResourceType::Energy,
container_amount as u32,
);
}
}
} else {
// NOTE Can't control how much I pick up with `pickup` ಠ_ಠ
self.creep.pickup(&obj);
}
} else {
if farmer_container.len() > 0 {
warn!("Dropped source not found, using container");
// HACK
// If no dropped source is there, perhaps the container
// still has resource
if let Some(Structure::Container(container)) =
farmer_container.first()
{
let amount = cmp::min(
// to.requested(),
// HACK Based on the run, it should take all or ony
// some energy
self.creep
.store_free_capacity(Some(ResourceType::Energy)) as u32,
container
.store_used_capacity(Some(ResourceType::Energy)),
);
self.creep.withdraw_amount(
container,
ResourceType::Energy,
amount,
);
}
} else {
warn!("Dropped source not found, resetting Runner");
self.new_run()?;
}
}
}
CreepRunnerFetchTarget::Terminal { id, .. } => {
let obj = get_object_typed(*id)?.ok_or(Box::new(
CreepError::ObjectNotFound(format!("{}", id)),
))?;
let amount = cmp::min(
// to.requested(),
self.creep.store_free_capacity(Some(ResourceType::Energy)) as u32,
obj.store_used_capacity(Some(ResourceType::Energy)),
);
self.creep
.withdraw_amount(&obj, ResourceType::Energy, amount);
}
}
// FIXME Hack
self.new_run()?;
} else {
self.creep.move_to(&from.pos());
}
}
CreepRunnerState::Delivering { to, provided } => {
if self.creep.pos().is_near_to(&to.pos()) {
match to {
CreepRunnerDeliverTarget::Tower { id, .. } => {
let obj = get_object_typed(*id)?.ok_or(Box::new(
CreepError::ObjectNotFound(format!("{}", id)),
))?;
let amount = cmp::min(
to.requested(),
self.creep.store_used_capacity(Some(ResourceType::Energy)),
);
self.creep
.transfer_amount(&obj, ResourceType::Energy, amount);
*provided += amount;
}
CreepRunnerDeliverTarget::Extension { id, .. } => {
let obj = get_object_typed(*id)?.ok_or(Box::new(
CreepError::ObjectNotFound(format!("{}", id)),
))?;
let amount = cmp::min(
to.requested(),
self.creep.store_used_capacity(Some(ResourceType::Energy)),
);
self.creep
.transfer_amount(&obj, ResourceType::Energy, amount);
*provided += amount;
}
CreepRunnerDeliverTarget::Spawn { id, .. } => {
let obj = get_object_typed(*id)?.ok_or(Box::new(
CreepError::ObjectNotFound(format!("{}", id)),
))?;
let amount = cmp::min(
to.requested(),
self.creep.store_used_capacity(Some(ResourceType::Energy)),
);
self.creep
.transfer_amount(&obj, ResourceType::Energy, amount);
*provided += amount;
}
CreepRunnerDeliverTarget::PermanentUpgraderContainer { id, .. } => {
let obj = get_object_typed(*id)?.ok_or(Box::new(
CreepError::ObjectNotFound(format!("{}", id)),
))?;
let amount = cmp::min(
to.requested(),
self.creep.store_used_capacity(Some(ResourceType::Energy)),
);
self.creep
.transfer_amount(&obj, ResourceType::Energy, amount);
*provided += amount;
}
CreepRunnerDeliverTarget::TempStorage { id, .. } => {
let obj = get_object_typed(*id)?.ok_or(Box::new(
CreepError::ObjectNotFound(format!("{}", id)),
))?;
let amount = cmp::min(
to.requested(),
self.creep.store_used_capacity(Some(ResourceType::Energy)),
);
self.creep
.transfer_amount(&obj, ResourceType::Energy, amount);
*provided += amount;
}
CreepRunnerDeliverTarget::TradeTransactionFee { id, .. } => {
let obj = get_object_typed(*id)?.ok_or(Box::new(
CreepError::ObjectNotFound(format!("terminal TradeTransactionFee {}", id)),
))?;
let amount = cmp::min(
to.requested(),
self.creep.store_used_capacity(Some(ResourceType::Energy)),
);
self.creep
.transfer_amount(&obj, ResourceType::Energy, amount);
*provided += amount;
}
}
} else {
self.creep.move_to(&to.pos());
}
}
}
}
Ok(())
}
pub fn new_run(&mut self) -> Result<(), Box<dyn Error>> {
let room = self.my_room.room()?;
let deliver_target = get_prio_deliver_target(&room, &self.creep)?;
info!("del target {:?} in {}", deliver_target, room.name());
if let Some(deliver_target) = deliver_target {
if deliver_target.requested()
<= self.creep.store_used_capacity(Some(ResourceType::Energy))
{
self.state = Some(CreepRunnerState::Delivering {
to: deliver_target,
provided: 0,
});
} else {
let fetch_target = get_prio_fetch_target(&room, &deliver_target, &self.creep.pos())?;
if let Some(fetch_target) = fetch_target {
self.state = Some(CreepRunnerState::Fetching {
from: fetch_target,
to: deliver_target,
});
} else {
info!(
"Delivery requested, but no provider in room {}",
room.name()
);
}
}
Ok(())
} else {
debug!("Nothing to do in room {}", room.name());
Ok(())
}
}
}
/// Searches for something that provides the resources for the delivery_target
fn get_prio_fetch_target(
room: &Room,
_delivery_target: &CreepRunnerDeliverTarget,
creep_pos: &Position,
) -> Result<Option<CreepRunnerFetchTarget>, Box<dyn Error>> {
let controller = room.controller().ok_or(anyhow!("Controller not found"))?;
let mut containers: Vec<StructureContainer> = room
.find(find::STRUCTURES)
.into_iter()
.filter_map(|s| match s {
Structure::Container(container) => Some(container),
_ => None,
})
.collect();
// TODO Dummy implementation
containers.sort_by_cached_key(|container| {
let path_len = container.pos().find_path_to(creep_pos, FindOptions::default()).vectorized().unwrap_or(vec![]).len() as i32;
-(container.store_used_capacity(Some(ResourceType::Energy)) as i32
- path_len * 100)
});
let viable_containers: Vec<CreepRunnerFetchTarget> = containers
.into_iter()
// HACK controller check will be done differently
.filter(|c| c.store_used_capacity(Some(ResourceType::Energy)) > 100 && !c.pos().in_range_to(&controller, 3))
.map(|c| CreepRunnerFetchTarget::PermanentFarmerContainer {
id: c.id(),
pos: c.pos(),
provides: c.store_used_capacity(Some(ResourceType::Energy)),
})
.collect();
let mut dropped_resources: Vec<screeps::Resource> = room
.find(find::DROPPED_RESOURCES)
.into_iter()
.filter(|res| res.resource_type() == ResourceType::Energy)
.collect();
dropped_resources.sort_by(|res_a, res_b| res_a.amount().cmp(&res_b.amount()).reverse());
let viable_dropped_sources: Vec<CreepRunnerFetchTarget> = dropped_resources
.into_iter()
.map(|res| CreepRunnerFetchTarget::DroppedSource {
id: res.id(),
pos: res.pos(),
provides: res.amount(),
})
.collect();
let viable_ruins: Vec<CreepRunnerFetchTarget> = room
.find(find::RUINS)
.into_iter()
.filter_map(|r| {
let energy = r.store_used_capacity(Some(ResourceType::Energy));
if energy == 0 {
return None;
}
Some(CreepRunnerFetchTarget::Ruin {
id: r.id(),
pos: r.pos(),
provides: energy,
})
})
.collect();
let terminal: Vec<CreepRunnerFetchTarget> = room
.find(find::STRUCTURES)
.into_iter()
.filter_map(|s| match s {
Structure::Terminal(terminal) => {
if terminal.store_used_capacity(Some(ResourceType::Energy)) > TERMINAL_TRADE_BUFFER {
Some(CreepRunnerFetchTarget::Terminal {
id: terminal.id(),
pos: terminal.pos(),
provides: terminal.store_free_capacity(Some(ResourceType::Energy))
as u32 - TERMINAL_TRADE_BUFFER,
})
} else {
None
}
}
_ => None,
})
.collect();
if viable_ruins.len() > 0 {
Ok(viable_ruins.first().and_then(|c| Some(c.clone())))
} else if viable_dropped_sources.len() > 0 {
Ok(viable_dropped_sources.first().and_then(|c| Some(c.clone())))
} else if viable_containers.len() > 0 {
Ok(viable_containers.first().and_then(|c| Some(c.clone())))
} else {
Ok(terminal.first().and_then(|c| Some(c.clone())))
}
}
fn get_prio_deliver_target(
room: &Room,
creep: &screeps::Creep,
) -> Result<Option<CreepRunnerDeliverTarget>, Box<dyn Error>> {
// TODO Dummy implementation
let structures = room.find(find::STRUCTURES);
let mut extensions: Vec<&StructureExtension> = structures
.iter()
.filter_map(|s| match s {
Structure::Extension(ext) => {
if ext.store_free_capacity(Some(ResourceType::Energy)) > 0 {
Some(ext)
} else {
None
}
}
_ => None,
})
.collect();
extensions.sort_by_cached_key(|ext| {
// let a_cap = ext
// .store_free_capacity(Some(ResourceType::Energy));
// let b_cap = ext_b
// .store_free_capacity(Some(ResourceType::Energy));
let range = ext.pos().find_path_to(creep, FindOptions::default());
range.vectorized().unwrap().len() as i32
});
let viable_extensions: Vec<CreepRunnerDeliverTarget> = extensions
.into_iter()
.map(|ext| CreepRunnerDeliverTarget::Extension {
id: ext.id(),
pos: ext.pos(),
requested: ext.store_free_capacity(Some(ResourceType::Energy)) as u32,
})
.collect();
let mut spawns: Vec<&StructureSpawn> = structures
.iter()
.filter_map(|s| match s {
Structure::Spawn(spawn) => {
if spawn.store_free_capacity(Some(ResourceType::Energy)) > 0 {
Some(spawn)
} else {
None
}
}
_ => None,
})
.collect();
spawns.sort_by(|spawn_a, spawn_b| {
spawn_a
.store_free_capacity(Some(ResourceType::Energy))
.cmp(&spawn_b.store_free_capacity(Some(ResourceType::Energy)))
.reverse()
});
let viable_spawns: Vec<CreepRunnerDeliverTarget> = spawns
.into_iter()
.map(|spawn| CreepRunnerDeliverTarget::Spawn {
id: spawn.id(),
pos: spawn.pos(),
requested: spawn.store_free_capacity(Some(ResourceType::Energy)) as u32,
})
.collect();
let mut towers: Vec<&StructureTower> = structures
.iter()
.filter_map(|s| match s {
Structure::Tower(tower) => {
if tower.store_free_capacity(Some(ResourceType::Energy)) > 0 {
Some(tower)
} else {
None
}
}
_ => None,
})
.collect();
towers.sort_by(|tower_a, tower_b| {
tower_a
.store_free_capacity(Some(ResourceType::Energy))
.cmp(&tower_b.store_free_capacity(Some(ResourceType::Energy)))
.reverse()
});
let viable_towers: Vec<CreepRunnerDeliverTarget> = towers
.into_iter()
.map(|tower| CreepRunnerDeliverTarget::Tower {
id: tower.id(),
pos: tower.pos(),
requested: tower.store_free_capacity(Some(ResourceType::Energy)) as u32,
})
.collect();
let viable_containers = if let Some(controller) = room.controller() {
let structures = room.look_for_around(look::STRUCTURES, controller.pos(), 3)?;
structures
.iter()
.filter_map(|s| match s {
Structure::Container(container) => {
if container.store_free_capacity(Some(ResourceType::Energy)) > 50 {
Some(CreepRunnerDeliverTarget::PermanentUpgraderContainer {
id: container.id(),
pos: container.pos(),
requested: container.store_free_capacity(Some(ResourceType::Energy))
as u32,
})
} else {
None
}
}
_ => None,
})
.collect()
} else {
vec![]
};
let storage: Vec<CreepRunnerDeliverTarget> = structures
.iter()
.filter_map(|s| match s {
Structure::Storage(storage) => {
if storage.store_free_capacity(Some(ResourceType::Energy)) > 0 {
Some(CreepRunnerDeliverTarget::TempStorage {
id: storage.id(),
pos: storage.pos(),
requested: storage.store_free_capacity(Some(ResourceType::Energy))
as u32,
})
} else {
None
}
}
_ => None,
})
.collect();
let terminal: Vec<CreepRunnerDeliverTarget> = structures
.iter()
.filter_map(|s| match s {
Structure::Terminal(terminal) => {
if terminal.store_used_capacity(Some(ResourceType::Energy)) < TERMINAL_TRADE_BUFFER {
Some(CreepRunnerDeliverTarget::TradeTransactionFee {
id: terminal.id(),
pos: terminal.pos(),
requested: terminal.store_free_capacity(Some(ResourceType::Energy))
as u32,
})
} else {
None
}
}
_ => None,
})
.collect();
if viable_extensions.len() > 0 {
Ok(viable_extensions.first().and_then(|c| Some(c.clone())))
} else if viable_spawns.len() > 0 {
Ok(viable_spawns.first().and_then(|c| Some(c.clone())))
} else if viable_towers.len() > 0 {
Ok(viable_towers.first().and_then(|c| Some(c.clone())))
} else if viable_containers.len() > 0 {
Ok(viable_containers.first().and_then(|c| Some(c.clone())))
} else if terminal.len() > 0 {
Ok(terminal.first().and_then(|c| Some(c.clone())))
} else{
Ok(storage.first().and_then(|c| Some(c.clone())))
}
}
#[derive(Clone, Debug)]
pub enum CreepRunnerFetchTarget {
PermanentFarmerContainer {
id: ObjectId<StructureContainer>,
pos: Position,
provides: u32,
},
Ruin {
id: ObjectId<Ruin>,
pos: Position,
provides: u32,
},
DroppedSource {
id: ObjectId<Resource>,
pos: Position,
provides: u32,
},
Terminal {
id: ObjectId<StructureTerminal>,
pos: Position,
provides: u32,
},
}
impl CreepRunnerFetchTarget {
fn pos(&self) -> Position {
use CreepRunnerFetchTarget::*;
match self {
PermanentFarmerContainer { pos, .. } => *pos,
Ruin { pos, .. } => *pos,
DroppedSource { pos, .. } => *pos,
Terminal { pos, .. } => *pos,
}
}
}
#[derive(Clone, Debug)]
pub enum CreepRunnerDeliverTarget {
Extension {
id: ObjectId<StructureExtension>,
pos: Position,
requested: u32,
},
Tower {
id: ObjectId<StructureTower>,
pos: Position,
requested: u32,
},
Spawn {
id: ObjectId<StructureSpawn>,
pos: Position,
requested: u32,
},
PermanentUpgraderContainer {
id: ObjectId<StructureContainer>,
pos: Position,
requested: u32,
},
TempStorage {
id: ObjectId<StructureStorage>,
pos: Position,
requested: u32,
},
TradeTransactionFee {
id: ObjectId<StructureTerminal>,
pos: Position,
requested: u32,
},
// TODO might make sense to differentiate the two, e.g. backup Storage
// should always be there in times of needs, TempStorage just for if
// nothing else accepts energy.
// BackupStorage {
// id: ObjectId<StructureContainer>,
// pos: Position,
// requested: u32,
// },
}
impl CreepRunnerDeliverTarget {
pub fn pos(&self) -> Position {
use CreepRunnerDeliverTarget::*;
match self {
Extension { pos, .. } => *pos,
Tower { pos, .. } => *pos,
Spawn { pos, .. } => *pos,
PermanentUpgraderContainer { pos, .. } => *pos,
TempStorage { pos, .. } => *pos,
TradeTransactionFee { pos, .. } => *pos,
}
}
fn requested(&self) -> u32 {
use CreepRunnerDeliverTarget::*;
match self {
Extension { requested, .. } => *requested,
Tower { requested, .. } => *requested,
Spawn { requested, .. } => *requested,
PermanentUpgraderContainer { requested, .. } => *requested,
TempStorage { requested, .. } => *requested,
TradeTransactionFee { requested, .. } => *requested,
}
}
}
#[derive(Clone)]
pub struct CreepUnknown {
creep: screeps::Creep,
}
impl fmt::Debug for CreepUnknown {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CreepUnknown").finish()
}
}
#[derive(Clone)]
pub struct TrySpawnOptions<'a> {
pub assumed_job: OokCreepJob,
pub available_spawns: Vec<ObjectId<StructureSpawn>>,
/// We really need the creep, allow to go way below `target_energy_usage`
pub force_spawn: bool,
pub race: OokRaceKind,
pub spawn_room: &'a Room,
pub target_energy_usage: u32,
pub request_id: Option<UniqId>,
pub preset_parts: Option<Vec<Part>>,
}
impl<'a> fmt::Debug for TrySpawnOptions<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TrySpawnOptions")
.field("assumed_job", &self.assumed_job)
.field("available_spawns", &self.available_spawns)
.field("force_spawn", &self.force_spawn)
.field("race", &self.race)
.field("spawn_room", &self.spawn_room.name())
.field("target_energy_usage", &self.target_energy_usage)
.field("request_id", &self.request_id)
.finish()
}
}
#[derive(Debug, Clone)]
pub enum TrySpawnResult {
Spawned(TrySpawnResultData),
ForceSpawned(TrySpawnResultData),
Skipped,
}
#[derive(Debug, Clone)]
pub struct TrySpawnResultData {
pub return_code: ReturnCode,
pub used_energy_amount: u32,
pub used_spawn: ObjectId<StructureSpawn>,
pub creep_name: String,
}
#[derive(Debug, Clone)]
pub struct CalcSpawnBodyResult {
pub amount: u32,
pub body: Vec<creep::Part>,
}
pub trait Spawnable<O: fmt::Debug + Clone> {
fn try_spawn(opts: &TrySpawnOptions, race_opts: &O) -> anyhow::Result<TrySpawnResult>;
fn calc_spawn_body(opts: &TrySpawnOptions, race_opts: &O) -> anyhow::Result<CalcSpawnBodyResult>;
}
#[derive(Debug, Clone)]
struct MoveMatrix {
road: u32,
land: u32,
swamp: u32,
}
#[derive(Debug, Clone)]
pub enum OokPresentCreep {
Spawning(OokRace),
Alive(OokRace),
Dead(),
}
impl OokPresentCreep {
pub fn alive(&self) -> Option<&OokRace> {
use OokPresentCreep::*;
match self {
Alive(creep) => Some(creep),
_ => None,
}
}
}
| 40.548889 | 530 | 0.458075 |
b9e9f55971dc4996d83fc748120613560b32fc1d | 176 | // Copyright 2019 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! IPC front handlers
pub mod domain_socket;
pub mod front_end;
pub mod listener;
| 25.142857 | 53 | 0.772727 |
c17833ee830707a68594d794735dec2ba9354486 | 595 | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
macro_rules! t {
() => ( String ; ); //~ ERROR macro expansion ignores token `;`
}
fn main() {
let i: Vec<t!()>;
}
| 33.055556 | 71 | 0.690756 |
f5994fa419b33ba70b9d1f720d9c59070dcfb647 | 10,656 | extern crate clap;
use self::clap::{App, Arg};
use clap::crate_version;
use regex::Regex;
use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};
trait Executor {
fn execute(&mut self, args: Vec<String>) -> String;
fn last_executed(&self) -> Option<Vec<String>>;
}
struct RealShell {
executed: Option<Vec<String>>,
}
impl RealShell {
fn new() -> RealShell {
RealShell { executed: None }
}
}
impl Executor for RealShell {
fn execute(&mut self, args: Vec<String>) -> String {
let execution = Command::new(args[0].as_str())
.args(&args[1..])
.output()
.expect("Couldn't run it");
self.executed = Some(args);
let output: String = String::from_utf8_lossy(&execution.stdout).into();
output.trim_end().to_string()
}
fn last_executed(&self) -> Option<Vec<String>> {
self.executed.clone()
}
}
const TMP_FILE: &str = "/tmp/thumbs-last";
pub struct Swapper<'a> {
executor: Box<&'a mut dyn Executor>,
dir: String,
command: String,
upcase_command: String,
active_pane_id: Option<String>,
active_pane_height: Option<i32>,
active_pane_scroll_position: Option<i32>,
active_pane_in_copy_mode: Option<String>,
thumbs_pane_id: Option<String>,
content: Option<String>,
signal: String,
}
impl<'a> Swapper<'a> {
fn new(executor: Box<&'a mut dyn Executor>, dir: String, command: String, upcase_command: String) -> Swapper {
let since_the_epoch = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("Time went backwards");
let signal = format!("thumbs-finished-{}", since_the_epoch.as_secs());
Swapper {
executor,
dir,
command,
upcase_command,
active_pane_id: None,
active_pane_height: None,
active_pane_scroll_position: None,
active_pane_in_copy_mode: None,
thumbs_pane_id: None,
content: None,
signal,
}
}
pub fn capture_active_pane(&mut self) {
let active_command = vec![
"tmux",
"list-panes",
"-F",
"#{pane_id}:#{?pane_in_mode,1,0}:#{pane_height}:#{scroll_position}:#{?pane_active,active,nope}",
];
let output = self
.executor
.execute(active_command.iter().map(|arg| arg.to_string()).collect());
let lines: Vec<&str> = output.split('\n').collect();
let chunks: Vec<Vec<&str>> = lines.into_iter().map(|line| line.split(':').collect()).collect();
let active_pane = chunks
.iter()
.find(|&chunks| *chunks.get(4).unwrap() == "active")
.expect("Unable to find active pane");
let pane_id = active_pane.get(0).unwrap();
let pane_in_copy_mode = active_pane.get(1).unwrap().to_string();
self.active_pane_id = Some(pane_id.to_string());
self.active_pane_in_copy_mode = Some(pane_in_copy_mode);
if self.active_pane_in_copy_mode.clone().unwrap() == "1" {
let pane_height = active_pane
.get(2)
.unwrap()
.parse()
.expect("Unable to retrieve pane height");
let pane_scroll_position = active_pane
.get(3)
.unwrap()
.parse()
.expect("Unable to retrieve pane scroll");
self.active_pane_height = Some(pane_height);
self.active_pane_scroll_position = Some(pane_scroll_position);
}
}
pub fn execute_thumbs(&mut self) {
let options_command = vec!["tmux", "show", "-g"];
let params: Vec<String> = options_command.iter().map(|arg| arg.to_string()).collect();
let options = self.executor.execute(params);
let lines: Vec<&str> = options.split('\n').collect();
let pattern = Regex::new(r#"@thumbs-([\w\-0-9]+) "?(\w+)"?"#).unwrap();
let args = lines
.iter()
.flat_map(|line| {
if let Some(captures) = pattern.captures(line) {
let name = captures.get(1).unwrap().as_str();
let value = captures.get(2).unwrap().as_str();
let boolean_params = vec!["reverse", "unique", "contrast"];
if boolean_params.iter().any(|&x| x == name) {
return vec![format!("--{}", name)];
}
let string_params = vec![
"position",
"fg-color",
"bg-color",
"hint-bg-color",
"hint-fg-color",
"select-fg-color",
"select-bg-color",
];
if string_params.iter().any(|&x| x == name) {
return vec![format!("--{}", name), format!("'{}'", value)];
}
if name.starts_with("regexp") {
return vec!["--regexp".to_string(), format!("'{}'", value)];
}
vec![]
} else {
vec![]
}
})
.collect::<Vec<String>>();
let active_pane_id = self.active_pane_id.as_mut().unwrap().clone();
let scroll_params = if self.active_pane_in_copy_mode.is_some() {
if let (Some(pane_height), Some(scroll_position)) =
(self.active_pane_scroll_position, self.active_pane_scroll_position)
{
format!(" -S {} -E {}", -scroll_position, pane_height - scroll_position - 1)
} else {
"".to_string()
}
} else {
"".to_string()
};
// NOTE: For debugging add echo $PWD && sleep 5 after tee
let pane_command = format!(
"tmux capture-pane -t {} -p{} | {}/target/release/thumbs -f '%U:%H' -t {} {}; tmux swap-pane -t {}; tmux wait-for -S {}",
active_pane_id,
scroll_params,
self.dir,
TMP_FILE,
args.join(" "),
active_pane_id,
self.signal
);
let thumbs_command = vec![
"tmux",
"new-window",
"-P",
"-d",
"-n",
"[thumbs]",
pane_command.as_str(),
];
let params: Vec<String> = thumbs_command.iter().map(|arg| arg.to_string()).collect();
self.thumbs_pane_id = Some(self.executor.execute(params));
}
pub fn swap_panes(&mut self) {
let active_pane_id = self.active_pane_id.as_mut().unwrap().clone();
let thumbs_pane_id = self.thumbs_pane_id.as_mut().unwrap().clone();
let swap_command = vec![
"tmux",
"swap-pane",
"-d",
"-s",
active_pane_id.as_str(),
"-t",
thumbs_pane_id.as_str(),
];
let params = swap_command.iter().map(|arg| arg.to_string()).collect();
self.executor.execute(params);
}
pub fn wait_thumbs(&mut self) {
let wait_command = vec!["tmux", "wait-for", self.signal.as_str()];
let params = wait_command.iter().map(|arg| arg.to_string()).collect();
self.executor.execute(params);
}
pub fn retrieve_content(&mut self) {
let retrieve_command = vec!["cat", TMP_FILE];
let params = retrieve_command.iter().map(|arg| arg.to_string()).collect();
self.content = Some(self.executor.execute(params));
}
pub fn destroy_content(&mut self) {
let retrieve_command = vec!["rm", TMP_FILE];
let params = retrieve_command.iter().map(|arg| arg.to_string()).collect();
self.executor.execute(params);
}
pub fn execute_command(&mut self) {
let content = self.content.clone().unwrap();
let mut splitter = content.splitn(2, ':');
if let Some(upcase) = splitter.next() {
if let Some(text) = splitter.next() {
let execute_command = if upcase.trim_end() == "true" {
self.upcase_command.clone()
} else {
self.command.clone()
};
let final_command = str::replace(execute_command.as_str(), "{}", text.trim_end());
let retrieve_command = vec!["bash", "-c", final_command.as_str()];
let params = retrieve_command.iter().map(|arg| arg.to_string()).collect();
self.executor.execute(params);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
struct TestShell {
outputs: Vec<String>,
executed: Option<Vec<String>>,
}
impl TestShell {
fn new(outputs: Vec<String>) -> TestShell {
TestShell {
executed: None,
outputs,
}
}
}
impl Executor for TestShell {
fn execute(&mut self, args: Vec<String>) -> String {
self.executed = Some(args);
self.outputs.pop().unwrap()
}
fn last_executed(&self) -> Option<Vec<String>> {
self.executed.clone()
}
}
#[test]
fn retrieve_active_pane() {
let last_command_outputs = vec!["%97:100:24:1:active\n%106:100:24:1:nope\n%107:100:24:1:nope\n".to_string()];
let mut executor = TestShell::new(last_command_outputs);
let mut swapper = Swapper::new(Box::new(&mut executor), "".to_string(), "".to_string(), "".to_string());
swapper.capture_active_pane();
assert_eq!(swapper.active_pane_id.unwrap(), "%97");
}
#[test]
fn swap_panes() {
let last_command_outputs = vec![
"".to_string(),
"%100".to_string(),
"".to_string(),
"%106:100:24:1:nope\n%98:100:24:1:active\n%107:100:24:1:nope\n".to_string(),
];
let mut executor = TestShell::new(last_command_outputs);
let mut swapper = Swapper::new(Box::new(&mut executor), "".to_string(), "".to_string(), "".to_string());
swapper.capture_active_pane();
swapper.execute_thumbs();
swapper.swap_panes();
let expectation = vec!["tmux", "swap-pane", "-d", "-s", "%98", "-t", "%100"];
assert_eq!(executor.last_executed().unwrap(), expectation);
}
}
fn app_args<'a>() -> clap::ArgMatches<'a> {
App::new("tmux-thumbs")
.version(crate_version!())
.about("A lightning fast version of tmux-fingers, copy/pasting tmux like vimium/vimperator")
.arg(
Arg::with_name("dir")
.help("Directory where to execute thumbs")
.long("dir")
.default_value(""),
)
.arg(
Arg::with_name("command")
.help("Pick command")
.long("command")
.default_value("tmux set-buffer {}"),
)
.arg(
Arg::with_name("upcase_command")
.help("Upcase command")
.long("upcase-command")
.default_value("tmux set-buffer {} && tmux paste-buffer"),
)
.get_matches()
}
fn main() -> std::io::Result<()> {
let args = app_args();
let dir = args.value_of("dir").unwrap();
let command = args.value_of("command").unwrap();
let upcase_command = args.value_of("upcase_command").unwrap();
if dir.is_empty() {
panic!("Invalid tmux-thumbs execution. Are you trying to execute tmux-thumbs directly?")
}
let mut executor = RealShell::new();
let mut swapper = Swapper::new(
Box::new(&mut executor),
dir.to_string(),
command.to_string(),
upcase_command.to_string(),
);
swapper.capture_active_pane();
swapper.execute_thumbs();
swapper.swap_panes();
swapper.wait_thumbs();
swapper.retrieve_content();
swapper.destroy_content();
swapper.execute_command();
Ok(())
}
| 27.677922 | 129 | 0.598067 |
0e8e87f2dff5c9512574cc8c5b192d882c5a6d58 | 705 | use crate::spec::TargetOptions;
pub fn opts() -> TargetOptions {
TargetOptions {
os: "vxworks".to_string(),
env: "gnu".to_string(),
vendor: "wrs".to_string(),
linker: Some("wr-c++".to_string()),
exe_suffix: ".vxe".to_string(),
dynamic_linking: true,
executables: true,
families: vec!["unix".to_string()],
linker_is_gnu: true,
has_rpath: true,
has_elf_tls: true,
crt_static_default: true,
crt_static_respected: true,
crt_static_allows_dylibs: true,
// VxWorks needs to implement this to support profiling
mcount: "_mcount".to_string(),
..Default::default()
}
}
| 29.375 | 63 | 0.585816 |
5b69248735f1e702b803e1e7ebc2783402d81087 | 2,355 | /*
* 给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
*
* 示例 1:
*
* 输入:
* [
* [ 1, 2, 3 ],
* [ 4, 5, 6 ],
* [ 7, 8, 9 ]
* ]
* 输出: [1,2,3,6,9,8,7,4,5]
* 示例 2:
*
* 输入:
* [
* [1, 2, 3, 4],
* [5, 6, 7, 8],
* [9,10,11,12]
* ]
* 输出: [1,2,3,4,8,12,11,10,9,5,6,7]
*/
struct Solution {}
impl Solution {
fn traverse_circle(
matrix: &Vec<Vec<i32>>,
i: usize,
j: usize,
m: usize,
n: usize,
output: &mut Vec<i32>,
) {
if m == 1 {
for v in 0..n {
output.push(matrix[i][j + v]);
}
return;
} else if n == 1 {
for v in (0..m) {
output.push(matrix[i + v][j]);
}
return;
}
let path_len = (m + n) * 2 - 4;
let dest_one = n;
let dest_two = m + n - 1;
let dest_thr = m + n * 2 - 2;
for d in 0..path_len {
let val: i32;
if d < dest_one {
val = matrix[i][j + d]
} else if d >= dest_one && d < dest_two {
val = matrix[i + d - dest_one + 1][j + n - 1];
} else if d >= dest_two && d < dest_thr {
val = matrix[i + m - 1][j + n - 1 - (d - dest_two + 1)];
} else if d >= dest_thr && d < path_len {
val = matrix[i + m - 1 - (d - dest_thr + 1)][j];
} else {
continue;
}
output.push(val);
}
if m > 2 && n > 2 {
Solution::traverse_circle(matrix, i + 1, j + 1, m - 2, n - 2, output);
}
}
pub fn spiral_order(matrix: Vec<Vec<i32>>) -> Vec<i32> {
let m = matrix.len();
if m == 0 {
return Vec::new();
}
let n = matrix[0].len();
let mut spiral_order_vec = Vec::with_capacity(m * n);
Solution::traverse_circle(&matrix, 0, 0, m, n, &mut spiral_order_vec);
spiral_order_vec
}
}
fn main() {
println!("0054: ");
//let input = vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]];
let input = vec![vec![1, 2], vec![4, 5], vec![7, 8]];
//let input = vec![vec![1], vec![4], vec![7]];
//let input = vec![vec![1, 2], vec![3, 4]];
let output = Solution::spiral_order(input);
println!("spriral-order: {:?}", output);
}
| 23.787879 | 82 | 0.407643 |
50c81596edffe9ac1145979f97804c934131c217 | 11,702 | // 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.
#![allow(non_camel_case_types)]
use middle::subst;
use middle::trans::adt;
use middle::trans::common::*;
use middle::trans::foreign;
use middle::ty;
use util::ppaux::Repr;
use middle::trans::type_::Type;
use syntax::abi;
use syntax::ast;
pub fn arg_is_indirect(ccx: &CrateContext, arg_ty: ty::t) -> bool {
!type_is_immediate(ccx, arg_ty)
}
pub fn return_uses_outptr(ccx: &CrateContext, ty: ty::t) -> bool {
!type_is_immediate(ccx, ty)
}
pub fn type_of_explicit_arg(ccx: &CrateContext, arg_ty: ty::t) -> Type {
let llty = arg_type_of(ccx, arg_ty);
if arg_is_indirect(ccx, arg_ty) {
llty.ptr_to()
} else {
llty
}
}
pub fn type_of_rust_fn(cx: &CrateContext, has_env: bool,
inputs: &[ty::t], output: ty::t) -> Type {
let mut atys: Vec<Type> = Vec::new();
// Arg 0: Output pointer.
// (if the output type is non-immediate)
let use_out_pointer = return_uses_outptr(cx, output);
let lloutputtype = arg_type_of(cx, output);
if use_out_pointer {
atys.push(lloutputtype.ptr_to());
}
// Arg 1: Environment
if has_env {
atys.push(Type::i8p(cx));
}
// ... then explicit args.
let input_tys = inputs.iter().map(|&arg_ty| type_of_explicit_arg(cx, arg_ty));
atys.extend(input_tys);
// Use the output as the actual return value if it's immediate.
if use_out_pointer || return_type_is_void(cx, output) {
Type::func(atys.as_slice(), &Type::void(cx))
} else {
Type::func(atys.as_slice(), &lloutputtype)
}
}
// Given a function type and a count of ty params, construct an llvm type
pub fn type_of_fn_from_ty(cx: &CrateContext, fty: ty::t) -> Type {
match ty::get(fty).sty {
ty::ty_closure(ref f) => {
type_of_rust_fn(cx, true, f.sig.inputs.as_slice(), f.sig.output)
}
ty::ty_bare_fn(ref f) => {
if f.abi == abi::Rust || f.abi == abi::RustIntrinsic {
type_of_rust_fn(cx,
false,
f.sig.inputs.as_slice(),
f.sig.output)
} else {
foreign::lltype_for_foreign_fn(cx, fty)
}
}
_ => {
cx.sess().bug("type_of_fn_from_ty given non-closure, non-bare-fn")
}
}
}
// A "sizing type" is an LLVM type, the size and alignment of which are
// guaranteed to be equivalent to what you would get out of `type_of()`. It's
// useful because:
//
// (1) It may be cheaper to compute the sizing type than the full type if all
// you're interested in is the size and/or alignment;
//
// (2) It won't make any recursive calls to determine the structure of the
// type behind pointers. This can help prevent infinite loops for
// recursive types. For example, enum types rely on this behavior.
pub fn sizing_type_of(cx: &CrateContext, t: ty::t) -> Type {
match cx.llsizingtypes.borrow().find_copy(&t) {
Some(t) => return t,
None => ()
}
let llsizingty = match ty::get(t).sty {
ty::ty_nil | ty::ty_bot => Type::nil(cx),
ty::ty_bool => Type::bool(cx),
ty::ty_char => Type::char(cx),
ty::ty_int(t) => Type::int_from_ty(cx, t),
ty::ty_uint(t) => Type::uint_from_ty(cx, t),
ty::ty_float(t) => Type::float_from_ty(cx, t),
ty::ty_box(..) |
ty::ty_ptr(..) => Type::i8p(cx),
ty::ty_uniq(ty) => {
match ty::get(ty).sty {
ty::ty_trait(..) => Type::opaque_trait(cx),
_ => Type::i8p(cx),
}
}
ty::ty_rptr(_, mt) => {
match ty::get(mt.ty).sty {
ty::ty_vec(_, None) | ty::ty_str => {
Type::struct_(cx, [Type::i8p(cx), Type::i8p(cx)], false)
}
ty::ty_trait(..) => Type::opaque_trait(cx),
_ => Type::i8p(cx),
}
}
ty::ty_bare_fn(..) => Type::i8p(cx),
ty::ty_closure(..) => Type::struct_(cx, [Type::i8p(cx), Type::i8p(cx)], false),
ty::ty_vec(mt, Some(size)) => {
Type::array(&sizing_type_of(cx, mt.ty), size as u64)
}
ty::ty_tup(..) | ty::ty_enum(..) => {
let repr = adt::represent_type(cx, t);
adt::sizing_type_of(cx, &*repr)
}
ty::ty_struct(..) => {
if ty::type_is_simd(cx.tcx(), t) {
let et = ty::simd_type(cx.tcx(), t);
let n = ty::simd_size(cx.tcx(), t);
Type::vector(&type_of(cx, et), n as u64)
} else {
let repr = adt::represent_type(cx, t);
adt::sizing_type_of(cx, &*repr)
}
}
ty::ty_infer(..) | ty::ty_param(..) |
ty::ty_err(..) | ty::ty_vec(_, None) | ty::ty_str | ty::ty_trait(..) => {
cx.sess().bug(format!("fictitious type {:?} in sizing_type_of()",
ty::get(t).sty).as_slice())
}
};
cx.llsizingtypes.borrow_mut().insert(t, llsizingty);
llsizingty
}
pub fn arg_type_of(cx: &CrateContext, t: ty::t) -> Type {
if ty::type_is_bool(t) {
Type::i1(cx)
} else {
type_of(cx, t)
}
}
// NB: If you update this, be sure to update `sizing_type_of()` as well.
pub fn type_of(cx: &CrateContext, t: ty::t) -> Type {
// Check the cache.
match cx.lltypes.borrow().find(&t) {
Some(&llty) => return llty,
None => ()
}
debug!("type_of {} {:?}", t.repr(cx.tcx()), t);
// Replace any typedef'd types with their equivalent non-typedef
// type. This ensures that all LLVM nominal types that contain
// Rust types are defined as the same LLVM types. If we don't do
// this then, e.g. `Option<{myfield: bool}>` would be a different
// type than `Option<myrec>`.
let t_norm = ty::normalize_ty(cx.tcx(), t);
if t != t_norm {
let llty = type_of(cx, t_norm);
debug!("--> normalized {} {:?} to {} {:?} llty={}",
t.repr(cx.tcx()),
t,
t_norm.repr(cx.tcx()),
t_norm,
cx.tn.type_to_string(llty));
cx.lltypes.borrow_mut().insert(t, llty);
return llty;
}
let mut llty = match ty::get(t).sty {
ty::ty_nil | ty::ty_bot => Type::nil(cx),
ty::ty_bool => Type::bool(cx),
ty::ty_char => Type::char(cx),
ty::ty_int(t) => Type::int_from_ty(cx, t),
ty::ty_uint(t) => Type::uint_from_ty(cx, t),
ty::ty_float(t) => Type::float_from_ty(cx, t),
ty::ty_enum(did, ref substs) => {
// Only create the named struct, but don't fill it in. We
// fill it in *after* placing it into the type cache. This
// avoids creating more than one copy of the enum when one
// of the enum's variants refers to the enum itself.
let repr = adt::represent_type(cx, t);
let tps = substs.types.get_slice(subst::TypeSpace);
let name = llvm_type_name(cx, an_enum, did, tps);
adt::incomplete_type_of(cx, &*repr, name.as_slice())
}
ty::ty_box(typ) => {
Type::at_box(cx, type_of(cx, typ)).ptr_to()
}
ty::ty_uniq(typ) => {
match ty::get(typ).sty {
ty::ty_vec(mt, None) => Type::vec(cx, &type_of(cx, mt.ty)).ptr_to(),
ty::ty_str => Type::vec(cx, &Type::i8(cx)).ptr_to(),
ty::ty_trait(..) => Type::opaque_trait(cx),
_ => type_of(cx, typ).ptr_to(),
}
}
ty::ty_ptr(ref mt) => type_of(cx, mt.ty).ptr_to(),
ty::ty_rptr(_, ref mt) => {
match ty::get(mt.ty).sty {
ty::ty_vec(mt, None) => {
let p_ty = type_of(cx, mt.ty).ptr_to();
let u_ty = Type::uint_from_ty(cx, ast::TyU);
Type::struct_(cx, [p_ty, u_ty], false)
}
ty::ty_str => {
// This means we get a nicer name in the output
cx.tn.find_type("str_slice").unwrap()
}
ty::ty_trait(..) => Type::opaque_trait(cx),
_ => type_of(cx, mt.ty).ptr_to(),
}
}
ty::ty_vec(ref mt, Some(n)) => {
Type::array(&type_of(cx, mt.ty), n as u64)
}
ty::ty_bare_fn(_) => {
type_of_fn_from_ty(cx, t).ptr_to()
}
ty::ty_closure(_) => {
let fn_ty = type_of_fn_from_ty(cx, t).ptr_to();
Type::struct_(cx, [fn_ty, Type::i8p(cx)], false)
}
ty::ty_tup(..) => {
let repr = adt::represent_type(cx, t);
adt::type_of(cx, &*repr)
}
ty::ty_struct(did, ref substs) => {
if ty::type_is_simd(cx.tcx(), t) {
let et = ty::simd_type(cx.tcx(), t);
let n = ty::simd_size(cx.tcx(), t);
Type::vector(&type_of(cx, et), n as u64)
} else {
// Only create the named struct, but don't fill it in. We fill it
// in *after* placing it into the type cache. This prevents
// infinite recursion with recursive struct types.
let repr = adt::represent_type(cx, t);
let tps = substs.types.get_slice(subst::TypeSpace);
let name = llvm_type_name(cx, a_struct, did, tps);
adt::incomplete_type_of(cx, &*repr, name.as_slice())
}
}
ty::ty_vec(_, None) => cx.sess().bug("type_of with unsized ty_vec"),
ty::ty_str => cx.sess().bug("type_of with unsized (bare) ty_str"),
ty::ty_trait(..) => cx.sess().bug("type_of with unsized ty_trait"),
ty::ty_infer(..) => cx.sess().bug("type_of with ty_infer"),
ty::ty_param(..) => cx.sess().bug("type_of with ty_param"),
ty::ty_err(..) => cx.sess().bug("type_of with ty_err")
};
debug!("--> mapped t={} {:?} to llty={}",
t.repr(cx.tcx()),
t,
cx.tn.type_to_string(llty));
cx.lltypes.borrow_mut().insert(t, llty);
// If this was an enum or struct, fill in the type now.
match ty::get(t).sty {
ty::ty_enum(..) | ty::ty_struct(..) if !ty::type_is_simd(cx.tcx(), t) => {
let repr = adt::represent_type(cx, t);
adt::finish_type_of(cx, &*repr, &mut llty);
}
_ => ()
}
return llty;
}
// Want refinements! (Or case classes, I guess
pub enum named_ty { a_struct, an_enum }
pub fn llvm_type_name(cx: &CrateContext,
what: named_ty,
did: ast::DefId,
tps: &[ty::t])
-> String
{
let name = match what {
a_struct => { "struct" }
an_enum => { "enum" }
};
let base = ty::item_path_str(cx.tcx(), did);
let strings: Vec<String> = tps.iter().map(|t| t.repr(cx.tcx())).collect();
let tstr = format!("{}<{}>", base, strings);
if did.krate == 0 {
format!("{}.{}", name, tstr)
} else {
format!("{}.{}[{}{}]", name, tstr, "#", did.krate)
}
}
pub fn type_of_dtor(ccx: &CrateContext, self_ty: ty::t) -> Type {
let self_ty = type_of(ccx, self_ty).ptr_to();
Type::func([self_ty], &Type::void(ccx))
}
| 34.621302 | 87 | 0.532302 |
9c046a6d18b17b5d86aa84825bc093035a75196a | 5,135 | use super::*;
use crate as mining;
use crate::{Config, Module};
use frame_support::pallet_prelude::{GenesisBuild, Hooks, MaybeSerializeDeserialize};
use frame_support::sp_runtime::traits::AtLeast32Bit;
use frame_support::{construct_runtime, ord_parameter_types, parameter_types, traits::EnsureOrigin, weights::Weight};
use frame_system::{EnsureRoot, EnsureSignedBy};
use orml_traits::parameter_type_with_key;
use primitives::FungibleTokenId::FungibleToken;
use primitives::{Amount, CurrencyId, FungibleTokenId};
use sp_core::H256;
use sp_runtime::{
testing::Header,
traits::{AccountIdConversion, IdentityLookup},
Perbill,
};
pub type AccountId = u128;
pub type AuctionId = u64;
pub type Balance = u128;
pub type MetaverseId = u64;
pub type BlockNumber = u64;
pub const ALICE: AccountId = 1;
pub const BOB: AccountId = 5;
pub const METAVERSE_ID: MetaverseId = 1;
pub const COUNTRY_ID_NOT_EXIST: MetaverseId = 1;
pub const NUUM: CurrencyId = 0;
pub const COUNTRY_FUND: FungibleTokenId = FungibleTokenId::FungibleToken(1);
ord_parameter_types! {
pub const One: AccountId = ALICE;
}
// Configure a mock runtime to test the pallet.
parameter_types! {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: u32 = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::one();
}
impl frame_system::Config for Runtime {
type Origin = Origin;
type Index = u64;
type BlockNumber = BlockNumber;
type Call = Call;
type Hash = H256;
type Hashing = ::sp_runtime::traits::BlakeTwo256;
type AccountId = AccountId;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = Event;
type BlockHashCount = BlockHashCount;
type BlockWeights = ();
type BlockLength = ();
type Version = ();
type PalletInfo = PalletInfo;
type AccountData = pallet_balances::AccountData<Balance>;
type OnNewAccount = ();
type OnKilledAccount = ();
type DbWeight = ();
type BaseCallFilter = ();
type SystemWeightInfo = ();
type SS58Prefix = ();
type OnSetCode = ();
}
parameter_types! {
pub const ExistentialDeposit: u64 = 1;
}
impl pallet_balances::Config for Runtime {
type Balance = Balance;
type Event = Event;
type DustRemoval = ();
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System;
type MaxLocks = ();
type WeightInfo = ();
type MaxReserves = ();
type ReserveIdentifier = ();
}
parameter_type_with_key! {
pub ExistentialDeposits: |_currency_id: FungibleTokenId| -> Balance {
Default::default()
};
}
parameter_types! {
pub const MetaverseTreasuryPalletId: PalletId = PalletId(*b"bit/trsy");
pub TreasuryModuleAccount: AccountId = MetaverseTreasuryPalletId::get().into_account();
pub const MiningTreasuryPalletId: PalletId = PalletId(*b"bit/fund");
}
impl orml_tokens::Config for Runtime {
type Event = Event;
type Balance = Balance;
type Amount = Amount;
type CurrencyId = FungibleTokenId;
type WeightInfo = ();
type ExistentialDeposits = ExistentialDeposits;
type OnDust = orml_tokens::TransferDust<Runtime, TreasuryModuleAccount>;
type MaxLocks = ();
type DustRemovalWhitelist = ();
}
pub type AdaptedBasicCurrency = currencies::BasicCurrencyAdapter<Runtime, Balances, Amount, BlockNumber>;
parameter_types! {
pub const GetNativeCurrencyId: FungibleTokenId = FungibleTokenId::NativeToken(0);
pub const MiningCurrencyId: FungibleTokenId = FungibleTokenId::MiningResource(0);
}
impl currencies::Config for Runtime {
type Event = Event;
type MultiSocialCurrency = Tokens;
type NativeCurrency = AdaptedBasicCurrency;
type GetNativeCurrencyId = GetNativeCurrencyId;
}
parameter_types! {
pub const MinVestedTransfer: Balance = 100;
}
impl Config for Runtime {
type Event = Event;
type MiningCurrency = Currencies;
type BitMiningTreasury = MiningTreasuryPalletId;
type BitMiningResourceId = MiningCurrencyId;
type AdminOrigin = EnsureSignedBy<One, AccountId>;
}
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Runtime>;
type Block = frame_system::mocking::MockBlock<Runtime>;
construct_runtime!(
pub enum Runtime where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic
{
System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
Currencies: currencies::{ Pallet, Storage, Call, Event<T>},
Tokens: orml_tokens::{ Pallet, Storage, Call, Event<T>},
MiningModule: mining:: {Pallet, Call, Storage, Event<T>},
}
);
pub struct ExtBuilder;
impl Default for ExtBuilder {
fn default() -> Self {
ExtBuilder
}
}
impl ExtBuilder {
pub fn build(self) -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::default()
.build_storage::<Runtime>()
.unwrap();
pallet_balances::GenesisConfig::<Runtime> {
balances: vec![(ALICE, 100000)],
}
.assimilate_storage(&mut t)
.unwrap();
let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(|| System::set_block_number(1));
ext
}
}
pub fn last_event() -> Event {
frame_system::Module::<Runtime>::events()
.pop()
.expect("Event expected")
.event
}
| 28.060109 | 116 | 0.744693 |
de52674cd1d3a291b7e87c8713f460c6d5b8cd3c | 2,409 | //! Database-related functions
use crate::config::{IConfig, CONFIG};
use actix_web::web;
use diesel::{
mysql::MysqlConnection,
pg::PgConnection,
r2d2::{ConnectionManager, PoolError},
sqlite::SqliteConnection,
Connection,
};
#[serde(untagged)]
#[derive(Clone, Deserialize, Debug, PartialEq)]
#[serde(field_identifier, rename_all = "lowercase")]
pub enum DatabaseConnection {
Cockroach,
Mysql,
Postgres,
Sqlite,
}
pub type Pool<T> = r2d2::Pool<ConnectionManager<T>>;
pub type CockroachPool = Pool<PgConnection>;
pub type MysqlPool = Pool<MysqlConnection>;
pub type PostgresPool = Pool<PgConnection>;
pub type SqlitePool = Pool<SqliteConnection>;
#[cfg(feature = "cockraoch")]
pub type PoolType = CockroachPool;
#[cfg(feature = "mysql")]
pub type PoolType = MysqlPool;
#[cfg(feature = "postgres")]
pub type PoolType = PostgresPool;
#[cfg(feature = "sqlite")]
pub type PoolType = SqlitePool;
#[derive(Clone)]
pub enum InferPool {
Cockroach(CockroachPool),
Mysql(MysqlPool),
Postgres(PostgresPool),
Sqlite(SqlitePool),
}
impl InferPool {
pub fn init_pool(config: IConfig) -> Result<Self, r2d2::Error> {
match config.database.driver {
DatabaseConnection::Cockroach => {
init_pool::<PgConnection>(config).map(InferPool::Cockroach)
}
DatabaseConnection::Mysql => init_pool::<MysqlConnection>(config).map(InferPool::Mysql),
DatabaseConnection::Postgres => {
init_pool::<PgConnection>(config).map(InferPool::Postgres)
}
DatabaseConnection::Sqlite => {
init_pool::<SqliteConnection>(config).map(InferPool::Sqlite)
}
}
.map_err(Into::into)
}
}
pub fn init_pool<T>(config: IConfig) -> Result<Pool<T>, PoolError>
where
T: Connection + 'static,
{
let manager = ConnectionManager::<T>::new(config.database.url);
Pool::builder().build(manager)
}
pub fn add_pool(cfg: &mut web::ServiceConfig) {
let pool = InferPool::init_pool(CONFIG.clone()).expect("Failed to create connection pool");
match pool {
InferPool::Cockroach(cockroach_pool) => cfg.data(cockroach_pool),
InferPool::Mysql(mysql_pool) => cfg.data(mysql_pool),
InferPool::Postgres(postgres_pool) => cfg.data(postgres_pool),
InferPool::Sqlite(sqlite_pool) => cfg.data(sqlite_pool),
};
}
| 29.024096 | 100 | 0.663346 |
03df4d59ba91fffd8a9a7f38c32da7a31ef374ee | 1,589 | // Copyright 2020 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
use crate::constants::algorithm::HashingAlgorithm;
use crate::structures::Digest;
use crate::tss2_esys::{TPMT_HA, TPMU_HA};
use crate::{Error, Result, WrapperErrorKind};
use std::convert::{TryFrom, TryInto};
#[derive(Debug)]
pub struct HashAgile {
algorithm: HashingAlgorithm,
digest: Digest,
}
impl HashAgile {
pub fn new(algorithm: HashingAlgorithm, digest: Digest) -> Self {
HashAgile { algorithm, digest }
}
}
impl TryFrom<HashAgile> for TPMT_HA {
type Error = Error;
fn try_from(ha: HashAgile) -> Result<Self> {
let algid: crate::tss2_esys::TPM2_ALG_ID = ha.algorithm.into();
let digest_val = ha.digest;
Ok(TPMT_HA {
hashAlg: algid,
digest: match ha.algorithm {
HashingAlgorithm::Sha1 => TPMU_HA {
sha1: digest_val.try_into()?,
},
HashingAlgorithm::Sha256 => TPMU_HA {
sha256: digest_val.try_into()?,
},
HashingAlgorithm::Sha384 => TPMU_HA {
sha384: digest_val.try_into()?,
},
HashingAlgorithm::Sha512 => TPMU_HA {
sha512: digest_val.try_into()?,
},
HashingAlgorithm::Sm3_256 => TPMU_HA {
sm3_256: digest_val.try_into()?,
},
_ => return Err(Error::local_error(WrapperErrorKind::UnsupportedParam)),
},
})
}
}
| 32.428571 | 88 | 0.56073 |
0e65a42a1704a29463191dcf796c12398e02964b | 4,730 | //! A simple filterer in the style of the watchexec v1 filter.
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use ignore::gitignore::{Gitignore, GitignoreBuilder};
use tracing::{debug, trace, trace_span};
use crate::error::RuntimeError;
use crate::event::{Event, FileType};
use crate::filter::Filterer;
use crate::ignore::{IgnoreFile, IgnoreFilterer};
/// A path-only filterer based on globsets.
///
/// This filterer mimics the behavior of the `watchexec` v1 filter, but does not match it exactly,
/// due to differing internals. It is intended to be used as a stopgap until the tagged filterer
/// or another advanced filterer, reaches a stable state or becomes the default. As such it does not
/// have an updatable configuration.
#[derive(Debug)]
pub struct GlobsetFilterer {
filters: Gitignore,
ignores: Gitignore,
ignore_files: IgnoreFilterer,
extensions: Vec<OsString>,
}
impl GlobsetFilterer {
/// Create a new `GlobsetFilterer` from a project origin, allowed extensions, and lists of globs.
///
/// The first list is used to filter paths (only matching paths will pass the filter), the
/// second is used to ignore paths (matching paths will fail the pattern). If the filter list is
/// empty, only the ignore list will be used. If both lists are empty, the filter always passes.
///
/// The extensions list is used to filter files by extension.
///
/// Non-path events are always passed.
pub async fn new(
origin: impl AsRef<Path>,
filters: impl IntoIterator<Item = (String, Option<PathBuf>)>,
ignores: impl IntoIterator<Item = (String, Option<PathBuf>)>,
ignore_files: impl IntoIterator<Item = IgnoreFile>,
extensions: impl IntoIterator<Item = OsString>,
) -> Result<Self, RuntimeError> {
let origin = origin.as_ref();
let mut filters_builder = GitignoreBuilder::new(&origin);
let mut ignores_builder = GitignoreBuilder::new(&origin);
for (filter, in_path) in filters {
trace!(filter=?&filter, "add filter to globset filterer");
filters_builder
.add_line(in_path.clone(), &filter)
.map_err(|err| RuntimeError::GlobsetGlob { file: in_path, err })?;
}
for (ignore, in_path) in ignores {
trace!(ignore=?&ignore, "add ignore to globset filterer");
ignores_builder
.add_line(in_path.clone(), &ignore)
.map_err(|err| RuntimeError::GlobsetGlob { file: in_path, err })?;
}
let filters = filters_builder
.build()
.map_err(|err| RuntimeError::GlobsetGlob { file: None, err })?;
let ignores = ignores_builder
.build()
.map_err(|err| RuntimeError::GlobsetGlob { file: None, err })?;
let extensions: Vec<OsString> = extensions.into_iter().collect();
let mut ignore_files =
IgnoreFilterer::new(origin, &ignore_files.into_iter().collect::<Vec<_>>()).await?;
ignore_files.finish();
debug!(
num_filters=%filters.num_ignores(),
num_neg_filters=%filters.num_whitelists(),
num_ignores=%ignores.num_ignores(),
num_in_ignore_files=?ignore_files.num_ignores(),
num_neg_ignores=%ignores.num_whitelists(),
num_extensions=%extensions.len(),
"globset filterer built");
Ok(Self {
filters,
ignores,
ignore_files,
extensions,
})
}
}
impl Filterer for GlobsetFilterer {
/// Filter an event.
///
/// This implementation never errors.
fn check_event(&self, event: &Event) -> Result<bool, RuntimeError> {
let _span = trace_span!("filterer_check").entered();
{
trace!("checking internal ignore filterer");
if !self
.ignore_files
.check_event(event)
.expect("IgnoreFilterer never errors")
{
trace!("internal ignore filterer matched (fail)");
return Ok(false);
}
}
let mut paths = event.paths().peekable();
if paths.peek().is_none() {
trace!("non-path event (pass)");
Ok(true)
} else {
Ok(paths.any(|(path, file_type)| {
let _span = trace_span!("path", ?path).entered();
let is_dir = file_type
.map(|t| matches!(t, FileType::Dir))
.unwrap_or(false);
if self.ignores.matched(path, is_dir).is_ignore() {
trace!("ignored by globset ignore");
return false;
}
if self.filters.num_ignores() > 0 && !self.filters.matched(path, is_dir).is_ignore()
{
trace!("ignored by globset filters");
return false;
}
if !self.extensions.is_empty() {
if is_dir {
trace!("failed on extension check due to being a dir");
return false;
}
if let Some(ext) = path.extension() {
if !self.extensions.iter().any(|e| e == ext) {
trace!("ignored by extension filter");
return false;
}
} else {
trace!(
?path,
"failed on extension check due to having no extension"
);
return false;
}
}
true
}))
}
}
}
| 29.5625 | 100 | 0.67463 |
3832faadc9c29e0475c2ca16afe4c1ca7ee125e6 | 17,271 | // Generated from definition io.k8s.api.batch.v1.JobSpec
/// JobSpec describes how the job execution will look like.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct JobSpec {
/// Specifies the duration in seconds relative to the startTime that the job may be active before the system tries to terminate it; value must be positive integer
pub active_deadline_seconds: Option<i64>,
/// Specifies the number of retries before marking this job failed. Defaults to 6
pub backoff_limit: Option<i32>,
/// Specifies the desired number of successfully finished pods the job should be run with. Setting to nil means that the success of any pod signals the success of all pods, and allows parallelism to have any positive value. Setting to 1 means that parallelism is limited to 1 and the success of that pod signals the success of the job. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/
pub completions: Option<i32>,
/// manualSelector controls generation of pod labels and pod selectors. Leave `manualSelector` unset unless you are certain what you are doing. When false or unset, the system pick labels unique to this job and appends those labels to the pod template. When true, the user is responsible for picking unique labels and specifying the selector. Failure to pick a unique label may cause this and other jobs to not function correctly. However, You may see `manualSelector=true` in jobs that were created with the old `extensions/v1beta1` API. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/#specifying-your-own-pod-selector
pub manual_selector: Option<bool>,
/// Specifies the maximum desired number of pods the job should run at any given time. The actual number of pods running in steady state will be less than this number when ((.spec.completions - .status.successful) \< .spec.parallelism), i.e. when the work left to do is less than max parallelism. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/
pub parallelism: Option<i32>,
/// A label query over pods that should match the pod count. Normally, the system sets this field for you. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors
pub selector: Option<crate::apimachinery::pkg::apis::meta::v1::LabelSelector>,
/// Describes the pod that will be created when executing a job. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/
pub template: crate::api::core::v1::PodTemplateSpec,
}
impl<'de> crate::serde::Deserialize<'de> for JobSpec {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: crate::serde::Deserializer<'de> {
#[allow(non_camel_case_types)]
enum Field {
Key_active_deadline_seconds,
Key_backoff_limit,
Key_completions,
Key_manual_selector,
Key_parallelism,
Key_selector,
Key_template,
Other,
}
impl<'de> crate::serde::Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: crate::serde::Deserializer<'de> {
struct Visitor;
impl<'de> crate::serde::de::Visitor<'de> for Visitor {
type Value = Field;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("field identifier")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: crate::serde::de::Error {
Ok(match v {
"activeDeadlineSeconds" => Field::Key_active_deadline_seconds,
"backoffLimit" => Field::Key_backoff_limit,
"completions" => Field::Key_completions,
"manualSelector" => Field::Key_manual_selector,
"parallelism" => Field::Key_parallelism,
"selector" => Field::Key_selector,
"template" => Field::Key_template,
_ => Field::Other,
})
}
}
deserializer.deserialize_identifier(Visitor)
}
}
struct Visitor;
impl<'de> crate::serde::de::Visitor<'de> for Visitor {
type Value = JobSpec;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("JobSpec")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: crate::serde::de::MapAccess<'de> {
let mut value_active_deadline_seconds: Option<i64> = None;
let mut value_backoff_limit: Option<i32> = None;
let mut value_completions: Option<i32> = None;
let mut value_manual_selector: Option<bool> = None;
let mut value_parallelism: Option<i32> = None;
let mut value_selector: Option<crate::apimachinery::pkg::apis::meta::v1::LabelSelector> = None;
let mut value_template: Option<crate::api::core::v1::PodTemplateSpec> = None;
while let Some(key) = crate::serde::de::MapAccess::next_key::<Field>(&mut map)? {
match key {
Field::Key_active_deadline_seconds => value_active_deadline_seconds = crate::serde::de::MapAccess::next_value(&mut map)?,
Field::Key_backoff_limit => value_backoff_limit = crate::serde::de::MapAccess::next_value(&mut map)?,
Field::Key_completions => value_completions = crate::serde::de::MapAccess::next_value(&mut map)?,
Field::Key_manual_selector => value_manual_selector = crate::serde::de::MapAccess::next_value(&mut map)?,
Field::Key_parallelism => value_parallelism = crate::serde::de::MapAccess::next_value(&mut map)?,
Field::Key_selector => value_selector = crate::serde::de::MapAccess::next_value(&mut map)?,
Field::Key_template => value_template = Some(crate::serde::de::MapAccess::next_value(&mut map)?),
Field::Other => { let _: crate::serde::de::IgnoredAny = crate::serde::de::MapAccess::next_value(&mut map)?; },
}
}
Ok(JobSpec {
active_deadline_seconds: value_active_deadline_seconds,
backoff_limit: value_backoff_limit,
completions: value_completions,
manual_selector: value_manual_selector,
parallelism: value_parallelism,
selector: value_selector,
template: value_template.ok_or_else(|| crate::serde::de::Error::missing_field("template"))?,
})
}
}
deserializer.deserialize_struct(
"JobSpec",
&[
"activeDeadlineSeconds",
"backoffLimit",
"completions",
"manualSelector",
"parallelism",
"selector",
"template",
],
Visitor,
)
}
}
impl crate::serde::Serialize for JobSpec {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: crate::serde::Serializer {
let mut state = serializer.serialize_struct(
"JobSpec",
1 +
self.active_deadline_seconds.as_ref().map_or(0, |_| 1) +
self.backoff_limit.as_ref().map_or(0, |_| 1) +
self.completions.as_ref().map_or(0, |_| 1) +
self.manual_selector.as_ref().map_or(0, |_| 1) +
self.parallelism.as_ref().map_or(0, |_| 1) +
self.selector.as_ref().map_or(0, |_| 1),
)?;
if let Some(value) = &self.active_deadline_seconds {
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "activeDeadlineSeconds", value)?;
}
if let Some(value) = &self.backoff_limit {
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "backoffLimit", value)?;
}
if let Some(value) = &self.completions {
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "completions", value)?;
}
if let Some(value) = &self.manual_selector {
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "manualSelector", value)?;
}
if let Some(value) = &self.parallelism {
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "parallelism", value)?;
}
if let Some(value) = &self.selector {
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "selector", value)?;
}
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "template", &self.template)?;
crate::serde::ser::SerializeStruct::end(state)
}
}
#[cfg(feature = "schemars")]
impl crate::schemars::JsonSchema for JobSpec {
fn schema_name() -> String {
"io.k8s.api.batch.v1.JobSpec".to_owned()
}
fn json_schema(__gen: &mut crate::schemars::gen::SchemaGenerator) -> crate::schemars::schema::Schema {
crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
metadata: Some(Box::new(crate::schemars::schema::Metadata {
description: Some("JobSpec describes how the job execution will look like.".to_owned()),
..Default::default()
})),
instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::Object))),
object: Some(Box::new(crate::schemars::schema::ObjectValidation {
properties: std::array::IntoIter::new([
(
"activeDeadlineSeconds".to_owned(),
crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
metadata: Some(Box::new(crate::schemars::schema::Metadata {
description: Some("Specifies the duration in seconds relative to the startTime that the job may be active before the system tries to terminate it; value must be positive integer".to_owned()),
..Default::default()
})),
instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::Integer))),
format: Some("int64".to_owned()),
..Default::default()
}),
),
(
"backoffLimit".to_owned(),
crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
metadata: Some(Box::new(crate::schemars::schema::Metadata {
description: Some("Specifies the number of retries before marking this job failed. Defaults to 6".to_owned()),
..Default::default()
})),
instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::Integer))),
format: Some("int32".to_owned()),
..Default::default()
}),
),
(
"completions".to_owned(),
crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
metadata: Some(Box::new(crate::schemars::schema::Metadata {
description: Some("Specifies the desired number of successfully finished pods the job should be run with. Setting to nil means that the success of any pod signals the success of all pods, and allows parallelism to have any positive value. Setting to 1 means that parallelism is limited to 1 and the success of that pod signals the success of the job. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/".to_owned()),
..Default::default()
})),
instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::Integer))),
format: Some("int32".to_owned()),
..Default::default()
}),
),
(
"manualSelector".to_owned(),
crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
metadata: Some(Box::new(crate::schemars::schema::Metadata {
description: Some("manualSelector controls generation of pod labels and pod selectors. Leave `manualSelector` unset unless you are certain what you are doing. When false or unset, the system pick labels unique to this job and appends those labels to the pod template. When true, the user is responsible for picking unique labels and specifying the selector. Failure to pick a unique label may cause this and other jobs to not function correctly. However, You may see `manualSelector=true` in jobs that were created with the old `extensions/v1beta1` API. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/#specifying-your-own-pod-selector".to_owned()),
..Default::default()
})),
instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::Boolean))),
..Default::default()
}),
),
(
"parallelism".to_owned(),
crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
metadata: Some(Box::new(crate::schemars::schema::Metadata {
description: Some("Specifies the maximum desired number of pods the job should run at any given time. The actual number of pods running in steady state will be less than this number when ((.spec.completions - .status.successful) < .spec.parallelism), i.e. when the work left to do is less than max parallelism. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/".to_owned()),
..Default::default()
})),
instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::Integer))),
format: Some("int32".to_owned()),
..Default::default()
}),
),
(
"selector".to_owned(),
{
let mut schema_obj = __gen.subschema_for::<crate::apimachinery::pkg::apis::meta::v1::LabelSelector>().into_object();
schema_obj.metadata = Some(Box::new(crate::schemars::schema::Metadata {
description: Some("A label query over pods that should match the pod count. Normally, the system sets this field for you. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors".to_owned()),
..Default::default()
}));
crate::schemars::schema::Schema::Object(schema_obj)
},
),
(
"template".to_owned(),
{
let mut schema_obj = __gen.subschema_for::<crate::api::core::v1::PodTemplateSpec>().into_object();
schema_obj.metadata = Some(Box::new(crate::schemars::schema::Metadata {
description: Some("Describes the pod that will be created when executing a job. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/".to_owned()),
..Default::default()
}));
crate::schemars::schema::Schema::Object(schema_obj)
},
),
]).collect(),
required: std::array::IntoIter::new([
"template",
]).map(std::borrow::ToOwned::to_owned).collect(),
..Default::default()
})),
..Default::default()
})
}
}
| 63.730627 | 728 | 0.569625 |
5b8736e15f4eeb631656fea8d97fef00dde4e3e9 | 136 | use crate::Node;
/// Item iterated over using an iterator.
pub struct Item<'a, T> {
pub node: &'a Node<T>,
pub level: usize,
}
| 17 | 41 | 0.617647 |
72509d67c4b1f2b1e5316c24126dc97bdd507922 | 3,003 | use bevy::{asset::LoadState, prelude::*, sprite::TextureAtlasBuilder};
/// In this example we generate a new texture atlas (sprite sheet) from a folder containing
/// individual sprites
fn main() {
App::build()
.init_resource::<RpgSpriteHandles>()
.add_plugins(DefaultPlugins)
.add_state(AppState::Setup)
.add_system_set(SystemSet::on_enter(AppState::Setup).with_system(load_textures.system()))
.add_system_set(SystemSet::on_update(AppState::Setup).with_system(check_textures.system()))
.add_system_set(SystemSet::on_enter(AppState::Finished).with_system(setup.system()))
.run();
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum AppState {
Setup,
Finished,
}
#[derive(Default)]
struct RpgSpriteHandles {
handles: Vec<HandleUntyped>,
}
fn load_textures(mut rpg_sprite_handles: ResMut<RpgSpriteHandles>, asset_server: Res<AssetServer>) {
rpg_sprite_handles.handles = asset_server.load_folder("textures/rpg").unwrap();
}
fn check_textures(
mut state: ResMut<State<AppState>>,
rpg_sprite_handles: ResMut<RpgSpriteHandles>,
asset_server: Res<AssetServer>,
) {
if let LoadState::Loaded =
asset_server.get_group_load_state(rpg_sprite_handles.handles.iter().map(|handle| handle.id))
{
state.set(AppState::Finished).unwrap();
}
}
fn setup(
mut commands: Commands,
rpg_sprite_handles: Res<RpgSpriteHandles>,
asset_server: Res<AssetServer>,
mut texture_atlases: ResMut<Assets<TextureAtlas>>,
mut textures: ResMut<Assets<Texture>>,
mut materials: ResMut<Assets<ColorMaterial>>,
) {
let mut texture_atlas_builder = TextureAtlasBuilder::default();
for handle in rpg_sprite_handles.handles.iter() {
let texture = textures.get(handle).unwrap();
texture_atlas_builder.add_texture(handle.clone_weak().typed::<Texture>(), texture);
}
let texture_atlas = texture_atlas_builder.finish(&mut textures).unwrap();
let texture_atlas_texture = texture_atlas.texture.clone();
let vendor_handle = asset_server.get_handle("textures/rpg/chars/vendor/generic-rpg-vendor.png");
let vendor_index = texture_atlas.get_texture_index(&vendor_handle).unwrap();
let atlas_handle = texture_atlases.add(texture_atlas);
// set up a scene to display our texture atlas
commands.spawn_bundle(OrthographicCameraBundle::new_2d());
// draw a sprite from the atlas
commands.spawn_bundle(SpriteSheetBundle {
transform: Transform {
translation: Vec3::new(150.0, 0.0, 0.0),
scale: Vec3::splat(4.0),
..Default::default()
},
sprite: TextureAtlasSprite::new(vendor_index as u32),
texture_atlas: atlas_handle,
..Default::default()
});
// draw the atlas itself
commands.spawn_bundle(SpriteBundle {
material: materials.add(texture_atlas_texture.into()),
transform: Transform::from_xyz(-300.0, 0.0, 0.0),
..Default::default()
});
}
| 36.180723 | 100 | 0.694972 |
9ce59acfd7f23e7f24f91b9565c1368c63d2e2a4 | 22,688 | use csml_engine::{
data::{RunRequest}, start_conversation, user_close_all_conversations,
Client, CsmlResult
};
use csml_interpreter::data::csml_bot::CsmlBot;
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
#[derive(Debug, serde::Deserialize)]
pub struct LimitPaginationQueryParams {
limit: Option<i64>,
pagination_key: Option<String>,
}
unsafe fn get_string(s: *mut c_char) -> String {
if s.is_null() {
return "".to_owned()
}
CString::from_raw(s)
.into_string()
.expect("into_string() call failed")
}
#[no_mangle]
pub unsafe extern "C" fn hello_csml(to: *const c_char) -> *mut c_char {
let c_str = CStr::from_ptr(to);
let recipient = match c_str.to_str() {
Ok(s) => s,
Err(_) => "you",
};
CString::new(format!("Hello from CSML: {}", recipient))
.unwrap()
.into_raw()
}
#[no_mangle]
pub unsafe extern "C" fn release_string(s: *mut c_char) {
if s.is_null() {
return;
}
CString::from_raw(s);
}
// #############################################################################
#[no_mangle]
pub unsafe extern "C" fn get_open_conversation(string: *mut c_char) -> *mut c_char {
let raw_client = get_string(string);
let client: Client = match serde_json::from_str(&raw_client) {
Ok(body) => body,
Err(_err) => {
return CString::new(format!("client bad format"))
.expect("Couldn't create string!")
.into_raw()
}
};
match csml_engine::get_open_conversation(&client) {
Ok(Some(conversation)) => {
let string = serde_json::json!(conversation).to_string();
CString::new(string)
.expect("Couldn't create string!")
.into_raw()
}
Ok(None) => {
CString::new(format!(""))
.expect("Couldn't create string!")
.into_raw()
}
Err(err) => {
CString::new(format!("{:?}", err))
.expect("Couldn't create string!")
.into_raw()
}
}
}
#[no_mangle]
pub unsafe extern "C" fn get_client_current_state(string: *mut c_char) -> *mut c_char {
let raw_client = get_string(string);
let client: Client = match serde_json::from_str(&raw_client) {
Ok(body) => body,
Err(_err) => {
return CString::new(format!("client bad format"))
.expect("Couldn't create string!")
.into_raw()
}
};
match csml_engine::get_current_state(&client) {
Ok(Some(conversation)) => {
let string = serde_json::json!(conversation).to_string();
CString::new(string)
.expect("Couldn't create string!")
.into_raw()
}
Ok(None) => {
CString::new(format!(""))
.expect("Couldn't create string!")
.into_raw()
}
Err(err) => {
CString::new(format!("{:?}", err))
.expect("Couldn't create string!")
.into_raw()
}
}
}
#[no_mangle]
pub unsafe extern "C" fn CreateClientMemory(
client: *mut c_char,
key: *mut c_char,
value: *mut c_char
) -> *mut c_char {
let raw_client = get_string(client);
let client: Client = match serde_json::from_str(&raw_client) {
Ok(body) => body,
Err(_err) => {
return CString::new(format!("client bad format"))
.expect("Couldn't create string!")
.into_raw()
}
};
let key = get_string(key);
let string = get_string(value);
let value: serde_json::Value = serde_json::from_str(&string).expect("");
match csml_engine::create_client_memory(&client, key, value) {
Ok(_) => {
CString::new(format!(""))
.expect("Couldn't create string!")
.into_raw()
},
Err(err) => {
CString::new(format!("{:?}", err))
.expect("Couldn't create string!")
.into_raw()
},
}
}
#[no_mangle]
pub unsafe extern "C" fn GetBotSteps(json: *mut c_char) -> *mut c_char {
let string = get_string(json);
let jsonbot: serde_json::Value = match serde_json::from_str(&string) {
Ok(body) => body,
Err(_err) => {
return CString::new(format!("client bad format"))
.expect("Couldn't create string!")
.into_raw()
}
};
let map = csml_engine::get_steps_from_flow(serde_json::from_value(jsonbot).unwrap());
let obj = serde_json::json!(map);
CString::new(obj.to_string())
.expect("Couldn't create string!")
.into_raw()
}
#[no_mangle]
pub unsafe extern "C" fn ValidateBot(
json: *mut c_char,
) -> *mut c_char {
let string = get_string(json);
let jsonbot: serde_json::Value = match serde_json::from_str(&string) {
Ok(body) => body,
Err(_err) => {
return CString::new(format!("client bad format"))
.expect("Couldn't create string!")
.into_raw()
}
};
let mut map = serde_json::Map::new();
match csml_engine::validate_bot(serde_json::from_value(jsonbot).unwrap()) {
CsmlResult {
flows: _,
extern_flows: _,
warnings,
errors: None,
} => {
map.insert(
"valid".to_owned(),
serde_json::json!(true)
);
if let Some(warnings) = warnings {
map.insert(
"warnings".to_owned(),
serde_json::json!(warnings)
);
}
}
CsmlResult {
flows: _,
extern_flows: _,
warnings,
errors: Some(errors),
} => {
map.insert(
"valid".to_owned(),
serde_json::json!(false)
);
if let Some(warnings) = warnings {
map.insert(
"warnings".to_owned(),
serde_json::json!(warnings)
);
}
map.insert(
"errors".to_owned(),
serde_json::json!(errors)
);
}
};
let obj = serde_json::json!(map);
CString::new(obj.to_string())
.expect("Couldn't create string!")
.into_raw()
}
#[no_mangle]
pub unsafe extern "C" fn RunBot(
json: *mut c_char,
) -> *mut c_char {
let string = get_string(json);
let run_request: RunRequest = match serde_json::from_str(&string) {
Ok(body) => body,
Err(_err) => {
return CString::new(format!("client bad format"))
.expect("Couldn't create string!")
.into_raw()
}
};
let bot_opt = match run_request.get_bot_opt() {
Ok(bot_opt) => bot_opt,
Err(err) => {
return CString::new(format!("{:?}", err))
.expect("Couldn't create string!")
.into_raw()
},
};
let request = run_request.event;
let obj = match start_conversation(request, bot_opt) {
Ok(map) => serde_json::json!(map),
Err(err) => {
return CString::new(format!("{:?}", err))
.expect("Couldn't create string!")
.into_raw()
},
};
CString::new(obj.to_string())
.expect("Couldn't create string!")
.into_raw()
}
#[no_mangle]
pub unsafe extern "C" fn CloseConversations(
json: *mut c_char,
) -> *mut c_char {
let string = get_string(json);
let client: Client = match serde_json::from_str(&string) {
Ok(body) => body,
Err(_err) => {
return CString::new(format!("client bad format"))
.expect("Couldn't create string!")
.into_raw()
}
};
match user_close_all_conversations(client) {
Ok(_) => {
return CString::new(format!("true"))
.expect("Couldn't create string!")
.into_raw()
},
Err(err) => {
return CString::new(format!("{:?}", err))
.expect("Couldn't create string!")
.into_raw()
}
}
}
#[no_mangle]
pub unsafe extern "C" fn CreateBotVersion(
json: *mut c_char,
) -> *mut c_char {
let string = get_string(json);
let bot: CsmlBot = match serde_json::from_str(&string) {
Ok(body) => body,
Err(_err) => {
return CString::new(format!("client bad format"))
.expect("Couldn't create string!")
.into_raw()
}
};
match csml_engine::create_bot_version(bot) {
Ok(version_data) => {
let value = serde_json::json!(version_data);
return CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
Err(err) => {
return CString::new(format!("{:?}", err))
.expect("Couldn't create string!")
.into_raw()
},
}
}
#[no_mangle]
pub unsafe extern "C" fn GetBotByVersionId(
j_bot_id: *mut c_char,
j_version_id: *mut c_char,
) -> *mut c_char {
let bot_id = get_string(j_bot_id);
let version_id = get_string(j_version_id);
match csml_engine::get_bot_by_version_id(&version_id, &bot_id) {
Ok(bot) => {
let value = match bot {
Some(bot) => {
serde_json::json!(
bot.flatten()
)
}
None => {
serde_json::json!({
"error": "Not found"
})
}
};
CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
}
Err(err) => {
let value = serde_json::json!({
"error": format!("{:?}", err),
});
CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
}
}
#[no_mangle]
pub unsafe extern "C" fn GetLastBotversion(
j_bot_id: *mut c_char,
) -> *mut c_char {
let bot_id = get_string(j_bot_id);
match csml_engine::get_last_bot_version(&bot_id) {
Ok(bot) => {
let value = match bot {
Some(bot) => {
serde_json::json!(
bot.flatten()
)
}
None => {
serde_json::json!({
"error": "Not found"
})
}
};
CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
Err(err) => {
let value = serde_json::json!({
"error": format!("{:?}", err),
});
CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
}
}
#[no_mangle]
pub unsafe extern "C" fn DeleteBotVersion(
j_bot_id: *mut c_char,
j_version_id: *mut c_char,
) -> *mut c_char {
let bot_id = get_string(j_bot_id);
let version_id = get_string(j_version_id);
match csml_engine::delete_bot_version_id(&version_id, &bot_id) {
Ok(value) => {
let value = serde_json::json!(
value
);
CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
Err(err) => {
let value = serde_json::json!({
"error": format!("{:?}", err),
});
CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
}
}
#[no_mangle]
pub unsafe extern "C" fn DeleteBotVersions(
j_bot_id: *mut c_char,
) -> *mut c_char {
let bot_id = get_string(j_bot_id);
match csml_engine::delete_all_bot_versions(&bot_id) {
Ok(value) => {
let value= serde_json::json!(
value
);
CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
Err(err) => {
let value = serde_json::json!({
"error": format!("{:?}", err),
});
CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
}
}
#[no_mangle]
pub unsafe extern "C" fn FoldBot(
j_bot: *mut c_char,
) -> *mut c_char {
let string= get_string(j_bot);
let bot: CsmlBot = match serde_json::from_str(&string) {
Ok(body) => body,
Err(_err) => {
return CString::new(format!("client bad format"))
.expect("Couldn't create string!")
.into_raw()
}
};
match csml_engine::fold_bot(bot) {
Ok(flow) => {
let value = serde_json::json!({"flow": flow});
CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
Err(err) => {
let value = serde_json::json!({
"error": format!("{:?}", err),
});
CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
}
}
#[no_mangle]
pub unsafe extern "C" fn DeleteClientMemory(
j_client: *mut c_char,
j_memory_key: *mut c_char,
) -> *mut c_char {
let string= get_string(j_client);
let client: Client = match serde_json::from_str(&string) {
Ok(body) => body,
Err(_err) => {
return CString::new(format!("client bad format"))
.expect("Couldn't create string!")
.into_raw()
}
};
let key = get_string(j_memory_key);
match csml_engine::delete_client_memory(&client, &key) {
Ok(value) => {
let value= serde_json::json!(
value
);
CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
Err(err) => {
let value = serde_json::json!({
"error": format!("{:?}", err),
});
CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
}
}
#[no_mangle]
pub unsafe extern "C" fn DeleteClientMemories(
j_client: *mut c_char,
) -> *mut c_char {
let string = get_string(j_client);
let client: Client = match serde_json::from_str(&string) {
Ok(body) => body,
Err(_err) => {
return CString::new(format!("client bad format"))
.expect("Couldn't create string!")
.into_raw()
}
};
match csml_engine::delete_client_memories(&client) {
Ok(value) => {
let value= serde_json::json!(
value
);
CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
Err(err) => {
let value = serde_json::json!({
"error": format!("{:?}", err),
});
CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
}
}
#[no_mangle]
pub unsafe extern "C" fn DeleteClientsData(
j_client: *mut c_char,
) -> *mut c_char {
let string = get_string(j_client);
let client: Client = match serde_json::from_str(&string) {
Ok(body) => body,
Err(_err) => {
return CString::new(format!("client bad format"))
.expect("Couldn't create string!")
.into_raw()
}
};
match csml_engine::delete_client(&client) {
Ok(value) => {
let value = serde_json::json!(
value
);
CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
Err(err) => {
let value = serde_json::json!({
"error": format!("{:?}", err),
});
CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
}
}
#[no_mangle]
pub unsafe extern "C" fn DeleteBotData(
j_bot_id: *mut c_char,
) -> *mut c_char {
let bot_id = get_string(j_bot_id);
match csml_engine::delete_all_bot_data(&bot_id) {
Ok(value) => {
let value = serde_json::json!(
value
);
CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
Err(err) => {
let value = serde_json::json!({
"error": format!("{:?}", err),
});
CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
}
}
#[no_mangle]
pub unsafe extern "C" fn DeleteExpiredData(
) -> *mut c_char {
match csml_engine::delete_expired_data() {
Ok(value) => {
let value = serde_json::json!(
value
);
CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
Err(err) => {
let value = serde_json::json!({
"error": format!("{:?}", err),
});
CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
}
}
#[no_mangle]
pub unsafe extern "C" fn GetClientMemories(
j_client: *mut c_char,
) -> *mut c_char {
let string = get_string(j_client);
let client: Client = match serde_json::from_str(&string) {
Ok(body) => body,
Err(_err) => {
return CString::new(format!("client bad format"))
.expect("Couldn't create string!")
.into_raw()
}
};
match csml_engine::get_client_memories(&client) {
Ok(value) => {
let value= serde_json::json!(
value
);
CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
Err(err) => {
let value = serde_json::json!({
"error": format!("{:?}", err),
});
CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
}
}
#[no_mangle]
pub unsafe extern "C" fn GetClientMemory(
j_client: *mut c_char,
j_memory_key: *mut c_char,
) -> *mut c_char {
let string = get_string(j_client);
let client: Client = match serde_json::from_str(&string) {
Ok(body) => body,
Err(_err) => {
return CString::new(format!("client bad format"))
.expect("Couldn't create string!")
.into_raw()
}
};
let memory_key = get_string(j_memory_key);
match csml_engine::get_client_memory(&client, &memory_key) {
Ok(value) => {
let value= serde_json::json!(
value
);
return CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
Err(err) => {
let value = serde_json::json!({
"error": format!("{:?}", err),
});
return CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
}
}
#[no_mangle]
pub unsafe extern "C" fn GetClientConversations(
j_client: *mut c_char,
j_limit: *mut c_char,
) -> *mut c_char {
let string = get_string(j_client);
let client: Client = match serde_json::from_str(&string) {
Ok(body) => body,
Err(_err) => {
return CString::new(format!("client bad format"))
.expect("Couldn't create string!")
.into_raw()
}
};
let string = get_string(j_limit);
let params: LimitPaginationQueryParams = match serde_json::from_str(&string) {
Ok(body) => body,
Err(_err) => {
return CString::new(format!("client bad format"))
.expect("Couldn't create string!")
.into_raw()
}
};
match csml_engine::get_client_conversations(&client, params.limit, params.pagination_key) {
Ok(value) => {
let value= serde_json::json!(
value
);
return CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
Err(err) => {
let value = serde_json::json!({
"error": format!("{:?}", err),
});
return CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
}
}
#[no_mangle]
pub unsafe extern "C" fn GetClientMessages(
j_client: *mut c_char,
j_limit: *mut c_char,
) -> *mut c_char {
let string = get_string(j_client);
let client: Client = match serde_json::from_str(&string) {
Ok(body) => body,
Err(_err) => {
return CString::new(format!("client bad format"))
.expect("Couldn't create string!")
.into_raw()
}
};
let string = get_string(j_limit);
let params: LimitPaginationQueryParams = match serde_json::from_str(&string) {
Ok(body) => body,
Err(_err) => {
return CString::new(format!("client bad format"))
.expect("Couldn't create string!")
.into_raw()
}
};
match csml_engine::get_client_messages(&client, params.limit, params.pagination_key) {
Ok(value) => {
let value= serde_json::json!(
value
);
return CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
Err(err) => {
let value = serde_json::json!({
"error": format!("{:?}", err),
});
return CString::new(value.to_string())
.expect("Couldn't create string!")
.into_raw()
},
}
}
| 26.259259 | 95 | 0.486821 |
09b250a13ce47131da41e7ba36597b92d109ef3c | 4,553 | use super::*;
use crate::config::Config;
use crate::rustfmt_diff::{make_diff, print_diff};
pub(crate) struct DiffEmitter {
config: Config,
}
impl DiffEmitter {
pub(crate) fn new(config: Config) -> Self {
Self { config }
}
}
impl Emitter for DiffEmitter {
fn emit_formatted_file(
&mut self,
output: &mut dyn Write,
FormattedFile {
filename,
original_text,
formatted_text,
}: FormattedFile<'_>,
) -> Result<EmitterResult, io::Error> {
const CONTEXT_SIZE: usize = 3;
let mismatch = make_diff(&original_text, formatted_text, CONTEXT_SIZE);
let has_diff = !mismatch.is_empty();
if has_diff {
if self.config.print_misformatted_file_names() {
writeln!(output, "{}", filename)?;
} else {
print_diff(
mismatch,
|line_num| format!("Diff in {} at line {}:", filename, line_num),
&self.config,
);
}
} else if original_text != formatted_text {
// This occurs when the only difference between the original and formatted values
// is the newline style. This happens because The make_diff function compares the
// original and formatted values line by line, independent of line endings.
writeln!(output, "Incorrect newline style in {}", filename)?;
return Ok(EmitterResult { has_diff: true });
}
return Ok(EmitterResult { has_diff });
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::Config;
use crate::FileName;
use std::path::PathBuf;
#[test]
fn does_not_print_when_no_files_reformatted() {
let mut writer = Vec::new();
let config = Config::default();
let mut emitter = DiffEmitter::new(config);
let result = emitter
.emit_formatted_file(
&mut writer,
FormattedFile {
filename: &FileName::Real(PathBuf::from("src/lib.rs")),
original_text: "fn empty() {}\n",
formatted_text: "fn empty() {}\n",
},
)
.unwrap();
assert_eq!(result.has_diff, false);
assert_eq!(writer.len(), 0);
}
#[test]
fn prints_file_names_when_config_is_enabled() {
let bin_file = "src/bin.rs";
let bin_original = "fn main() {\nprintln!(\"Hello, world!\");\n}";
let bin_formatted = "fn main() {\n println!(\"Hello, world!\");\n}";
let lib_file = "src/lib.rs";
let lib_original = "fn greet() {\nprintln!(\"Greetings!\");\n}";
let lib_formatted = "fn greet() {\n println!(\"Greetings!\");\n}";
let mut writer = Vec::new();
let mut config = Config::default();
config.set().print_misformatted_file_names(true);
let mut emitter = DiffEmitter::new(config);
let _ = emitter
.emit_formatted_file(
&mut writer,
FormattedFile {
filename: &FileName::Real(PathBuf::from(bin_file)),
original_text: bin_original,
formatted_text: bin_formatted,
},
)
.unwrap();
let _ = emitter
.emit_formatted_file(
&mut writer,
FormattedFile {
filename: &FileName::Real(PathBuf::from(lib_file)),
original_text: lib_original,
formatted_text: lib_formatted,
},
)
.unwrap();
assert_eq!(
String::from_utf8(writer).unwrap(),
format!("{}\n{}\n", bin_file, lib_file),
)
}
#[test]
fn prints_newline_message_with_only_newline_style_diff() {
let mut writer = Vec::new();
let config = Config::default();
let mut emitter = DiffEmitter::new(config);
let _ = emitter
.emit_formatted_file(
&mut writer,
FormattedFile {
filename: &FileName::Real(PathBuf::from("src/lib.rs")),
original_text: "fn empty() {}\n",
formatted_text: "fn empty() {}\r\n",
},
)
.unwrap();
assert_eq!(
String::from_utf8(writer).unwrap(),
String::from("Incorrect newline style in src/lib.rs\n")
);
}
}
| 32.992754 | 93 | 0.518559 |
e6860be491332eccc9b495dcd5cb804e2688b11e | 6,992 | //! A wrapper type for representing a layer of indirection within a file.
//!
//! A `FilePtr<P, T>` is composed of two types: a pointer type `P` and a value type `T` where
//! the pointer type describes an offset to read the value type from. Once read from the file
//! it can be dereferenced to yield the value it points to.
//!
//! ## Example
//! ```rust
//! use binread::{prelude::*, io::Cursor, FilePtr};
//!
//! #[derive(BinRead)]
//! struct Test {
//! pointer: FilePtr<u32, u8>
//! }
//!
//! let test: Test = Cursor::new(b"\0\0\0\x08\0\0\0\0\xff").read_be().unwrap();
//! assert_eq!(test.pointer.ptr, 8);
//! assert_eq!(*test.pointer, 0xFF);
//! ```
//!
//! Example data mapped out:
//! ```hex
//! [pointer] [value]
//! 00000000: 0000 0008 0000 0000 ff ............
//! ```
//!
//! Use `offset` to change what the pointer is relative to (default: beginning of reader).
use super::*;
use core::fmt;
use core::ops::{Deref, DerefMut};
/// A wrapper type for representing a layer of indirection within a file.
///
/// A `FilePtr<P, T>` is composed of two types: a pointer type `P` and a value type `T` where
/// the pointer type describes and offset to read the value type from. Once read from the file
/// it can be dereferenced to yeild the value it points to.
///
/// ## Example
/// ```rust
/// use binread::{prelude::*, io::Cursor, FilePtr};
///
/// #[derive(BinRead)]
/// struct Test {
/// pointer: FilePtr<u32, u8>
/// }
///
/// let test: Test = Cursor::new(b"\0\0\0\x08\0\0\0\0\xff").read_be().unwrap();
/// assert_eq!(test.pointer.ptr, 8);
/// assert_eq!(*test.pointer, 0xFF);
/// ```
///
/// Example data mapped out:
/// ```hex
/// [pointer] [value]
/// 00000000: 0000 0008 0000 0000 ff ............
/// ```
///
/// Use `offset` to change what the pointer is relative to (default: beginning of reader).
use core2::io::{Read, Seek, SeekFrom};
pub struct FilePtr<Ptr: IntoSeekFrom, BR: BinRead> {
pub ptr: Ptr,
pub value: Option<BR>,
}
/// Type alias for 8-bit pointers
pub type FilePtr8<T> = FilePtr<u8, T>;
/// Type alias for 16-bit pointers
pub type FilePtr16<T> = FilePtr<u16, T>;
/// Type alias for 32-bit pointers
pub type FilePtr32<T> = FilePtr<u32, T>;
/// Type alias for 64-bit pointers
pub type FilePtr64<T> = FilePtr<u64, T>;
/// Type alias for 128-bit pointers
pub type FilePtr128<T> = FilePtr<u128, T>;
impl<Ptr: BinRead<Args = ()> + IntoSeekFrom, BR: BinRead> BinRead for FilePtr<Ptr, BR> {
type Args = BR::Args;
fn read_options<R: Read + Seek>(
reader: &mut R,
options: &ReadOptions,
_: Self::Args,
) -> BinResult<Self> {
#[cfg(feature = "debug_template")]
let options = &{
let mut options = *options;
let pos = reader.seek(SeekFrom::Current(0)).unwrap();
let type_name = &core::any::type_name::<Ptr>();
if let Some(name) = options.variable_name {
binary_template::write_named(
options.endian,
pos,
type_name,
&format!("ptr_to_{}", name),
);
} else {
binary_template::write(options.endian, pos, type_name);
}
options.dont_output_to_template = true;
options
};
Ok(FilePtr {
ptr: Ptr::read_options(reader, options, ())?,
value: None,
})
}
fn after_parse<R>(&mut self, reader: &mut R, ro: &ReadOptions, args: BR::Args) -> BinResult<()>
where
R: Read + Seek,
{
let relative_to = ro.offset;
let before = reader.seek(SeekFrom::Current(0))?;
reader.seek(SeekFrom::Start(relative_to))?;
reader.seek(self.ptr.into_seek_from())?;
let mut inner: BR = BinRead::read_options(reader, ro, args)?;
inner.after_parse(reader, ro, args)?;
self.value = Some(inner);
reader.seek(SeekFrom::Start(before))?;
Ok(())
}
}
impl<Ptr: BinRead<Args = ()> + IntoSeekFrom, BR: BinRead> FilePtr<Ptr, BR> {
/// Custom parser designed for use with the `parse_with` attribute ([example](crate::attribute#custom-parsers))
/// that reads a [`FilePtr`](FilePtr) then immediately dereferences it into an owned value
pub fn parse<R: Read + Seek>(
reader: &mut R,
options: &ReadOptions,
args: BR::Args,
) -> BinResult<BR> {
let mut ptr: Self = Self::read_options(reader, options, args)?;
let saved_pos = reader.seek(SeekFrom::Current(0))?;
ptr.after_parse(reader, options, args)?;
reader.seek(SeekFrom::Start(saved_pos))?;
Ok(ptr.into_inner())
}
/// Consume the pointer and return the inner type
///
/// # Panics
///
/// Will panic if the file pointer hasn't been properly postprocessed
pub fn into_inner(self) -> BR {
self.value.unwrap()
}
}
/// Used to allow any convert any type castable to i64 into a [`SeekFrom::Current`](io::SeekFrom::Current)
pub trait IntoSeekFrom: Copy {
fn into_seek_from(self) -> SeekFrom;
}
macro_rules! impl_into_seek_from {
($($t:ty),*) => {
$(
impl IntoSeekFrom for $t {
fn into_seek_from(self) -> SeekFrom {
SeekFrom::Current(self as i64)
}
}
)*
};
}
impl_into_seek_from!(i8, i16, i32, i64, i128, u8, u16, u32, u64, u128);
/// ## Panics
/// Will panic if the FilePtr has not been read yet using [`BinRead::after_parse`](BinRead::after_parse)
impl<Ptr: IntoSeekFrom, BR: BinRead> Deref for FilePtr<Ptr, BR> {
type Target = BR;
fn deref(&self) -> &Self::Target {
match self.value.as_ref() {
Some(x) => x,
None => panic!(
"Deref'd FilePtr before reading (make sure to use FilePtr::after_parse first)"
),
}
}
}
/// ## Panics
/// Will panic if the FilePtr has not been read yet using [`BinRead::after_parse`](BinRead::after_parse)
impl<Ptr: IntoSeekFrom, BR: BinRead> DerefMut for FilePtr<Ptr, BR> {
fn deref_mut(&mut self) -> &mut BR {
match self.value.as_mut() {
Some(x) => x,
None => panic!(
"Deref'd FilePtr before reading (make sure to use FilePtr::after_parse first)"
),
}
}
}
impl<Ptr, BR> fmt::Debug for FilePtr<Ptr, BR>
where
Ptr: BinRead<Args = ()> + IntoSeekFrom,
BR: BinRead + fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(ref value) = self.value {
fmt::Debug::fmt(value, f)
} else {
write!(f, "UnreadPointer")
}
}
}
impl<Ptr, BR> PartialEq<FilePtr<Ptr, BR>> for FilePtr<Ptr, BR>
where
Ptr: BinRead<Args = ()> + IntoSeekFrom,
BR: BinRead + PartialEq,
{
fn eq(&self, other: &Self) -> bool {
self.deref() == other.deref()
}
}
| 30.801762 | 115 | 0.572654 |
28e19398c9f0761985cf929363be7c0a78e2312c | 15,171 | //! The `faucet` module provides an object for launching a Solana Faucet,
//! which is the custodian of any remaining lamports in a mint.
//! The Solana Faucet builds and send airdrop transactions,
//! checking requests against a request cap for a given time time_slice
//! and (to come) an IP rate limit.
use bincode::{deserialize, serialize};
use byteorder::{ByteOrder, LittleEndian};
use bytes::{Bytes, BytesMut};
use log::*;
use serde_derive::{Deserialize, Serialize};
use solana_metrics::datapoint_info;
use solana_sdk::{
hash::Hash,
message::Message,
packet::PACKET_DATA_SIZE,
pubkey::Pubkey,
signature::{Keypair, Signer},
system_instruction,
transaction::Transaction,
};
use std::{
io::{self, Error, ErrorKind},
net::{IpAddr, Ipv4Addr, SocketAddr, TcpStream},
sync::{mpsc::Sender, Arc, Mutex},
thread,
time::Duration,
};
use tokio::{
self,
net::TcpListener,
prelude::{Future, Read, Sink, Stream, Write},
};
use tokio_codec::{BytesCodec, Decoder};
#[macro_export]
macro_rules! socketaddr {
($ip:expr, $port:expr) => {
SocketAddr::from((Ipv4Addr::from($ip), $port))
};
($str:expr) => {{
let a: SocketAddr = $str.parse().unwrap();
a
}};
}
pub const TIME_SLICE: u64 = 60;
pub const REQUEST_CAP: u64 = solana_sdk::native_token::LAMPORTS_PER_SOL * 10_000_000;
pub const FAUCET_PORT: u16 = 9900;
pub const FAUCET_PORT_STR: &str = "9900";
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub enum FaucetRequest {
GetAirdrop {
lamports: u64,
to: Pubkey,
blockhash: Hash,
},
}
pub struct Faucet {
mint_keypair: Keypair,
ip_cache: Vec<IpAddr>,
pub time_slice: Duration,
per_time_cap: u64,
per_request_cap: Option<u64>,
pub request_current: u64,
}
impl Faucet {
pub fn new(
mint_keypair: Keypair,
time_input: Option<u64>,
per_time_cap: Option<u64>,
per_request_cap: Option<u64>,
) -> Faucet {
let time_slice = Duration::new(time_input.unwrap_or(TIME_SLICE), 0);
let per_time_cap = per_time_cap.unwrap_or(REQUEST_CAP);
Faucet {
mint_keypair,
ip_cache: Vec::new(),
time_slice,
per_time_cap,
per_request_cap,
request_current: 0,
}
}
pub fn check_time_request_limit(&mut self, request_amount: u64) -> bool {
self.request_current
.checked_add(request_amount)
.map(|s| s <= self.per_time_cap)
.unwrap_or(false)
}
pub fn clear_request_count(&mut self) {
self.request_current = 0;
}
pub fn add_ip_to_cache(&mut self, ip: IpAddr) {
self.ip_cache.push(ip);
}
pub fn clear_ip_cache(&mut self) {
self.ip_cache.clear();
}
pub fn build_airdrop_transaction(
&mut self,
req: FaucetRequest,
) -> Result<Transaction, io::Error> {
trace!("build_airdrop_transaction: {:?}", req);
match req {
FaucetRequest::GetAirdrop {
lamports,
to,
blockhash,
} => {
if let Some(cap) = self.per_request_cap {
if lamports > cap {
return Err(Error::new(
ErrorKind::Other,
format!("request too large; req: {} cap: {}", lamports, cap),
));
}
}
if self.check_time_request_limit(lamports) {
self.request_current = self.request_current.saturating_add(lamports);
datapoint_info!(
"faucet-airdrop",
("request_amount", lamports, i64),
("request_current", self.request_current, i64)
);
info!("Requesting airdrop of {} to {:?}", lamports, to);
let mint_pubkey = self.mint_keypair.pubkey();
let create_instruction =
system_instruction::transfer(&mint_pubkey, &to, lamports);
let message = Message::new(&[create_instruction], Some(&mint_pubkey));
Ok(Transaction::new(&[&self.mint_keypair], message, blockhash))
} else {
Err(Error::new(
ErrorKind::Other,
format!(
"token limit reached; req: {} current: {} cap: {}",
lamports, self.request_current, self.per_time_cap
),
))
}
}
}
}
pub fn process_faucet_request(&mut self, bytes: &BytesMut) -> Result<Bytes, io::Error> {
let req: FaucetRequest = deserialize(bytes).map_err(|err| {
io::Error::new(
io::ErrorKind::Other,
format!("deserialize packet in faucet: {:?}", err),
)
})?;
info!("Airdrop transaction requested...{:?}", req);
let res = self.build_airdrop_transaction(req);
match res {
Ok(tx) => {
let response_vec = bincode::serialize(&tx).map_err(|err| {
io::Error::new(
io::ErrorKind::Other,
format!("deserialize packet in faucet: {:?}", err),
)
})?;
let mut response_vec_with_length = vec![0; 2];
LittleEndian::write_u16(&mut response_vec_with_length, response_vec.len() as u16);
response_vec_with_length.extend_from_slice(&response_vec);
let response_bytes = Bytes::from(response_vec_with_length);
info!("Airdrop transaction granted");
Ok(response_bytes)
}
Err(err) => {
warn!("Airdrop transaction failed: {:?}", err);
Err(err)
}
}
}
}
impl Drop for Faucet {
fn drop(&mut self) {
solana_metrics::flush();
}
}
pub fn request_airdrop_transaction(
faucet_addr: &SocketAddr,
id: &Pubkey,
lamports: u64,
blockhash: Hash,
) -> Result<Transaction, Error> {
info!(
"request_airdrop_transaction: faucet_addr={} id={} lamports={} blockhash={}",
faucet_addr, id, lamports, blockhash
);
let mut stream = TcpStream::connect_timeout(faucet_addr, Duration::new(3, 0))?;
stream.set_read_timeout(Some(Duration::new(10, 0)))?;
let req = FaucetRequest::GetAirdrop {
lamports,
blockhash,
to: *id,
};
let req = serialize(&req).expect("serialize faucet request");
stream.write_all(&req)?;
// Read length of transaction
let mut buffer = [0; 2];
stream.read_exact(&mut buffer).map_err(|err| {
info!(
"request_airdrop_transaction: buffer length read_exact error: {:?}",
err
);
Error::new(ErrorKind::Other, "Airdrop failed")
})?;
let transaction_length = LittleEndian::read_u16(&buffer) as usize;
if transaction_length > PACKET_DATA_SIZE || transaction_length == 0 {
return Err(Error::new(
ErrorKind::Other,
format!(
"request_airdrop_transaction: invalid transaction_length from faucet: {}",
transaction_length
),
));
}
// Read the transaction
let mut buffer = Vec::new();
buffer.resize(transaction_length, 0);
stream.read_exact(&mut buffer).map_err(|err| {
info!(
"request_airdrop_transaction: buffer read_exact error: {:?}",
err
);
Error::new(ErrorKind::Other, "Airdrop failed")
})?;
let transaction: Transaction = deserialize(&buffer).map_err(|err| {
Error::new(
ErrorKind::Other,
format!("request_airdrop_transaction deserialize failure: {:?}", err),
)
})?;
Ok(transaction)
}
// For integration tests. Listens on random open port and reports port to Sender.
pub fn run_local_faucet(
mint_keypair: Keypair,
sender: Sender<SocketAddr>,
per_time_cap: Option<u64>,
) {
thread::spawn(move || {
let faucet_addr = socketaddr!(0, 0);
let faucet = Arc::new(Mutex::new(Faucet::new(
mint_keypair,
None,
per_time_cap,
None,
)));
run_faucet(faucet, faucet_addr, Some(sender));
});
}
pub fn run_faucet(
faucet: Arc<Mutex<Faucet>>,
faucet_addr: SocketAddr,
send_addr: Option<Sender<SocketAddr>>,
) {
let socket = TcpListener::bind(&faucet_addr).unwrap();
if let Some(send_addr) = send_addr {
send_addr.send(socket.local_addr().unwrap()).unwrap();
}
info!("Faucet started. Listening on: {}", faucet_addr);
let done = socket
.incoming()
.map_err(|e| debug!("failed to accept socket; error = {:?}", e))
.for_each(move |socket| {
let faucet2 = faucet.clone();
let framed = BytesCodec::new().framed(socket);
let (writer, reader) = framed.split();
let processor = reader.and_then(move |bytes| {
match faucet2.lock().unwrap().process_faucet_request(&bytes) {
Ok(response_bytes) => {
trace!("Airdrop response_bytes: {:?}", response_bytes.to_vec());
Ok(response_bytes)
}
Err(e) => {
info!("Error in request: {:?}", e);
Ok(Bytes::from(0u16.to_le_bytes().to_vec()))
}
}
});
let server = writer
.send_all(processor.or_else(|err| {
Err(io::Error::new(
io::ErrorKind::Other,
format!("Faucet response: {:?}", err),
))
}))
.then(|_| Ok(()));
tokio::spawn(server)
});
tokio::run(done);
}
#[cfg(test)]
mod tests {
use super::*;
use bytes::BufMut;
use solana_sdk::system_instruction::SystemInstruction;
use std::time::Duration;
#[test]
fn test_check_time_request_limit() {
let keypair = Keypair::new();
let mut faucet = Faucet::new(keypair, None, Some(3), None);
assert!(faucet.check_time_request_limit(1));
faucet.request_current = 3;
assert!(!faucet.check_time_request_limit(1));
faucet.request_current = 1;
assert!(!faucet.check_time_request_limit(u64::MAX));
}
#[test]
fn test_clear_request_count() {
let keypair = Keypair::new();
let mut faucet = Faucet::new(keypair, None, None, None);
faucet.request_current += 256;
assert_eq!(faucet.request_current, 256);
faucet.clear_request_count();
assert_eq!(faucet.request_current, 0);
}
#[test]
fn test_add_ip_to_cache() {
let keypair = Keypair::new();
let mut faucet = Faucet::new(keypair, None, None, None);
let ip = "127.0.0.1".parse().expect("create IpAddr from string");
assert_eq!(faucet.ip_cache.len(), 0);
faucet.add_ip_to_cache(ip);
assert_eq!(faucet.ip_cache.len(), 1);
assert!(faucet.ip_cache.contains(&ip));
}
#[test]
fn test_clear_ip_cache() {
let keypair = Keypair::new();
let mut faucet = Faucet::new(keypair, None, None, None);
let ip = "127.0.0.1".parse().expect("create IpAddr from string");
assert_eq!(faucet.ip_cache.len(), 0);
faucet.add_ip_to_cache(ip);
assert_eq!(faucet.ip_cache.len(), 1);
faucet.clear_ip_cache();
assert_eq!(faucet.ip_cache.len(), 0);
assert!(faucet.ip_cache.is_empty());
}
#[test]
fn test_faucet_default_init() {
let keypair = Keypair::new();
let time_slice: Option<u64> = None;
let request_cap: Option<u64> = None;
let faucet = Faucet::new(keypair, time_slice, request_cap, Some(100));
assert_eq!(faucet.time_slice, Duration::new(TIME_SLICE, 0));
assert_eq!(faucet.per_time_cap, REQUEST_CAP);
assert_eq!(faucet.per_request_cap, Some(100));
}
#[test]
fn test_faucet_build_airdrop_transaction() {
let to = Pubkey::new_rand();
let blockhash = Hash::default();
let request = FaucetRequest::GetAirdrop {
lamports: 2,
to,
blockhash,
};
let mint = Keypair::new();
let mint_pubkey = mint.pubkey();
let mut faucet = Faucet::new(mint, None, None, None);
let tx = faucet.build_airdrop_transaction(request).unwrap();
let message = tx.message();
assert_eq!(tx.signatures.len(), 1);
assert_eq!(
message.account_keys,
vec![mint_pubkey, to, Pubkey::default()]
);
assert_eq!(message.recent_blockhash, blockhash);
assert_eq!(message.instructions.len(), 1);
let instruction: SystemInstruction = deserialize(&message.instructions[0].data).unwrap();
assert_eq!(instruction, SystemInstruction::Transfer { lamports: 2 });
// Test per-time request cap
let mint = Keypair::new();
faucet = Faucet::new(mint, None, Some(1), None);
let tx = faucet.build_airdrop_transaction(request);
assert!(tx.is_err());
// Test per-request cap
let mint = Keypair::new();
faucet = Faucet::new(mint, None, None, Some(1));
let tx = faucet.build_airdrop_transaction(request);
assert!(tx.is_err());
}
#[test]
fn test_process_faucet_request() {
let to = Pubkey::new_rand();
let blockhash = Hash::new(&to.as_ref());
let lamports = 50;
let req = FaucetRequest::GetAirdrop {
lamports,
blockhash,
to,
};
let req = serialize(&req).unwrap();
let mut bytes = BytesMut::with_capacity(req.len());
bytes.put(&req[..]);
let keypair = Keypair::new();
let expected_instruction = system_instruction::transfer(&keypair.pubkey(), &to, lamports);
let message = Message::new(&[expected_instruction], Some(&keypair.pubkey()));
let expected_tx = Transaction::new(&[&keypair], message, blockhash);
let expected_bytes = serialize(&expected_tx).unwrap();
let mut expected_vec_with_length = vec![0; 2];
LittleEndian::write_u16(&mut expected_vec_with_length, expected_bytes.len() as u16);
expected_vec_with_length.extend_from_slice(&expected_bytes);
let mut faucet = Faucet::new(keypair, None, None, None);
let response = faucet.process_faucet_request(&bytes);
let response_vec = response.unwrap().to_vec();
assert_eq!(expected_vec_with_length, response_vec);
let mut bad_bytes = BytesMut::with_capacity(9);
bad_bytes.put("bad bytes");
assert!(faucet.process_faucet_request(&bad_bytes).is_err());
}
}
| 33.490066 | 98 | 0.5614 |
fe852e5d8eaee4c95df68851587fde0643bb912e | 568 | // Copyright 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.
pub struct Heap;
pub struct FakeHeap;
pub struct FakeVec<T, A = FakeHeap> { pub f: Option<(T,A)> }
| 35.5 | 68 | 0.732394 |
5dfcbf1350e492a1992e965a6ff18e3893388390 | 7,995 | use serde::{Serialize, Deserialize};
use serde_with::skip_serializing_none;
use super::request_mixin::*;
use crate::janus::core::json::*;
// mixins: RoomParameters (optional), AdminKeyParameters (if enabled)
#[skip_serializing_none]
#[derive(Serialize, Deserialize)]
pub struct CreateParameters {
request: String,
pub room: Option<Identity>,
pub description: Option<JSON_STRING>,
pub is_private: Option<JSON_BOOL>,
pub allowed: Option<JSON_STRING_ARRAY>,
pub secret: Option<JSON_STRING>,
pub pin: Option<JSON_STRING>,
pub require_pvtid: Option<JSON_BOOL>,
pub bitrate: Option<JSON_POSITIVE_INTEGER>,
pub bitrate_cap: Option<JSON_BOOL>,
pub fir_freq: Option<JSON_POSITIVE_INTEGER>,
pub publishers: Option<JSON_POSITIVE_INTEGER>,
pub audiocodec: Option<JSON_STRING>,
pub videocodec: Option<JSON_STRING>,
pub vp9_profile: Option<JSON_STRING>,
pub h264_profile: Option<JSON_STRING>,
pub opus_fec: Option<JSON_BOOL>,
pub video_svc: Option<JSON_BOOL>,
pub audiolevel_ext: Option<JSON_BOOL>,
pub audiolevel_event: Option<JSON_BOOL>,
pub audio_active_packets: Option<JSON_POSITIVE_INTEGER>,
pub audio_level_average: Option<JSON_POSITIVE_INTEGER>,
pub videoorient_ext: Option<JSON_BOOL>,
pub playoutdelay_ext: Option<JSON_BOOL>,
pub transport_wide_cc_ext: Option<JSON_BOOL>,
pub record: Option<JSON_BOOL>,
pub rec_dir: Option<JSON_STRING>,
pub lock_record: Option<JSON_BOOL>,
pub permanent: Option<JSON_BOOL>,
pub notify_joining: Option<JSON_BOOL>,
pub require_e2ee: Option<JSON_BOOL>
}
// mixins: RoomParameters
// missing new_lock_record in parameters definition of janus_videoroom.c
#[derive(Deserialize)]
pub struct EditParameters {
pub secret: Option<JSON_STRING>, // janus_videoroom_access_room(check_modify=TRUE)
pub new_description: Option<JSON_STRING>,
pub new_is_private: Option<JSON_BOOL>,
pub new_secret: Option<JSON_STRING>,
pub new_pin: Option<JSON_STRING>,
pub new_require_pvtid: Option<JSON_BOOL>,
pub new_bitrate: Option<JSON_POSITIVE_INTEGER>,
pub new_fir_freq: Option<JSON_POSITIVE_INTEGER>,
pub new_publishers: Option<JSON_POSITIVE_INTEGER>,
pub new_lock_record: Option<JSON_BOOL>,
pub permanent: Option<JSON_BOOL>
}
// mixins: RoomParameters
// missing secret - janus_videoroom_access_room(check_modify=TRUE)
#[derive(Deserialize)]
pub struct DestroyParameters {
pub secret: Option<JSON_STRING>,
pub permanent: Option<JSON_BOOL>
}
// mixins: AdminKeyParameters (if enabled)
#[derive(Deserialize)]
pub struct ListParameters {}
// mixins: RoomParameters, PidParameters, AdminKeyParameters (if lock_rtp_forward, admin_key enabled)
// missing secret - janus_videoroom_access_room(check_modify=TRUE)
#[derive(Deserialize)]
pub struct RtpForwardParameters {
pub secret: Option<JSON_STRING>,
pub video_port: Option<JSON_POSITIVE_INTEGER>,
pub video_rtcp_port: Option<JSON_POSITIVE_INTEGER>,
pub video_ssrc: Option<JSON_POSITIVE_INTEGER>,
pub video_pt: Option<JSON_POSITIVE_INTEGER>,
pub video_port_2: Option<JSON_POSITIVE_INTEGER>,
pub video_ssrc_2: Option<JSON_POSITIVE_INTEGER>,
pub video_pt_2: Option<JSON_POSITIVE_INTEGER>,
pub video_port_3: Option<JSON_POSITIVE_INTEGER>,
pub video_ssrc_3: Option<JSON_POSITIVE_INTEGER>,
pub video_pt_3: Option<JSON_POSITIVE_INTEGER>,
pub audio_port: Option<JSON_POSITIVE_INTEGER>,
pub audio_rtcp_port: Option<JSON_POSITIVE_INTEGER>,
pub audio_ssrc: Option<JSON_POSITIVE_INTEGER>,
pub audio_pt: Option<JSON_POSITIVE_INTEGER>,
pub data_port: Option<JSON_POSITIVE_INTEGER>,
pub host: JSON_STRING, // JANUS_JSON_PARAM_REQUIRED
pub host_family: Option<JSON_STRING>,
pub simulcast: Option<JSON_BOOL>,
pub srtp_suite: Option<JSON_POSITIVE_INTEGER>,
pub srtp_crypto: Option<JSON_STRING>
}
// same as RtpForwardParameters
#[derive(Deserialize)]
pub struct StopRtpForwardParameters {
pub secret: Option<JSON_STRING>,
pub stream_id: JSON_POSITIVE_INTEGER, // JANUS_JSON_PARAM_REQUIRED
}
// Mixins: RoomParameters,
#[derive(Deserialize)]
pub struct ExistsParameters {
pub room: u64
}
// mixins: RoomParameters
#[derive(Deserialize)]
pub struct AllowedParameters {
pub secret: Option<JSON_STRING>, // janus_videoroom_access_room(check_modify=TRUE)
pub action: JSON_STRING, // JANUS_JSON_PARAM_REQUIRED
pub allowed: Option<JSON_STRING_ARRAY>
}
// mixins: RoomParameters, IdParameters
#[derive(Deserialize)]
pub struct KickParameters {
pub secret: Option<JSON_STRING> // janus_videoroom_access_room(check_modify=TRUE)
}
// mixins: RoomParameters
#[derive(Deserialize)]
pub struct ListParticipantsParameters {}
// mixins: RoomParameters
// missing secret - janus_videoroom_access_room(check_modify=TRUE)
#[derive(Deserialize)]
pub struct ListForwardersParameters {
pub secret: Option<JSON_STRING>
}
// mixins: RoomParameters, janus_videoroom_access_room=TRUE
#[derive(Deserialize)]
pub struct RecordParameters {
pub record: JSON_BOOL, // JANUS_JSON_PARAM_REQUIRED
}
pub type EnableRecordingParameters = RecordParameters;
/** Asynchronous request type definitions */
#[skip_serializing_none]
#[derive(Serialize, Deserialize)]
pub struct JoinParameters {
request: String,
pub room: Identity,
pub ptype: JSON_STRING, // JANUS_JSON_PARAM_REQUIRED
#[serde(flatten)]
pub _rest: JSON_OBJECT
}
#[skip_serializing_none]
#[derive(Serialize, Deserialize)]
pub struct PublisherParameters {
pub token: Option<JSON_STRING>,
pub id: Option<JSON_POSITIVE_INTEGER>,
pub display: Option<JSON_STRING>,
/** joinandconfigure */
pub audio: Option<JSON_BOOL>,
pub video: Option<JSON_BOOL>,
pub data: Option<JSON_BOOL>,
pub bitrate: Option<JSON_POSITIVE_INTEGER>,
pub record: Option<JSON_BOOL>,
pub filename: Option<JSON_STRING>,
/** is configure? */
pub audio_active_packets: Option<JSON_POSITIVE_INTEGER>,
pub audio_level_average: Option<JSON_POSITIVE_INTEGER>
}
#[skip_serializing_none]
#[derive(Serialize, Deserialize)]
pub struct SubscriberParameters {
pub feed: JSON_POSITIVE_INTEGER,
pub private_id: Option<JSON_POSITIVE_INTEGER>,
pub close_pc: Option<JSON_BOOL>,
pub audio: Option<JSON_BOOL>,
pub video: Option<JSON_BOOL>,
pub data: Option<JSON_BOOL>,
pub offer_audio: Option<JSON_BOOL>,
pub offer_video: Option<JSON_BOOL>,
pub offer_data: Option<JSON_BOOL>,
/* For VP8 (or H.264) simulcast */
pub substream: Option<JSON_POSITIVE_INTEGER>,
pub temporal: Option<JSON_POSITIVE_INTEGER>,
pub fallback: Option<JSON_POSITIVE_INTEGER>,
/* For VP9 SVC */
pub spatial_layer: Option<JSON_POSITIVE_INTEGER>,
pub temporal_layer: Option<JSON_POSITIVE_INTEGER>,
}
#[derive(Deserialize)]
pub struct PublishParameters {
pub audio: Option<JSON_BOOL>,
pub audiocodec: Option<JSON_STRING>,
pub video: Option<JSON_BOOL>,
pub videocodec: Option<JSON_STRING>,
pub data: Option<JSON_BOOL>,
pub bitrate: Option<JSON_POSITIVE_INTEGER>,
pub keyframe: Option<JSON_BOOL>,
pub record: Option<JSON_BOOL>,
pub filename: Option<JSON_STRING>,
pub display: Option<JSON_STRING>,
pub secret: Option<JSON_STRING>,
pub audio_level_averge: Option<JSON_POSITIVE_INTEGER>,
pub audio_active_packets: Option<JSON_POSITIVE_INTEGER>,
/* The following are just to force a renegotiation and/or an ICE restart */
pub update: Option<JSON_BOOL>,
pub restart: Option<JSON_BOOL>
}
#[derive(Deserialize)]
pub struct ConfigureParameters {
pub audio: Option<JSON_BOOL>,
pub video: Option<JSON_BOOL>,
pub data: Option<JSON_BOOL>,
/* For talk detection */
pub audio_level_averge: Option<JSON_POSITIVE_INTEGER>,
pub audio_active_packets: Option<JSON_POSITIVE_INTEGER>,
/* For VP8 (or H.264) simulcast */
pub substream: Option<JSON_POSITIVE_INTEGER>,
pub temporal: Option<JSON_POSITIVE_INTEGER>,
pub fallback: Option<JSON_POSITIVE_INTEGER>,
/* For VP9 SVC */
pub spatial_layer: Option<JSON_POSITIVE_INTEGER>,
pub temporal_layer: Option<JSON_POSITIVE_INTEGER>,
/* The following is to handle a renegotiation */
pub update: Option<JSON_BOOL>
}
| 33.734177 | 101 | 0.779862 |
edb1e0facaaf22f878bd5e8318de604ab9cd79ad | 2,018 | #[doc = "Reader of register FLT_DLC"]
pub type R = crate::R<u32, super::FLT_DLC>;
#[doc = "Writer for register FLT_DLC"]
pub type W = crate::W<u32, super::FLT_DLC>;
#[doc = "Register FLT_DLC `reset()`'s with value 0x08"]
impl crate::ResetValue for super::FLT_DLC {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0x08
}
}
#[doc = "Reader of field `FLT_DLC_HI`"]
pub type FLT_DLC_HI_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `FLT_DLC_HI`"]
pub struct FLT_DLC_HI_W<'a> {
w: &'a mut W,
}
impl<'a> FLT_DLC_HI_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f);
self.w
}
}
#[doc = "Reader of field `FLT_DLC_LO`"]
pub type FLT_DLC_LO_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `FLT_DLC_LO`"]
pub struct FLT_DLC_LO_W<'a> {
w: &'a mut W,
}
impl<'a> FLT_DLC_LO_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0f << 16)) | (((value as u32) & 0x0f) << 16);
self.w
}
}
impl R {
#[doc = "Bits 0:3 - Upper Limit for Length of Data Bytes Filter"]
#[inline(always)]
pub fn flt_dlc_hi(&self) -> FLT_DLC_HI_R {
FLT_DLC_HI_R::new((self.bits & 0x0f) as u8)
}
#[doc = "Bits 16:19 - Lower Limit for Length of Data Bytes Filter"]
#[inline(always)]
pub fn flt_dlc_lo(&self) -> FLT_DLC_LO_R {
FLT_DLC_LO_R::new(((self.bits >> 16) & 0x0f) as u8)
}
}
impl W {
#[doc = "Bits 0:3 - Upper Limit for Length of Data Bytes Filter"]
#[inline(always)]
pub fn flt_dlc_hi(&mut self) -> FLT_DLC_HI_W {
FLT_DLC_HI_W { w: self }
}
#[doc = "Bits 16:19 - Lower Limit for Length of Data Bytes Filter"]
#[inline(always)]
pub fn flt_dlc_lo(&mut self) -> FLT_DLC_LO_W {
FLT_DLC_LO_W { w: self }
}
}
| 31.046154 | 86 | 0.589693 |
fbc68c47ee6fac056b20a6454da0bccf71cdcf18 | 18,993 | use futures::future::BoxFuture;
use futures::{join, FutureExt};
use regex::Regex;
use serde::de::DeserializeOwned;
use serde_json::from_slice;
use std::convert::Into;
use std::future::Future;
use super::cache::{CacheExpiry, CacheManager, CachePolicy, FetchResult};
use super::client::{SpotifyApiError, SpotifyClient, SpotifyResponse, SpotifyResponseKind};
use crate::app::models::*;
lazy_static! {
pub static ref ME_ALBUMS_CACHE: Regex =
Regex::new(r"^me_albums_\w+_\w+\.json\.expiry$").unwrap();
pub static ref USER_CACHE: Regex =
Regex::new(r"^me_(albums|playlists)_\w+_\w+\.json(\.expiry)?$").unwrap();
pub static ref ALL_CACHE: Regex =
Regex::new(r"^(me_albums_|me_playlists_|album_|playlist_|artist_)\w+\.json(\.expiry)?$")
.unwrap();
}
fn _playlist_cache(id: &str) -> Regex {
Regex::new(&format!(
r"^playlist(_{}|item_{}_\w+_\w+)\.json\.expiry$",
id, id
))
.unwrap()
}
pub type SpotifyResult<T> = Result<T, SpotifyApiError>;
pub trait SpotifyApiClient {
fn get_artist(&self, id: &str) -> BoxFuture<SpotifyResult<ArtistDescription>>;
fn get_album(&self, id: &str) -> BoxFuture<SpotifyResult<AlbumFullDescription>>;
fn get_album_tracks(
&self,
id: &str,
offset: usize,
limit: usize,
) -> BoxFuture<SpotifyResult<SongBatch>>;
fn get_playlist(&self, id: &str) -> BoxFuture<SpotifyResult<PlaylistDescription>>;
fn get_playlist_tracks(
&self,
id: &str,
offset: usize,
limit: usize,
) -> BoxFuture<SpotifyResult<SongBatch>>;
fn get_saved_albums(
&self,
offset: usize,
limit: usize,
) -> BoxFuture<SpotifyResult<Vec<AlbumDescription>>>;
fn save_album(&self, id: &str) -> BoxFuture<SpotifyResult<AlbumDescription>>;
fn remove_saved_album(&self, id: &str) -> BoxFuture<SpotifyResult<()>>;
fn get_saved_playlists(
&self,
offset: usize,
limit: usize,
) -> BoxFuture<SpotifyResult<Vec<PlaylistDescription>>>;
fn add_to_playlist(&self, id: &str, uris: Vec<String>) -> BoxFuture<SpotifyResult<()>>;
fn remove_from_playlist(&self, id: &str, uris: Vec<String>) -> BoxFuture<SpotifyResult<()>>;
fn search(
&self,
query: &str,
offset: usize,
limit: usize,
) -> BoxFuture<SpotifyResult<SearchResults>>;
fn get_artist_albums(
&self,
id: &str,
offset: usize,
limit: usize,
) -> BoxFuture<SpotifyResult<Vec<AlbumDescription>>>;
fn get_user(&self, id: &str) -> BoxFuture<SpotifyResult<UserDescription>>;
fn get_user_playlists(
&self,
id: &str,
offset: usize,
limit: usize,
) -> BoxFuture<SpotifyResult<Vec<PlaylistDescription>>>;
fn update_token(&self, token: String);
}
enum SpotCacheKey<'a> {
SavedAlbums(usize, usize),
SavedPlaylists(usize, usize),
Album(&'a str),
AlbumLiked(&'a str),
AlbumTracks(&'a str, usize, usize),
Playlist(&'a str),
PlaylistTracks(&'a str, usize, usize),
ArtistAlbums(&'a str, usize, usize),
Artist(&'a str),
ArtistTopTracks(&'a str),
User(&'a str),
UserPlaylists(&'a str, usize, usize),
}
impl<'a> SpotCacheKey<'a> {
fn into_raw(self) -> String {
match self {
Self::SavedAlbums(offset, limit) => format!("me_albums_{}_{}.json", offset, limit),
Self::SavedPlaylists(offset, limit) => {
format!("me_playlists_{}_{}.json", offset, limit)
}
Self::Album(id) => format!("album_{}.json", id),
Self::AlbumTracks(id, offset, limit) => {
format!("album_item_{}_{}_{}.json", id, offset, limit)
}
Self::AlbumLiked(id) => format!("album_liked_{}.json", id),
Self::Playlist(id) => format!("playlist_{}.json", id),
Self::PlaylistTracks(id, offset, limit) => {
format!("playlist_item_{}_{}_{}.json", id, offset, limit)
}
Self::ArtistAlbums(id, offset, limit) => {
format!("artist_albums_{}_{}_{}.json", id, offset, limit)
}
Self::Artist(id) => format!("artist_{}.json", id),
Self::ArtistTopTracks(id) => format!("artist_top_tracks_{}.json", id),
Self::User(id) => format!("user_{}.json", id),
Self::UserPlaylists(id, offset, limit) => {
format!("user_playlists_{}_{}_{}.json", id, offset, limit)
}
}
}
}
pub struct CachedSpotifyClient {
client: SpotifyClient,
cache: CacheManager,
}
impl CachedSpotifyClient {
pub fn new() -> CachedSpotifyClient {
CachedSpotifyClient {
client: SpotifyClient::new(),
cache: CacheManager::new(&["spot/net"]).unwrap(),
}
}
fn default_cache_policy(&self) -> CachePolicy {
if self.client.has_token() {
CachePolicy::Default
} else {
CachePolicy::IgnoreExpiry
}
}
async fn wrap_write<T, O, F>(write: &F, etag: Option<String>) -> SpotifyResult<FetchResult>
where
O: Future<Output = SpotifyResult<SpotifyResponse<T>>>,
F: Fn(Option<String>) -> O,
{
write(etag)
.map(|r| {
let SpotifyResponse {
kind,
max_age,
etag,
} = r?;
let expiry = CacheExpiry::expire_in_seconds(u64::max(max_age, 10), etag);
SpotifyResult::Ok(match kind {
SpotifyResponseKind::Ok(content, _) => {
FetchResult::Modified(content.into_bytes(), expiry)
}
SpotifyResponseKind::NotModified => FetchResult::NotModified(expiry),
})
})
.await
}
async fn cache_get_or_write<T, O, F>(
&self,
key: SpotCacheKey<'_>,
cache_policy: Option<CachePolicy>,
write: F,
) -> SpotifyResult<T>
where
O: Future<Output = SpotifyResult<SpotifyResponse<T>>>,
F: Fn(Option<String>) -> O,
T: DeserializeOwned,
{
let write = &write;
let cache_key = format!("spot/net/{}", key.into_raw());
let raw = self
.cache
.get_or_write(
&cache_key,
cache_policy.unwrap_or_else(|| self.default_cache_policy()),
|etag| Self::wrap_write(write, etag),
)
.await?;
let result = from_slice::<T>(&raw);
match result {
Ok(t) => Ok(t),
// parsing failed: cache is likely invalid, request again, ignoring cache
Err(e) => {
dbg!(&cache_key, e);
let new_raw = self
.cache
.get_or_write(&cache_key, CachePolicy::IgnoreCached, |etag| {
Self::wrap_write(write, etag)
})
.await?;
Ok(from_slice::<T>(&new_raw)?)
}
}
}
}
impl SpotifyApiClient for CachedSpotifyClient {
fn update_token(&self, new_token: String) {
self.client.update_token(new_token)
}
fn get_saved_albums(
&self,
offset: usize,
limit: usize,
) -> BoxFuture<SpotifyResult<Vec<AlbumDescription>>> {
Box::pin(async move {
let page = self
.cache_get_or_write(SpotCacheKey::SavedAlbums(offset, limit), None, |etag| {
self.client
.get_saved_albums(offset, limit)
.etag(etag)
.send()
})
.await?;
let albums = page
.into_iter()
.map(|saved| saved.album.into())
.collect::<Vec<AlbumDescription>>();
Ok(albums)
})
}
fn get_saved_playlists(
&self,
offset: usize,
limit: usize,
) -> BoxFuture<SpotifyResult<Vec<PlaylistDescription>>> {
Box::pin(async move {
let page = self
.cache_get_or_write(SpotCacheKey::SavedPlaylists(offset, limit), None, |etag| {
self.client
.get_saved_playlists(offset, limit)
.etag(etag)
.send()
})
.await?;
let albums = page
.into_iter()
.map(|playlist| playlist.into())
.collect::<Vec<PlaylistDescription>>();
Ok(albums)
})
}
fn add_to_playlist(&self, id: &str, uris: Vec<String>) -> BoxFuture<SpotifyResult<()>> {
let id = id.to_owned();
Box::pin(async move {
self.cache
.set_expired_pattern("spot/net", &_playlist_cache(&id))
.await
.unwrap_or(());
self.client
.add_to_playlist(&id, uris)
.send_no_response()
.await?;
Ok(())
})
}
fn remove_from_playlist(&self, id: &str, uris: Vec<String>) -> BoxFuture<SpotifyResult<()>> {
let id = id.to_owned();
Box::pin(async move {
self.cache
.set_expired_pattern("spot/net", &_playlist_cache(&id))
.await
.unwrap_or(());
self.client
.remove_from_playlist(&id, uris)
.send_no_response()
.await?;
Ok(())
})
}
fn get_album(&self, id: &str) -> BoxFuture<SpotifyResult<AlbumFullDescription>> {
let id = id.to_owned();
Box::pin(async move {
let album = self.cache_get_or_write(SpotCacheKey::Album(&id), None, |etag| {
self.client.get_album(&id).etag(etag).send()
});
let liked = self.cache_get_or_write(
SpotCacheKey::AlbumLiked(&id),
Some(if self.client.has_token() {
CachePolicy::Revalidate
} else {
CachePolicy::IgnoreExpiry
}),
|etag| self.client.is_album_saved(&id).etag(etag).send(),
);
let (album, liked) = join!(album, liked);
let mut album: AlbumFullDescription = album?.into();
album.description.is_liked = liked?[0];
Ok(album)
})
}
fn save_album(&self, id: &str) -> BoxFuture<SpotifyResult<AlbumDescription>> {
let id = id.to_owned();
Box::pin(async move {
self.cache
.set_expired_pattern("spot/net", &*ME_ALBUMS_CACHE)
.await
.unwrap_or(());
self.client.save_album(&id).send_no_response().await?;
self.get_album(&id[..]).await.map(|a| a.description)
})
}
fn remove_saved_album(&self, id: &str) -> BoxFuture<SpotifyResult<()>> {
let id = id.to_owned();
Box::pin(async move {
self.cache
.set_expired_pattern("spot/net", &*ME_ALBUMS_CACHE)
.await
.unwrap_or(());
self.client.remove_saved_album(&id).send_no_response().await
})
}
fn get_album_tracks(
&self,
id: &str,
offset: usize,
limit: usize,
) -> BoxFuture<SpotifyResult<SongBatch>> {
let id = id.to_owned();
Box::pin(async move {
let album = self.cache_get_or_write(
SpotCacheKey::Album(&id),
Some(CachePolicy::IgnoreExpiry),
|etag| self.client.get_album(&id).etag(etag).send(),
);
let songs = self.cache_get_or_write(
SpotCacheKey::AlbumTracks(&id, offset, limit),
None,
|etag| {
self.client
.get_album_tracks(&id, offset, limit)
.etag(etag)
.send()
},
);
let (album, songs) = join!(album, songs);
Ok((songs?, &album?.album).into())
})
}
fn get_playlist(&self, id: &str) -> BoxFuture<SpotifyResult<PlaylistDescription>> {
let id = id.to_owned();
Box::pin(async move {
let playlist = self
.cache_get_or_write(SpotCacheKey::Playlist(&id), None, |etag| {
self.client.get_playlist(&id).etag(etag).send()
})
.await?;
Ok(playlist.into())
})
}
fn get_playlist_tracks(
&self,
id: &str,
offset: usize,
limit: usize,
) -> BoxFuture<SpotifyResult<SongBatch>> {
let id = id.to_owned();
Box::pin(async move {
let songs = self
.cache_get_or_write(
SpotCacheKey::PlaylistTracks(&id, offset, limit),
None,
|etag| {
self.client
.get_playlist_tracks(&id, offset, limit)
.etag(etag)
.send()
},
)
.await?;
Ok(songs.into())
})
}
fn get_artist_albums(
&self,
id: &str,
offset: usize,
limit: usize,
) -> BoxFuture<SpotifyResult<Vec<AlbumDescription>>> {
let id = id.to_owned();
Box::pin(async move {
let albums = self
.cache_get_or_write(
SpotCacheKey::ArtistAlbums(&id, offset, limit),
None,
|etag| {
self.client
.get_artist_albums(&id, offset, limit)
.etag(etag)
.send()
},
)
.await?;
let albums = albums
.into_iter()
.map(|a| a.into())
.collect::<Vec<AlbumDescription>>();
Ok(albums)
})
}
fn get_artist(&self, id: &str) -> BoxFuture<Result<ArtistDescription, SpotifyApiError>> {
let id = id.to_owned();
Box::pin(async move {
let artist = self.cache_get_or_write(SpotCacheKey::Artist(&id), None, |etag| {
self.client.get_artist(&id).etag(etag).send()
});
let albums = self.get_artist_albums(&id, 0, 20);
let top_tracks =
self.cache_get_or_write(SpotCacheKey::ArtistTopTracks(&id), None, |etag| {
self.client.get_artist_top_tracks(&id).etag(etag).send()
});
let (artist, albums, top_tracks) = join!(artist, albums, top_tracks);
let artist = artist?;
let result = ArtistDescription {
id: artist.id,
name: artist.name,
albums: albums?,
top_tracks: top_tracks?.into(),
};
Ok(result)
})
}
fn search(
&self,
query: &str,
offset: usize,
limit: usize,
) -> BoxFuture<SpotifyResult<SearchResults>> {
let query = query.to_owned();
Box::pin(async move {
let results = self
.client
.search(query, offset, limit)
.send()
.await?
.deserialize()
.ok_or(SpotifyApiError::NoContent)?;
let albums = results
.albums
.unwrap_or_default()
.into_iter()
.map(|saved| saved.into())
.collect::<Vec<AlbumDescription>>();
let artists = results
.artists
.unwrap_or_default()
.into_iter()
.map(|saved| saved.into())
.collect::<Vec<ArtistSummary>>();
Ok(SearchResults { albums, artists })
})
}
fn get_user_playlists(
&self,
id: &str,
offset: usize,
limit: usize,
) -> BoxFuture<SpotifyResult<Vec<PlaylistDescription>>> {
let id = id.to_owned();
Box::pin(async move {
let playlists = self
.cache_get_or_write(
SpotCacheKey::UserPlaylists(&id, offset, limit),
None,
|etag| {
self.client
.get_user_playlists(&id, offset, limit)
.etag(etag)
.send()
},
)
.await?;
let playlists = playlists
.into_iter()
.map(|a| a.into())
.collect::<Vec<PlaylistDescription>>();
Ok(playlists)
})
}
fn get_user(&self, id: &str) -> BoxFuture<Result<UserDescription, SpotifyApiError>> {
let id = id.to_owned();
Box::pin(async move {
let user = self.cache_get_or_write(SpotCacheKey::User(&id), None, |etag| {
self.client.get_user(&id).etag(etag).send()
});
let playlists = self.get_user_playlists(&id, 0, 30);
let (user, playlists) = join!(user, playlists);
let user = user?;
let result = UserDescription {
id: user.id,
name: user.display_name,
playlists: playlists?,
};
Ok(result)
})
}
}
#[cfg(test)]
pub mod tests {
use crate::api::api_models::*;
#[test]
fn test_search_query() {
let query = SearchQuery {
query: "test".to_string(),
types: vec![SearchType::Album, SearchType::Artist],
limit: 5,
offset: 0,
};
assert_eq!(
query.into_query_string(),
"type=album,artist&q=test&offset=0&limit=5&market=from_token"
);
}
#[test]
fn test_search_query_spaces_and_stuff() {
let query = SearchQuery {
query: "test??? wow".to_string(),
types: vec![SearchType::Album],
limit: 5,
offset: 0,
};
assert_eq!(
query.into_query_string(),
"type=album&q=test+wow&offset=0&limit=5&market=from_token"
);
}
#[test]
fn test_search_query_encoding() {
let query = SearchQuery {
query: "кириллица".to_string(),
types: vec![SearchType::Album],
limit: 5,
offset: 0,
};
assert_eq!(query.into_query_string(), "type=album&q=%D0%BA%D0%B8%D1%80%D0%B8%D0%BB%D0%BB%D0%B8%D1%86%D0%B0&offset=0&limit=5&market=from_token");
}
}
| 30.004739 | 152 | 0.495551 |
22955fa94dc87afd302a83e65bab8467934dcf3a | 7,953 | //use std::collections::HashMap;
use std::convert::TryFrom;
use std::fmt;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use std::path::Path;
pub trait SequenceCollection {
type SeqType;
type CollectionType;
fn from_fasta(fasta: File) -> Self::CollectionType;
fn new() -> Self::CollectionType;
fn seqs(&self) -> &Vec<Self::SeqType>;
fn into_seqs(self) -> Vec<Self::SeqType>;
fn nseqs(&self) -> usize;
fn to_fasta<P>(&self, out_fasta: P)
where
P: AsRef<Path>;
//fn header_filter_ref(self, header_vector: Vec<String>) -> Vec<&Self::SeqType>;
}
pub trait Sequence {
type SeqType;
fn write_fasta(&self, path: &str) {}
fn complement_bytes(&self) -> Self::SeqType;
fn complement_rusty(&self) -> Self::SeqType;
fn reverse(&self) -> Self::SeqType;
fn revcomp(&self) -> Self::SeqType;
fn orfs(&self) -> ();
}
pub enum Nucleotide {
A,
T,
C,
G,
U,
N,
}
impl Nucleotide {
fn complement(self) -> Nucleotide {
match self {
Nucleotide::A => Nucleotide::T,
Nucleotide::T => Nucleotide::A,
Nucleotide::G => Nucleotide::C,
Nucleotide::C => Nucleotide::G,
Nucleotide::U => Nucleotide::A,
Nucleotide::N => Nucleotide::N,
}
}
}
impl Into<u8> for Nucleotide {
fn into(self) -> u8 {
match self {
Nucleotide::A => b'A',
Nucleotide::T => b'T',
Nucleotide::G => b'G',
Nucleotide::C => b'C',
Nucleotide::U => b'U',
Nucleotide::N => b'N',
}
}
}
impl TryFrom<u8> for Nucleotide {
type Error = &'static str;
fn try_from(byte: u8) -> Result<Self, Self::Error> {
match byte {
b'A' | b'a' => Ok(Nucleotide::A),
b'T' | b't' => Ok(Nucleotide::T),
b'G' | b'g' => Ok(Nucleotide::G),
b'C' | b'c' => Ok(Nucleotide::C),
b'U' | b'u' => Ok(Nucleotide::U),
b'N' | b'n' => Ok(Nucleotide::U),
_ => Err("Invalide nucleotide base in sequence."),
}
}
}
#[derive(Default, Clone)]
pub struct DnaSequence {
pub header: String,
pub sequence: Vec<u8>,
}
impl DnaSequence {
pub fn new(header: String, sequence: Vec<u8>) -> Self {
DnaSequence { header, sequence }
}
}
impl Sequence for DnaSequence {
type SeqType = DnaSequence;
fn write_fasta(&self, path: &str) {
let out = format!("{}", self);
let bytes = out.as_bytes();
let mut buffer = File::create(path).expect("Couldn't create file.");
buffer
.write_all(&bytes)
.expect("Could not write fasta file.");
}
fn complement_bytes(&self) -> DnaSequence {
let pairs = vec![
[b'A', b'T'],
[b'T', b'A'],
[b'C', b'G'],
[b'G', b'C'],
[b'N', b'N'],
];
let complement = self
.sequence
.iter()
.filter_map(|base| pairs.iter().find(|[l, _c]| l == base).map(|[_l, c]| *c))
.collect::<Vec<u8>>();
DnaSequence::new(self.header.clone(), complement)
}
fn complement_rusty(&self) -> DnaSequence {
let complement = self
.sequence
.iter()
.map(|byte| Nucleotide::try_from(*byte).expect("Invalide sequence letter."))
.map(|nucl| nucl.complement().into())
.collect::<Vec<u8>>();
DnaSequence::new(self.header.clone(), complement)
}
fn reverse(&self) -> DnaSequence {
DnaSequence::new(
self.header.clone(),
self.sequence
.iter()
.rev()
.map(|byte| *byte)
.collect::<Vec<u8>>(),
)
}
fn revcomp(&self) -> DnaSequence {
self.reverse().complement_rusty()
}
fn orfs(&self) -> () {
let seq = self.sequence.clone();
let test = seq
.chunks(3)
.map(|c| {
c.iter()
.map(|b| Nucleotide::try_from(*b).expect("bad byte"))
.map(|nucl| format!("{}", nucl))
.collect::<Vec<String>>()
})
.collect::<Vec<Vec<String>>>();
println!("{:?}", test);
}
}
#[derive(Clone)]
pub struct DnaSequenceVector(pub Vec<DnaSequence>);
impl SequenceCollection for DnaSequenceVector {
type SeqType = DnaSequence;
type CollectionType = DnaSequenceVector;
fn new() -> Self {
DnaSequenceVector(Vec::new())
}
fn seqs(&self) -> &Vec<DnaSequence> {
&self.0
}
fn into_seqs(self) -> Vec<DnaSequence> {
self.0
}
fn nseqs(&self) -> usize {
self.0.len()
}
fn from_fasta(fasta: File) -> DnaSequenceVector {
let mut collector: Vec<DnaSequence> = Vec::new();
let _pushall = parse_fasta(fasta).into_iter().for_each(|p| {
collector.push(DnaSequence::new(p.0, p.1.into_bytes().to_ascii_uppercase()))
});
DnaSequenceVector(collector)
}
fn to_fasta<P>(&self, out_fasta: P)
where
P: AsRef<Path>,
{
let mut buffer = File::create(out_fasta).expect("Couldn't create file.");
for s in self.seqs() {
let out = format!("{}\n", s);
let bytes = out.as_bytes();
buffer
.write_all(&bytes)
.expect("Could not write fasta file.");
}
}
/*
fn header_filter_ref(&self, header_vector: Vec<String>) -> Vec<&DnaSequence> {
let ret: Vec<&DnaSequence>;
for s in self.seqs() {
if (s.header in header_vector.iter {
s.ret.push(&s)
}
}
ret
}
*/
}
// Generic fasta parser that doesn't care what kind of sequence is being read
#[derive(Default, Clone)]
pub struct GenericFastaPair(String, String);
pub fn parse_fasta(fasta: File) -> Vec<GenericFastaPair> {
let mut buffer = BufReader::new(fasta);
let mut collector: Vec<GenericFastaPair> = Vec::new();
let mut pair = GenericFastaPair::default();
loop {
let mut line = String::new();
let bytes = buffer.read_line(&mut line).unwrap();
if bytes == 0 {
collector.push(pair.clone());
break;
}
line = line.replace('\n', "");
if line.starts_with(">") {
if pair.1.len() != 0 {
collector.push(pair.clone());
}
pair.0 = line.replace('>', "");
pair.1.clear();
} else {
pair.1.push_str(&line);
}
}
collector
}
// Display implementations
impl fmt::Display for Nucleotide {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let strrep = match self {
Nucleotide::A => "A",
Nucleotide::T => "T",
Nucleotide::G => "G",
Nucleotide::C => "C",
Nucleotide::U => "U",
Nucleotide::N => "N",
};
write!(f, "{}", strrep)
}
}
impl fmt::Display for DnaSequence {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let sequence_string = self
.sequence
.iter()
.map(|byte| Nucleotide::try_from(*byte).expect("Invalid sequence character"))
.map(|n| format!("{}", n))
.collect::<String>();
write!(f, ">{}\n{}", self.header, sequence_string)
}
}
impl fmt::Debug for DnaSequence {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let sequence_string = self
.sequence
.iter()
.map(|byte| Nucleotide::try_from(*byte).expect("Invalid sequence character"))
.map(|n| format!("{}", n))
.collect::<String>();
write!(f, ">{}\n{}", self.header, sequence_string)
}
}
| 30.011321 | 89 | 0.50811 |
4a9875e55adea85da70c1b2b8166c204f54160e4 | 1,435 | #[test]
fn absolute_layout_justify_content_center() {
let layout = stretch::node::Node::new(
stretch::style::Style {
justify_content: stretch::style::JustifyContent::Center,
size: stretch::geometry::Size {
width: stretch::style::Dimension::Points(110f32),
height: stretch::style::Dimension::Points(100f32),
..Default::default()
},
..Default::default()
},
vec![&stretch::node::Node::new(
stretch::style::Style {
position_type: stretch::style::PositionType::Absolute,
size: stretch::geometry::Size {
width: stretch::style::Dimension::Points(60f32),
height: stretch::style::Dimension::Points(40f32),
..Default::default()
},
..Default::default()
},
vec![],
)],
)
.compute_layout(stretch::geometry::Size::undefined())
.unwrap();
assert_eq!(layout.size.width, 110f32);
assert_eq!(layout.size.height, 100f32);
assert_eq!(layout.location.x, 0f32);
assert_eq!(layout.location.y, 0f32);
assert_eq!(layout.children[0usize].size.width, 60f32);
assert_eq!(layout.children[0usize].size.height, 40f32);
assert_eq!(layout.children[0usize].location.x, 25f32);
assert_eq!(layout.children[0usize].location.y, 0f32);
}
| 38.783784 | 70 | 0.565854 |
5066f19cb099502372ed7eace85822784711326b | 2,989 | use super::super::args::BaseArgs;
use super::super::credentials::{Credentials, CredentialsFile};
use super::super::error::TwitterError;
use std::fs;
use std::path::PathBuf;
const HELP: &str = "Initialize your credentials file!\n
Usage: tw init [OPTIONS]
Options:
-c, --credentials <name>
The file name or path to use for the credentials file.
Default: ~/.twitter_credentials.toml
Examples:
Initialize with default file path:
tw init
Initialize with custom file path:
tw init -c /path/to/credentials.toml
";
struct Args {
credentials_file: String,
}
fn parse(args: &BaseArgs) -> Args {
let credentials_file = args.get(
"credentials",
"c",
String::from(".twitter_credentials.toml"),
);
Args { credentials_file }
}
fn help() -> Result<(), TwitterError> {
println!("{}", HELP);
Ok(())
}
fn home_dir() -> PathBuf {
home::home_dir()
.expect("Cannot get your home directory! Please pass the path to your .twitter_credentials.toml manually using -c or --credentials")
}
fn write_empty_credentials(path: &PathBuf) -> Result<(), TwitterError> {
let credentials = Credentials {
api_key: "".to_string(),
api_key_secret: "".to_string(),
access_token: "".to_string(),
access_token_secret: "".to_string(),
handle: "".to_string(),
};
let credentials_file = CredentialsFile {
default: credentials,
};
let contents = toml::to_string(&credentials_file)?;
match fs::write(path, contents) {
Ok(_) => {
println!(
"✅ Credentials file succesfully initialized. Please open {:?} and fill in the values",
&path
);
Ok(())
}
Err(e) => {
println!("Could not initialize credentials file!");
println!("Please ensure the credentials file path {:?} is a valid relative or absolute path name.", &path);
Err(TwitterError::Io(e))
}
}
}
pub fn execute(base_args: &BaseArgs) -> Result<(), TwitterError> {
if base_args.is_requesting_help() {
return help();
}
let args = parse(&base_args);
let mut path = PathBuf::from(home_dir());
path.push(args.credentials_file);
match fs::canonicalize(&path) {
Ok(_) => match fs::read_to_string(&path) {
Ok(contents) if contents != "" => {
println!(
"🤨 Credentials file {:?} already exists and is non-empty!",
&path
);
Ok(())
}
Ok(_) => write_empty_credentials(&path),
Err(e) => {
println!("Could not initialize credentials file!");
println!("Please ensure the credentials file path {:?} is a valid relative or absolute path name.", &path);
Err(TwitterError::Io(e))
}
},
Err(_) => write_empty_credentials(&path),
}
}
| 29.89 | 140 | 0.573101 |
2f470a83cdc31c4d6b93a65f4fb12b78770a3ba7 | 17,332 | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Rational numbers
use std::cmp;
use std::from_str::FromStr;
use std::num::{Zero,One,ToStrRadix,FromStrRadix,Round};
use super::bigint::BigInt;
/// Represents the ratio between 2 numbers.
#[deriving(Clone)]
#[allow(missing_doc)]
pub struct Ratio<T> {
priv numer: T,
priv denom: T
}
/// Alias for a `Ratio` of machine-sized integers.
pub type Rational = Ratio<int>;
pub type Rational32 = Ratio<i32>;
pub type Rational64 = Ratio<i64>;
/// Alias for arbitrary precision rationals.
pub type BigRational = Ratio<BigInt>;
impl<T: Clone + Integer + Ord>
Ratio<T> {
/// Create a ratio representing the integer `t`.
#[inline]
pub fn from_integer(t: T) -> Ratio<T> {
Ratio::new_raw(t, One::one())
}
/// Create a ratio without checking for `denom == 0` or reducing.
#[inline]
pub fn new_raw(numer: T, denom: T) -> Ratio<T> {
Ratio { numer: numer, denom: denom }
}
/// Create a new Ratio. Fails if `denom == 0`.
#[inline]
pub fn new(numer: T, denom: T) -> Ratio<T> {
if denom == Zero::zero() {
fail!("denominator == 0");
}
let mut ret = Ratio::new_raw(numer, denom);
ret.reduce();
ret
}
/// Convert to an integer.
#[inline]
pub fn to_integer(&self) -> T {
self.trunc().numer
}
/// Gets an immutable reference to the numerator.
#[inline]
pub fn numer<'a>(&'a self) -> &'a T {
&self.numer
}
/// Gets an immutable reference to the denominator.
#[inline]
pub fn denom<'a>(&'a self) -> &'a T {
&self.denom
}
/// Return true if the rational number is an integer (denominator is 1).
#[inline]
pub fn is_integer(&self) -> bool {
self.denom == One::one()
}
/// Put self into lowest terms, with denom > 0.
fn reduce(&mut self) {
let g : T = self.numer.gcd(&self.denom);
// FIXME(#6050): overloaded operators force moves with generic types
// self.numer /= g;
self.numer = self.numer / g;
// FIXME(#6050): overloaded operators force moves with generic types
// self.denom /= g;
self.denom = self.denom / g;
// keep denom positive!
if self.denom < Zero::zero() {
self.numer = -self.numer;
self.denom = -self.denom;
}
}
/// Return a `reduce`d copy of self.
fn reduced(&self) -> Ratio<T> {
let mut ret = self.clone();
ret.reduce();
ret
}
}
/* Comparisons */
// comparing a/b and c/d is the same as comparing a*d and b*c, so we
// abstract that pattern. The following macro takes a trait and either
// a comma-separated list of "method name -> return value" or just
// "method name" (return value is bool in that case)
macro_rules! cmp_impl {
(impl $imp:ident, $($method:ident),+) => {
cmp_impl!(impl $imp, $($method -> bool),+)
};
// return something other than a Ratio<T>
(impl $imp:ident, $($method:ident -> $res:ty),+) => {
impl<T: Mul<T,T> + $imp> $imp for Ratio<T> {
$(
#[inline]
fn $method(&self, other: &Ratio<T>) -> $res {
(self.numer * other.denom). $method (&(self.denom*other.numer))
}
)+
}
};
}
cmp_impl!(impl Eq, eq, ne)
cmp_impl!(impl TotalEq, equals)
cmp_impl!(impl Ord, lt, gt, le, ge)
cmp_impl!(impl TotalOrd, cmp -> cmp::Ordering)
impl<T: Clone + Integer + Ord> Orderable for Ratio<T> {
#[inline]
fn min(&self, other: &Ratio<T>) -> Ratio<T> {
if *self < *other { self.clone() } else { other.clone() }
}
#[inline]
fn max(&self, other: &Ratio<T>) -> Ratio<T> {
if *self > *other { self.clone() } else { other.clone() }
}
#[inline]
fn clamp(&self, mn: &Ratio<T>, mx: &Ratio<T>) -> Ratio<T> {
if *self > *mx { mx.clone()} else
if *self < *mn { mn.clone() } else { self.clone() }
}
}
/* Arithmetic */
// a/b * c/d = (a*c)/(b*d)
impl<T: Clone + Integer + Ord>
Mul<Ratio<T>,Ratio<T>> for Ratio<T> {
#[inline]
fn mul(&self, rhs: &Ratio<T>) -> Ratio<T> {
Ratio::new(self.numer * rhs.numer, self.denom * rhs.denom)
}
}
// (a/b) / (c/d) = (a*d)/(b*c)
impl<T: Clone + Integer + Ord>
Div<Ratio<T>,Ratio<T>> for Ratio<T> {
#[inline]
fn div(&self, rhs: &Ratio<T>) -> Ratio<T> {
Ratio::new(self.numer * rhs.denom, self.denom * rhs.numer)
}
}
// Abstracts the a/b `op` c/d = (a*d `op` b*d) / (b*d) pattern
macro_rules! arith_impl {
(impl $imp:ident, $method:ident) => {
impl<T: Clone + Integer + Ord>
$imp<Ratio<T>,Ratio<T>> for Ratio<T> {
#[inline]
fn $method(&self, rhs: &Ratio<T>) -> Ratio<T> {
Ratio::new((self.numer * rhs.denom).$method(&(self.denom * rhs.numer)),
self.denom * rhs.denom)
}
}
}
}
// a/b + c/d = (a*d + b*c)/(b*d
arith_impl!(impl Add, add)
// a/b - c/d = (a*d - b*c)/(b*d)
arith_impl!(impl Sub, sub)
// a/b % c/d = (a*d % b*c)/(b*d)
arith_impl!(impl Rem, rem)
impl<T: Clone + Integer + Ord>
Neg<Ratio<T>> for Ratio<T> {
#[inline]
fn neg(&self) -> Ratio<T> {
Ratio::new_raw(-self.numer, self.denom.clone())
}
}
/* Constants */
impl<T: Clone + Integer + Ord>
Zero for Ratio<T> {
#[inline]
fn zero() -> Ratio<T> {
Ratio::new_raw(Zero::zero(), One::one())
}
#[inline]
fn is_zero(&self) -> bool {
*self == Zero::zero()
}
}
impl<T: Clone + Integer + Ord>
One for Ratio<T> {
#[inline]
fn one() -> Ratio<T> {
Ratio::new_raw(One::one(), One::one())
}
}
impl<T: Clone + Integer + Ord>
Num for Ratio<T> {}
/* Utils */
impl<T: Clone + Integer + Ord>
Round for Ratio<T> {
fn floor(&self) -> Ratio<T> {
if *self < Zero::zero() {
Ratio::from_integer((self.numer - self.denom + One::one()) / self.denom)
} else {
Ratio::from_integer(self.numer / self.denom)
}
}
fn ceil(&self) -> Ratio<T> {
if *self < Zero::zero() {
Ratio::from_integer(self.numer / self.denom)
} else {
Ratio::from_integer((self.numer + self.denom - One::one()) / self.denom)
}
}
#[inline]
fn round(&self) -> Ratio<T> {
if *self < Zero::zero() {
Ratio::from_integer((self.numer - self.denom + One::one()) / self.denom)
} else {
Ratio::from_integer((self.numer + self.denom - One::one()) / self.denom)
}
}
#[inline]
fn trunc(&self) -> Ratio<T> {
Ratio::from_integer(self.numer / self.denom)
}
fn fract(&self) -> Ratio<T> {
Ratio::new_raw(self.numer % self.denom, self.denom.clone())
}
}
impl<T: Clone + Integer + Ord> Fractional for Ratio<T> {
#[inline]
fn recip(&self) -> Ratio<T> {
Ratio::new_raw(self.denom.clone(), self.numer.clone())
}
}
/* String conversions */
impl<T: ToStr> ToStr for Ratio<T> {
/// Renders as `numer/denom`.
fn to_str(&self) -> ~str {
format!("{}/{}", self.numer.to_str(), self.denom.to_str())
}
}
impl<T: ToStrRadix> ToStrRadix for Ratio<T> {
/// Renders as `numer/denom` where the numbers are in base `radix`.
fn to_str_radix(&self, radix: uint) -> ~str {
format!("{}/{}", self.numer.to_str_radix(radix), self.denom.to_str_radix(radix))
}
}
impl<T: FromStr + Clone + Integer + Ord>
FromStr for Ratio<T> {
/// Parses `numer/denom`.
fn from_str(s: &str) -> Option<Ratio<T>> {
let split: ~[&str] = s.splitn_iter('/', 1).collect();
if split.len() < 2 {
return None
}
let a_option: Option<T> = FromStr::from_str(split[0]);
do a_option.and_then |a| {
let b_option: Option<T> = FromStr::from_str(split[1]);
do b_option.and_then |b| {
Some(Ratio::new(a.clone(), b.clone()))
}
}
}
}
impl<T: FromStrRadix + Clone + Integer + Ord>
FromStrRadix for Ratio<T> {
/// Parses `numer/denom` where the numbers are in base `radix`.
fn from_str_radix(s: &str, radix: uint) -> Option<Ratio<T>> {
let split: ~[&str] = s.splitn_iter('/', 1).collect();
if split.len() < 2 {
None
} else {
let a_option: Option<T> = FromStrRadix::from_str_radix(split[0],
radix);
do a_option.and_then |a| {
let b_option: Option<T> =
FromStrRadix::from_str_radix(split[1], radix);
do b_option.and_then |b| {
Some(Ratio::new(a.clone(), b.clone()))
}
}
}
}
}
#[cfg(test)]
mod test {
use super::*;
use std::num::{Zero,One,FromStrRadix,FromPrimitive};
use std::from_str::FromStr;
pub static _0 : Rational = Ratio { numer: 0, denom: 1};
pub static _1 : Rational = Ratio { numer: 1, denom: 1};
pub static _2: Rational = Ratio { numer: 2, denom: 1};
pub static _1_2: Rational = Ratio { numer: 1, denom: 2};
pub static _3_2: Rational = Ratio { numer: 3, denom: 2};
pub static _neg1_2: Rational = Ratio { numer: -1, denom: 2};
pub fn to_big(n: Rational) -> BigRational {
Ratio::new(
FromPrimitive::from_int(n.numer).unwrap(),
FromPrimitive::from_int(n.denom).unwrap()
)
}
#[test]
fn test_test_constants() {
// check our constants are what Ratio::new etc. would make.
assert_eq!(_0, Zero::zero());
assert_eq!(_1, One::one());
assert_eq!(_2, Ratio::from_integer(2));
assert_eq!(_1_2, Ratio::new(1,2));
assert_eq!(_3_2, Ratio::new(3,2));
assert_eq!(_neg1_2, Ratio::new(-1,2));
}
#[test]
fn test_new_reduce() {
let one22 = Ratio::new(2i,2);
assert_eq!(one22, One::one());
}
#[test]
#[should_fail]
fn test_new_zero() {
let _a = Ratio::new(1,0);
}
#[test]
fn test_cmp() {
assert!(_0 == _0 && _1 == _1);
assert!(_0 != _1 && _1 != _0);
assert!(_0 < _1 && !(_1 < _0));
assert!(_1 > _0 && !(_0 > _1));
assert!(_0 <= _0 && _1 <= _1);
assert!(_0 <= _1 && !(_1 <= _0));
assert!(_0 >= _0 && _1 >= _1);
assert!(_1 >= _0 && !(_0 >= _1));
}
#[test]
fn test_to_integer() {
assert_eq!(_0.to_integer(), 0);
assert_eq!(_1.to_integer(), 1);
assert_eq!(_2.to_integer(), 2);
assert_eq!(_1_2.to_integer(), 0);
assert_eq!(_3_2.to_integer(), 1);
assert_eq!(_neg1_2.to_integer(), 0);
}
#[test]
fn test_numer() {
assert_eq!(_0.numer(), &0);
assert_eq!(_1.numer(), &1);
assert_eq!(_2.numer(), &2);
assert_eq!(_1_2.numer(), &1);
assert_eq!(_3_2.numer(), &3);
assert_eq!(_neg1_2.numer(), &(-1));
}
#[test]
fn test_denom() {
assert_eq!(_0.denom(), &1);
assert_eq!(_1.denom(), &1);
assert_eq!(_2.denom(), &1);
assert_eq!(_1_2.denom(), &2);
assert_eq!(_3_2.denom(), &2);
assert_eq!(_neg1_2.denom(), &2);
}
#[test]
fn test_is_integer() {
assert!(_0.is_integer());
assert!(_1.is_integer());
assert!(_2.is_integer());
assert!(!_1_2.is_integer());
assert!(!_3_2.is_integer());
assert!(!_neg1_2.is_integer());
}
mod arith {
use super::*;
use super::super::*;
#[test]
fn test_add() {
fn test(a: Rational, b: Rational, c: Rational) {
assert_eq!(a + b, c);
assert_eq!(to_big(a) + to_big(b), to_big(c));
}
test(_1, _1_2, _3_2);
test(_1, _1, _2);
test(_1_2, _3_2, _2);
test(_1_2, _neg1_2, _0);
}
#[test]
fn test_sub() {
fn test(a: Rational, b: Rational, c: Rational) {
assert_eq!(a - b, c);
assert_eq!(to_big(a) - to_big(b), to_big(c))
}
test(_1, _1_2, _1_2);
test(_3_2, _1_2, _1);
test(_1, _neg1_2, _3_2);
}
#[test]
fn test_mul() {
fn test(a: Rational, b: Rational, c: Rational) {
assert_eq!(a * b, c);
assert_eq!(to_big(a) * to_big(b), to_big(c))
}
test(_1, _1_2, _1_2);
test(_1_2, _3_2, Ratio::new(3,4));
test(_1_2, _neg1_2, Ratio::new(-1, 4));
}
#[test]
fn test_div() {
fn test(a: Rational, b: Rational, c: Rational) {
assert_eq!(a / b, c);
assert_eq!(to_big(a) / to_big(b), to_big(c))
}
test(_1, _1_2, _2);
test(_3_2, _1_2, _1 + _2);
test(_1, _neg1_2, _neg1_2 + _neg1_2 + _neg1_2 + _neg1_2);
}
#[test]
fn test_rem() {
fn test(a: Rational, b: Rational, c: Rational) {
assert_eq!(a % b, c);
assert_eq!(to_big(a) % to_big(b), to_big(c))
}
test(_3_2, _1, _1_2);
test(_2, _neg1_2, _0);
test(_1_2, _2, _1_2);
}
#[test]
fn test_neg() {
fn test(a: Rational, b: Rational) {
assert_eq!(-a, b);
assert_eq!(-to_big(a), to_big(b))
}
test(_0, _0);
test(_1_2, _neg1_2);
test(-_1, _1);
}
#[test]
fn test_zero() {
assert_eq!(_0 + _0, _0);
assert_eq!(_0 * _0, _0);
assert_eq!(_0 * _1, _0);
assert_eq!(_0 / _neg1_2, _0);
assert_eq!(_0 - _0, _0);
}
#[test]
#[should_fail]
fn test_div_0() {
let _a = _1 / _0;
}
}
#[test]
fn test_round() {
assert_eq!(_1_2.ceil(), _1);
assert_eq!(_1_2.floor(), _0);
assert_eq!(_1_2.round(), _1);
assert_eq!(_1_2.trunc(), _0);
assert_eq!(_neg1_2.ceil(), _0);
assert_eq!(_neg1_2.floor(), -_1);
assert_eq!(_neg1_2.round(), -_1);
assert_eq!(_neg1_2.trunc(), _0);
assert_eq!(_1.ceil(), _1);
assert_eq!(_1.floor(), _1);
assert_eq!(_1.round(), _1);
assert_eq!(_1.trunc(), _1);
}
#[test]
fn test_fract() {
assert_eq!(_1.fract(), _0);
assert_eq!(_neg1_2.fract(), _neg1_2);
assert_eq!(_1_2.fract(), _1_2);
assert_eq!(_3_2.fract(), _1_2);
}
#[test]
fn test_recip() {
assert_eq!(_1 * _1.recip(), _1);
assert_eq!(_2 * _2.recip(), _1);
assert_eq!(_1_2 * _1_2.recip(), _1);
assert_eq!(_3_2 * _3_2.recip(), _1);
assert_eq!(_neg1_2 * _neg1_2.recip(), _1);
}
#[test]
fn test_to_from_str() {
fn test(r: Rational, s: ~str) {
assert_eq!(FromStr::from_str(s), Some(r));
assert_eq!(r.to_str(), s);
}
test(_1, ~"1/1");
test(_0, ~"0/1");
test(_1_2, ~"1/2");
test(_3_2, ~"3/2");
test(_2, ~"2/1");
test(_neg1_2, ~"-1/2");
}
#[test]
fn test_from_str_fail() {
fn test(s: &str) {
let rational: Option<Rational> = FromStr::from_str(s);
assert_eq!(rational, None);
}
let xs = ["0 /1", "abc", "", "1/", "--1/2","3/2/1"];
for &s in xs.iter() {
test(s);
}
}
#[test]
fn test_to_from_str_radix() {
fn test(r: Rational, s: ~str, n: uint) {
assert_eq!(FromStrRadix::from_str_radix(s, n), Some(r));
assert_eq!(r.to_str_radix(n), s);
}
fn test3(r: Rational, s: ~str) { test(r, s, 3) }
fn test16(r: Rational, s: ~str) { test(r, s, 16) }
test3(_1, ~"1/1");
test3(_0, ~"0/1");
test3(_1_2, ~"1/2");
test3(_3_2, ~"10/2");
test3(_2, ~"2/1");
test3(_neg1_2, ~"-1/2");
test3(_neg1_2 / _2, ~"-1/11");
test16(_1, ~"1/1");
test16(_0, ~"0/1");
test16(_1_2, ~"1/2");
test16(_3_2, ~"3/2");
test16(_2, ~"2/1");
test16(_neg1_2, ~"-1/2");
test16(_neg1_2 / _2, ~"-1/4");
test16(Ratio::new(13,15), ~"d/f");
test16(_1_2*_1_2*_1_2*_1_2, ~"1/10");
}
#[test]
fn test_from_str_radix_fail() {
fn test(s: &str) {
let radix: Option<Rational> = FromStrRadix::from_str_radix(s, 3);
assert_eq!(radix, None);
}
let xs = ["0 /1", "abc", "", "1/", "--1/2","3/2/1", "3/2"];
for &s in xs.iter() {
test(s);
}
}
}
| 27.7312 | 88 | 0.500577 |
6415ffe8d725fa7fded08769491589776658864c | 1,278 | use bb8::Pool;
use bb8_postgres::PostgresConnectionManager;
use std::str::FromStr;
// Select some static data from a Postgres DB
//
// The simplest way to start the db is using Docker:
// docker run --name gotham-middleware-postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -d postgres
#[tokio::main]
async fn main() {
let config = tokio_postgres::config::Config::from_str(
"postgresql://postgres:mysecretpassword@localhost:5432",
)
.unwrap();
let pg_mgr = PostgresConnectionManager::new(config, tokio_postgres::NoTls);
let pool = match Pool::builder().build(pg_mgr).await {
Ok(pool) => pool,
Err(e) => panic!("builder error: {:?}", e),
};
let _ = pool
.run(|connection| async {
let select = match connection.prepare("SELECT 1").await {
Ok(stmt) => stmt,
Err(e) => return Err((e, connection)),
};
match connection.query_one(&select, &[]).await {
Ok(row) => {
println!("result: {}", row.get::<usize, i32>(0));
Ok(((), connection))
}
Err(e) => Err((e, connection)),
}
})
.await
.map_err(|e| panic!("{:?}", e));
}
| 31.170732 | 110 | 0.546166 |
ccaa0d4e1b1b059de8214d48454ea049d7897eac | 8,374 | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::collections::HashSet;
use std::env;
use std::path::{Path, PathBuf};
use std::fs;
use rustc::hir::def_id::CrateNum;
use rustc::middle::cstore::LibSource;
pub struct RPathConfig<'a> {
pub used_crates: Vec<(CrateNum, LibSource)>,
pub out_filename: PathBuf,
pub is_like_osx: bool,
pub has_rpath: bool,
pub linker_is_gnu: bool,
pub get_install_prefix_lib_path: &'a mut FnMut() -> PathBuf,
}
pub fn get_rpath_flags(config: &mut RPathConfig) -> Vec<String> {
// No rpath on windows
if !config.has_rpath {
return Vec::new();
}
let mut flags = Vec::new();
debug!("preparing the RPATH!");
let libs = config.used_crates.clone();
let libs = libs.into_iter().filter_map(|(_, l)| l.option()).collect::<Vec<_>>();
let rpaths = get_rpaths(config, &libs[..]);
flags.extend_from_slice(&rpaths_to_flags(&rpaths[..]));
// Use DT_RUNPATH instead of DT_RPATH if available
if config.linker_is_gnu {
flags.push("-Wl,--enable-new-dtags".to_string());
}
flags
}
fn rpaths_to_flags(rpaths: &[String]) -> Vec<String> {
let mut ret = Vec::new();
for rpath in rpaths {
ret.push(format!("-Wl,-rpath,{}", &(*rpath)));
}
return ret;
}
fn get_rpaths(config: &mut RPathConfig, libs: &[PathBuf]) -> Vec<String> {
debug!("output: {:?}", config.out_filename.display());
debug!("libs:");
for libpath in libs {
debug!(" {:?}", libpath.display());
}
// Use relative paths to the libraries. Binaries can be moved
// as long as they maintain the relative relationship to the
// crates they depend on.
let rel_rpaths = get_rpaths_relative_to_output(config, libs);
// And a final backup rpath to the global library location.
let fallback_rpaths = vec![get_install_prefix_rpath(config)];
fn log_rpaths(desc: &str, rpaths: &[String]) {
debug!("{} rpaths:", desc);
for rpath in rpaths {
debug!(" {}", *rpath);
}
}
log_rpaths("relative", &rel_rpaths[..]);
log_rpaths("fallback", &fallback_rpaths[..]);
let mut rpaths = rel_rpaths;
rpaths.extend_from_slice(&fallback_rpaths[..]);
// Remove duplicates
let rpaths = minimize_rpaths(&rpaths[..]);
return rpaths;
}
fn get_rpaths_relative_to_output(config: &mut RPathConfig,
libs: &[PathBuf]) -> Vec<String> {
libs.iter().map(|a| get_rpath_relative_to_output(config, a)).collect()
}
fn get_rpath_relative_to_output(config: &mut RPathConfig, lib: &Path) -> String {
// Mac doesn't appear to support $ORIGIN
let prefix = if config.is_like_osx {
"@loader_path"
} else {
"$ORIGIN"
};
let cwd = env::current_dir().unwrap();
let mut lib = fs::canonicalize(&cwd.join(lib)).unwrap_or(cwd.join(lib));
lib.pop();
let mut output = cwd.join(&config.out_filename);
output.pop();
let output = fs::canonicalize(&output).unwrap_or(output);
let relative = path_relative_from(&lib, &output)
.expect(&format!("couldn't create relative path from {:?} to {:?}", output, lib));
// FIXME (#9639): This needs to handle non-utf8 paths
format!("{}/{}", prefix,
relative.to_str().expect("non-utf8 component in path"))
}
// This routine is adapted from the *old* Path's `path_relative_from`
// function, which works differently from the new `relative_from` function.
// In particular, this handles the case on unix where both paths are
// absolute but with only the root as the common directory.
fn path_relative_from(path: &Path, base: &Path) -> Option<PathBuf> {
use std::path::Component;
if path.is_absolute() != base.is_absolute() {
if path.is_absolute() {
Some(PathBuf::from(path))
} else {
None
}
} else {
let mut ita = path.components();
let mut itb = base.components();
let mut comps: Vec<Component> = vec![];
loop {
match (ita.next(), itb.next()) {
(None, None) => break,
(Some(a), None) => {
comps.push(a);
comps.extend(ita.by_ref());
break;
}
(None, _) => comps.push(Component::ParentDir),
(Some(a), Some(b)) if comps.is_empty() && a == b => (),
(Some(a), Some(b)) if b == Component::CurDir => comps.push(a),
(Some(_), Some(b)) if b == Component::ParentDir => return None,
(Some(a), Some(_)) => {
comps.push(Component::ParentDir);
for _ in itb {
comps.push(Component::ParentDir);
}
comps.push(a);
comps.extend(ita.by_ref());
break;
}
}
}
Some(comps.iter().map(|c| c.as_os_str()).collect())
}
}
fn get_install_prefix_rpath(config: &mut RPathConfig) -> String {
let path = (config.get_install_prefix_lib_path)();
let path = env::current_dir().unwrap().join(&path);
// FIXME (#9639): This needs to handle non-utf8 paths
path.to_str().expect("non-utf8 component in rpath").to_string()
}
fn minimize_rpaths(rpaths: &[String]) -> Vec<String> {
let mut set = HashSet::new();
let mut minimized = Vec::new();
for rpath in rpaths {
if set.insert(&rpath[..]) {
minimized.push(rpath.clone());
}
}
minimized
}
#[cfg(all(unix, test))]
mod tests {
use super::{RPathConfig};
use super::{minimize_rpaths, rpaths_to_flags, get_rpath_relative_to_output};
use std::path::{Path, PathBuf};
#[test]
fn test_rpaths_to_flags() {
let flags = rpaths_to_flags(&[
"path1".to_string(),
"path2".to_string()
]);
assert_eq!(flags,
["-Wl,-rpath,path1",
"-Wl,-rpath,path2"]);
}
#[test]
fn test_minimize1() {
let res = minimize_rpaths(&[
"rpath1".to_string(),
"rpath2".to_string(),
"rpath1".to_string()
]);
assert!(res == [
"rpath1",
"rpath2",
]);
}
#[test]
fn test_minimize2() {
let res = minimize_rpaths(&[
"1a".to_string(),
"2".to_string(),
"2".to_string(),
"1a".to_string(),
"4a".to_string(),
"1a".to_string(),
"2".to_string(),
"3".to_string(),
"4a".to_string(),
"3".to_string()
]);
assert!(res == [
"1a",
"2",
"4a",
"3",
]);
}
#[test]
fn test_rpath_relative() {
if cfg!(target_os = "macos") {
let config = &mut RPathConfig {
used_crates: Vec::new(),
has_rpath: true,
is_like_osx: true,
linker_is_gnu: false,
out_filename: PathBuf::from("bin/rustc"),
get_install_prefix_lib_path: &mut || panic!(),
};
let res = get_rpath_relative_to_output(config,
Path::new("lib/libstd.so"));
assert_eq!(res, "@loader_path/../lib");
} else {
let config = &mut RPathConfig {
used_crates: Vec::new(),
out_filename: PathBuf::from("bin/rustc"),
get_install_prefix_lib_path: &mut || panic!(),
has_rpath: true,
is_like_osx: false,
linker_is_gnu: true,
};
let res = get_rpath_relative_to_output(config,
Path::new("lib/libstd.so"));
assert_eq!(res, "$ORIGIN/../lib");
}
}
}
| 31.961832 | 90 | 0.546334 |
23a993ecd1597f3b34243c7c0727fbec1bc94f87 | 2,053 | use std::io::{self, BufRead, Write};
use std::time::Duration;
use url::Url;
use crate::console;
use errors::Result;
/// Wait for user input and return what they typed
fn read_line() -> Result<String> {
let stdin = io::stdin();
let stdin = stdin.lock();
let mut lines = stdin.lines();
lines
.next()
.and_then(|l| l.ok())
.ok_or_else(|| "unable to read from stdin for confirmation".into())
}
/// Ask a yes/no question to the user
pub fn ask_bool(question: &str, default: bool) -> Result<bool> {
print!("{} {}: ", question, if default { "[Y/n]" } else { "[y/N]" });
let _ = io::stdout().flush();
let input = read_line()?;
match &*input {
"y" | "Y" | "yes" | "YES" | "true" => Ok(true),
"n" | "N" | "no" | "NO" | "false" => Ok(false),
"" => Ok(default),
_ => {
println!("Invalid choice: '{}'", input);
ask_bool(question, default)
}
}
}
/// Ask a yes/no question to the user with a timeout
pub async fn ask_bool_timeout(question: &str, default: bool, timeout: Duration) -> Result<bool> {
let (tx, rx) = tokio::sync::oneshot::channel();
let q = question.to_string();
std::thread::spawn(move || {
tx.send(ask_bool(&q, default)).unwrap();
});
match tokio::time::timeout(timeout, rx).await {
Err(_) => {
console::warn("\nWaited too long for response.");
Ok(default)
}
Ok(val) => val.expect("Tokio failed to properly execute"),
}
}
/// Ask a question to the user where they can write a URL
pub fn ask_url(question: &str, default: &str) -> Result<String> {
print!("{} ({}): ", question, default);
let _ = io::stdout().flush();
let input = read_line()?;
match &*input {
"" => Ok(default.to_string()),
_ => match Url::parse(&input) {
Ok(_) => Ok(input),
Err(_) => {
println!("Invalid URL: '{}'", input);
ask_url(question, default)
}
},
}
}
| 28.513889 | 97 | 0.528495 |
9039707b763f9f95f3008c288ac7fe0319938ec5 | 903 | use crate::config::{read, Conf, NuConfig};
use indexmap::IndexMap;
use nu_protocol::Value;
use nu_source::Tag;
use parking_lot::Mutex;
use std::path::{Path, PathBuf};
use std::sync::Arc;
#[derive(Debug)]
pub struct FakeConfig {
pub config: NuConfig,
}
impl Conf for FakeConfig {
fn env(&self) -> Option<Value> {
self.config.env()
}
fn path(&self) -> Option<Value> {
self.config.path()
}
fn reload(&self) {
// no-op
}
}
impl FakeConfig {
pub fn new(config_file: &Path) -> FakeConfig {
let config_file = PathBuf::from(config_file);
let vars = if let Ok(variables) = read(Tag::unknown(), &Some(config_file)) {
variables
} else {
IndexMap::default()
};
FakeConfig {
config: NuConfig {
vars: Arc::new(Mutex::new(vars)),
},
}
}
}
| 20.066667 | 84 | 0.550388 |
fbdc4f395d9ffffb500288f7f45f72d6ccc7c7a0 | 3,952 | use crate::query_builder::limit_clause::{LimitClause, NoLimitClause};
use crate::query_builder::limit_offset_clause::{BoxedLimitOffsetClause, LimitOffsetClause};
use crate::query_builder::offset_clause::{NoOffsetClause, OffsetClause};
use crate::query_builder::{AstPass, IntoBoxedClause, QueryFragment};
use crate::result::QueryResult;
use crate::sqlite::Sqlite;
impl QueryFragment<Sqlite> for LimitOffsetClause<NoLimitClause, NoOffsetClause> {
fn walk_ast(&self, _out: AstPass<Sqlite>) -> QueryResult<()> {
Ok(())
}
}
impl<L> QueryFragment<Sqlite> for LimitOffsetClause<LimitClause<L>, NoOffsetClause>
where
LimitClause<L>: QueryFragment<Sqlite>,
{
fn walk_ast(&self, out: AstPass<Sqlite>) -> QueryResult<()> {
self.limit_clause.walk_ast(out)?;
Ok(())
}
}
impl<O> QueryFragment<Sqlite> for LimitOffsetClause<NoLimitClause, OffsetClause<O>>
where
OffsetClause<O>: QueryFragment<Sqlite>,
{
fn walk_ast(&self, mut out: AstPass<Sqlite>) -> QueryResult<()> {
// Sqlite requires a limit clause in front of any offset clause
// using `LIMIT -1` is the same as not having any limit clause
// https://sqlite.org/lang_select.html
out.push_sql(" LIMIT -1 ");
self.offset_clause.walk_ast(out)?;
Ok(())
}
}
impl<L, O> QueryFragment<Sqlite> for LimitOffsetClause<LimitClause<L>, OffsetClause<O>>
where
LimitClause<L>: QueryFragment<Sqlite>,
OffsetClause<O>: QueryFragment<Sqlite>,
{
fn walk_ast(&self, mut out: AstPass<Sqlite>) -> QueryResult<()> {
self.limit_clause.walk_ast(out.reborrow())?;
self.offset_clause.walk_ast(out.reborrow())?;
Ok(())
}
}
impl<'a> QueryFragment<Sqlite> for BoxedLimitOffsetClause<'a, Sqlite> {
fn walk_ast(&self, mut out: AstPass<Sqlite>) -> QueryResult<()> {
match (self.limit.as_ref(), self.offset.as_ref()) {
(Some(limit), Some(offset)) => {
limit.walk_ast(out.reborrow())?;
offset.walk_ast(out.reborrow())?;
}
(Some(limit), None) => {
limit.walk_ast(out.reborrow())?;
}
(None, Some(offset)) => {
// See the `QueryFragment` implementation for `LimitOffsetClause` for details.
out.push_sql(" LIMIT -1 ");
offset.walk_ast(out.reborrow())?;
}
(None, None) => {}
}
Ok(())
}
}
impl<'a> IntoBoxedClause<'a, Sqlite> for LimitOffsetClause<NoLimitClause, NoOffsetClause> {
type BoxedClause = BoxedLimitOffsetClause<'a, Sqlite>;
fn into_boxed(self) -> Self::BoxedClause {
BoxedLimitOffsetClause {
limit: None,
offset: None,
}
}
}
impl<'a, L> IntoBoxedClause<'a, Sqlite> for LimitOffsetClause<LimitClause<L>, NoOffsetClause>
where
L: QueryFragment<Sqlite> + 'a,
{
type BoxedClause = BoxedLimitOffsetClause<'a, Sqlite>;
fn into_boxed(self) -> Self::BoxedClause {
BoxedLimitOffsetClause {
limit: Some(Box::new(self.limit_clause)),
offset: None,
}
}
}
impl<'a, O> IntoBoxedClause<'a, Sqlite> for LimitOffsetClause<NoLimitClause, OffsetClause<O>>
where
O: QueryFragment<Sqlite> + 'a,
{
type BoxedClause = BoxedLimitOffsetClause<'a, Sqlite>;
fn into_boxed(self) -> Self::BoxedClause {
BoxedLimitOffsetClause {
limit: None,
offset: Some(Box::new(self.offset_clause)),
}
}
}
impl<'a, L, O> IntoBoxedClause<'a, Sqlite> for LimitOffsetClause<LimitClause<L>, OffsetClause<O>>
where
L: QueryFragment<Sqlite> + 'a,
O: QueryFragment<Sqlite> + 'a,
{
type BoxedClause = BoxedLimitOffsetClause<'a, Sqlite>;
fn into_boxed(self) -> Self::BoxedClause {
BoxedLimitOffsetClause {
limit: Some(Box::new(self.limit_clause)),
offset: Some(Box::new(self.offset_clause)),
}
}
}
| 31.870968 | 97 | 0.628289 |
7654d8c440390189fcd282fc445bc9159adaf979 | 137 | // run-rustfix
#[allow(unused_macros)]
macro_rules! foo! { //~ ERROR macro names aren't followed by a `!`
() => {};
}
fn main() {}
| 15.222222 | 66 | 0.576642 |
09c81c394d88878c8cfec9e24613a7ec3dc5281a | 42,605 | //! Full build support for the Skia library, SkiaBindings library and bindings.rs file.
use crate::build_support::{android, cargo, clang, git, ios, vs};
use cc::Build;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::{env, fs};
/// The libraries to link with.
mod lib {
pub const SKIA: &str = "skia";
pub const SKIA_BINDINGS: &str = "skia-bindings";
pub const SKSHAPER: &str = "skshaper";
pub const SKPARAGRAPH: &str = "skparagraph";
}
/// Feature identifiers define the additional configuration parts of the binaries to download.
mod feature_id {
pub const VULKAN: &str = "vulkan";
pub const SVG: &str = "svg";
pub const SHAPER: &str = "shaper";
pub const TEXTLAYOUT: &str = "textlayout";
}
/// The defaults for the Skia build configuration.
impl Default for BuildConfiguration {
fn default() -> Self {
// m74: if we don't build the particles or the skottie library on macOS, the build fails with
// for example:
// [763/867] link libparticles.a
// FAILED: libparticles.a
let all_skia_libs = {
match cargo::target().as_strs() {
(_, "apple", "darwin", _) => true,
(_, "apple", "ios", _) => true,
_ => false,
}
};
let text_layout = {
match (cfg!(feature = "textlayout"), cfg!(feature = "shaper")) {
(false, false) => TextLayout::None,
(false, true) => TextLayout::ShaperOnly,
(true, false) => panic!("invalid feature configuration, feature 'shaper' must be enabled for feature 'textlayout'"),
(true, true) => TextLayout::ShaperAndParagraph,
}
};
BuildConfiguration {
on_windows: cargo::host().is_windows(),
// Note that currently, we don't support debug Skia builds,
// because they are hard to configure and pull in a lot of testing related modules.
skia_release: true,
keep_inline_functions: true,
features: Features {
vulkan: cfg!(feature = "vulkan"),
svg: cfg!(feature = "svg"),
text_layout,
animation: false,
dng: false,
particles: false,
},
all_skia_libs,
definitions: Vec::new(),
}
}
}
/// The build configuration for Skia.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct BuildConfiguration {
/// Do we build _on_ a Windows OS?
on_windows: bool,
/// Build Skia in a release configuration?
skia_release: bool,
/// Configure Skia builds to keep inline functions to
/// prevent linker errors.
keep_inline_functions: bool,
/// The Skia feature set to compile.
features: Features,
/// As of M74, There is a bug in the Skia macOS build
/// that requires all libraries to be built, otherwise the build will fail.
all_skia_libs: bool,
/// Additional preprocessor definitions that will override predefined ones.
definitions: Definitions,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Features {
/// Build with Vulkan support?
vulkan: bool,
/// Build with SVG support?
svg: bool,
/// Features related to text layout.
text_layout: TextLayout,
/// Build with animation support (yet unsupported, no wrappers).
animation: bool,
/// Support DNG file format (currently unsupported because of build errors).
dng: bool,
/// Build the particles module (unsupported, no wrappers).
particles: bool,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum TextLayout {
/// No text shaping or layout features.
None,
/// Builds the skshaper module, compiles harfbuzz & icu support.
ShaperOnly,
/// Builds the skshaper and the skparagraph module.
ShaperAndParagraph,
}
impl TextLayout {
fn skia_args(&self) -> Vec<(&'static str, String)> {
let mut args = Vec::new();
let (shaper, paragraph) = match self {
TextLayout::None => {
args.push(("skia_use_icu", no()));
(false, false)
}
TextLayout::ShaperOnly => (true, false),
TextLayout::ShaperAndParagraph => (true, true),
};
if shaper {
args.extend(vec![
("skia_enable_skshaper", yes()),
("skia_use_icu", yes()),
("skia_use_system_icu", no()),
("skia_use_harfbuzz", yes()),
("skia_use_system_harfbuzz", no()),
("skia_use_sfntly", no()),
]);
}
if paragraph {
args.extend(vec![
("skia_enable_skparagraph", yes()),
// note: currently, tests need to be enabled, because modules/skparagraph
// is not included in the default dependency configuration.
// ("paragraph_tests_enabled", no()),
]);
}
args
}
fn sources(&self) -> Vec<PathBuf> {
match self {
TextLayout::None => Vec::new(),
TextLayout::ShaperOnly => vec!["src/shaper.cpp".into()],
TextLayout::ShaperAndParagraph => {
vec!["src/shaper.cpp".into(), "src/paragraph.cpp".into()]
}
}
}
fn patches(&self) -> Vec<Patch> {
match self {
TextLayout::ShaperAndParagraph => vec![Patch {
name: "skparagraph".into(),
marked_file: "BUILD.gn".into(),
}],
_ => Vec::new(),
}
}
fn ninja_files(&self) -> Vec<PathBuf> {
match self {
TextLayout::None => Vec::new(),
TextLayout::ShaperOnly => vec!["obj/modules/skshaper/skshaper.ninja".into()],
TextLayout::ShaperAndParagraph => vec![
"obj/modules/skshaper/skshaper.ninja".into(),
"obj/modules/skparagraph/skparagraph.ninja".into(),
],
}
}
}
/// This is the final, low level build configuration.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct FinalBuildConfiguration {
/// Patches to be applied to the Skia repository.
pub skia_patches: Vec<Patch>,
/// The name value pairs passed as arguments to gn.
pub gn_args: Vec<(String, String)>,
/// ninja files that need to be parsed for further definitions.
pub ninja_files: Vec<PathBuf>,
/// The additional definitions (cloned from the definitions of
/// the BuildConfiguration).
pub definitions: Definitions,
/// The binding source files to compile.
pub binding_sources: Vec<PathBuf>,
}
impl FinalBuildConfiguration {
pub fn from_build_configuration(build: &BuildConfiguration) -> FinalBuildConfiguration {
let features = &build.features;
let gn_args = {
fn quote(s: &str) -> String {
format!("\"{}\"", s)
}
let mut args: Vec<(&str, String)> = vec![
(
"is_official_build",
if build.skia_release { yes() } else { no() },
),
("skia_use_system_libjpeg_turbo", no()),
("skia_use_system_libpng", no()),
("skia_use_libwebp", no()),
("skia_use_system_zlib", no()),
(
"skia_enable_skottie",
if features.animation || build.all_skia_libs {
yes()
} else {
no()
},
),
("skia_use_xps", no()),
("skia_use_dng_sdk", if features.dng { yes() } else { no() }),
(
"skia_enable_particles",
if features.particles || build.all_skia_libs {
yes()
} else {
no()
},
),
("cc", quote("clang")),
("cxx", quote("clang++")),
];
// further flags that limit the components of Skia debug builds.
if !build.skia_release {
args.push(("skia_enable_atlas_text", no()));
args.push(("skia_enable_spirv_validation", no()));
args.push(("skia_enable_tools", no()));
args.push(("skia_enable_vulkan_debug_layers", no()));
args.push(("skia_use_libheif", no()));
args.push(("skia_use_lua", no()));
}
args.extend(features.text_layout.skia_args());
if features.vulkan {
args.push(("skia_use_vulkan", yes()));
args.push(("skia_enable_spirv_validation", no()));
}
let mut flags: Vec<&str> = vec![];
let mut use_expat = features.svg;
// target specific gn args.
let target = cargo::target();
match target.as_strs() {
(_, _, "windows", Some("msvc")) if build.on_windows => {
if let Some(win_vc) = vs::resolve_win_vc() {
args.push(("win_vc", quote(win_vc.to_str().unwrap())))
}
// Code on MSVC needs to be compiled differently (e.g. with /MT or /MD) depending on the runtime being linked.
// (See https://doc.rust-lang.org/reference/linkage.html#static-and-dynamic-c-runtimes)
// When static feature is enabled (target-feature=+crt-static) the C runtime should be statically linked
// and the compiler has to place the library name LIBCMT.lib into the .obj
// See https://docs.microsoft.com/en-us/cpp/build/reference/md-mt-ld-use-run-time-library?view=vs-2019
if cargo::target_crt_static() {
flags.push("/MT");
}
// otherwise the C runtime should be linked dynamically
else {
flags.push("/MD");
}
// Tell Skia's build system where LLVM is supposed to be located.
// TODO: this should be checked as a prerequisite.
args.push(("clang_win", quote("C:/Program Files/LLVM")));
}
(arch, "linux", "android", _) => {
args.push(("ndk", quote(&android::ndk())));
// TODO: make API-level configurable?
args.push(("ndk_api", android::API_LEVEL.into()));
args.push(("target_cpu", quote(clang::target_arch(arch))));
args.push(("skia_use_system_freetype2", no()));
args.push(("skia_enable_fontmgr_android", yes()));
// Enabling fontmgr_android implicitly enables expat.
// We make this explicit to avoid relying on an expat installed
// in the system.
use_expat = true;
}
(arch, "apple", "ios", _) => {
args.push(("target_os", quote("ios")));
args.push(("target_cpu", quote(clang::target_arch(arch))));
}
_ => {}
}
if use_expat {
args.push(("skia_use_expat", yes()));
args.push(("skia_use_system_expat", no()));
} else {
args.push(("skia_use_expat", no()));
}
if build.all_skia_libs {
// m78: modules/particles forgets to set SKIA_IMPLEMENTATION=1 and so
// expects system vulkan headers.
flags.push("-DSKIA_IMPLEMENTATION=1");
}
if !flags.is_empty() {
let flags: String = {
let v: Vec<String> = flags.into_iter().map(quote).collect();
v.join(",")
};
args.push(("extra_cflags", format!("[{}]", flags)));
}
args.into_iter()
.map(|(key, value)| (key.to_string(), value))
.collect()
};
let ninja_files = {
let mut files = Vec::new();
files.push("obj/skia.ninja".into());
files.extend(features.text_layout.ninja_files());
files
};
let binding_sources = {
let mut sources: Vec<PathBuf> = Vec::new();
sources.push("src/bindings.cpp".into());
sources.extend(features.text_layout.sources());
sources
};
FinalBuildConfiguration {
skia_patches: features.text_layout.patches(),
gn_args,
ninja_files,
definitions: build.definitions.clone(),
binding_sources,
}
}
}
fn yes() -> String {
"true".into()
}
fn no() -> String {
"false".into()
}
/// The resulting binaries configuration.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct BinariesConfiguration {
/// The feature identifiers we built with.
pub feature_ids: Vec<String>,
/// The output directory of the libraries we build and we need to inform cargo about.
pub output_directory: PathBuf,
/// The TARGET specific link libraries we need to inform cargo about.
pub link_libraries: Vec<String>,
/// The static Skia libraries skia-bindings provides and dependent projects need to link with.
pub built_libraries: Vec<String>,
/// Additional files relative to the output_directory
/// that are needed to build dependent projects.
pub additional_files: Vec<PathBuf>,
}
const SKIA_OUTPUT_DIR: &str = "skia";
const ICUDTL_DAT: &str = "icudtl.dat";
impl BinariesConfiguration {
/// Build a binaries configuration based on the current environment cargo
/// supplies us with and a Skia build configuration.
pub fn from_cargo_env(build: &BuildConfiguration) -> Self {
let features = &build.features;
let target = cargo::target();
let mut built_libraries = Vec::new();
let mut additional_files = Vec::new();
let mut feature_ids = Vec::new();
if features.vulkan {
feature_ids.push(feature_id::VULKAN);
}
if features.svg {
feature_ids.push(feature_id::SVG);
}
match features.text_layout {
TextLayout::None => {}
TextLayout::ShaperOnly => {
feature_ids.push(feature_id::SHAPER);
additional_files.push(ICUDTL_DAT.into());
built_libraries.push(lib::SKSHAPER.into());
}
TextLayout::ShaperAndParagraph => {
feature_ids.push(feature_id::TEXTLAYOUT);
additional_files.push(ICUDTL_DAT.into());
built_libraries.push(lib::SKPARAGRAPH.into());
built_libraries.push(lib::SKSHAPER.into());
}
}
let mut link_libraries = Vec::new();
match target.as_strs() {
(_, "unknown", "linux", Some("gnu")) => {
link_libraries.extend(vec!["stdc++", "bz2", "GL", "fontconfig", "freetype"]);
}
(_, "apple", "darwin", _) => {
link_libraries.extend(vec![
"c++",
"framework=OpenGL",
"framework=ApplicationServices",
]);
}
(_, _, "windows", Some("msvc")) => {
link_libraries.extend(vec![
"usp10", "ole32", "user32", "gdi32", "fontsub", "opengl32",
]);
}
(_, "linux", "android", _) => {
link_libraries.extend(vec![
"log",
"android",
"EGL",
"GLESv2",
"c++_static",
"c++abi",
]);
}
(_, "apple", "ios", _) => {
link_libraries.extend(vec![
"c++",
"framework=MobileCoreServices",
"framework=CoreFoundation",
"framework=CoreGraphics",
"framework=CoreText",
"framework=ImageIO",
"framework=UIKit",
]);
}
_ => panic!("unsupported target: {:?}", cargo::target()),
};
let output_directory = cargo::output_directory()
.join(SKIA_OUTPUT_DIR)
.to_str()
.unwrap()
.into();
built_libraries.push(lib::SKIA.into());
built_libraries.push(lib::SKIA_BINDINGS.into());
BinariesConfiguration {
feature_ids: feature_ids.into_iter().map(|f| f.to_string()).collect(),
output_directory,
link_libraries: link_libraries
.into_iter()
.map(|lib| lib.to_string())
.collect(),
built_libraries,
additional_files,
}
}
/// Inform cargo that the output files of the given configuration are available and
/// can be used as dependencies.
pub fn commit_to_cargo(&self) {
cargo::add_link_libs(&self.link_libraries);
println!(
"cargo:rustc-link-search={}",
self.output_directory.to_str().unwrap()
);
for lib in &self.built_libraries {
cargo::add_link_lib(format!("static={}", lib));
}
}
}
/// The full build of Skia, SkiaBindings, and the generation of bindings.rs.
pub fn build(build: &FinalBuildConfiguration, config: &BinariesConfiguration) {
prerequisites::resolve_dependencies();
// call Skia's git-sync-deps
let python2 = &prerequisites::locate_python2_cmd();
println!("Python 2 found: {:?}", python2);
assert!(
Command::new(python2)
.arg("skia/tools/git-sync-deps")
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.status()
.unwrap()
.success(),
"`skia/tools/git-sync-deps` failed"
);
// apply patches
for patch in &build.skia_patches {
println!("applying patch: {}", patch.name);
patch.apply(&PathBuf::from("skia"));
}
// configure Skia
let gn_args = build
.gn_args
.iter()
.map(|(name, value)| name.clone() + "=" + value)
.collect::<Vec<String>>()
.join(" ");
let current_dir = env::current_dir().unwrap();
let gn_command = current_dir.join("skia").join("bin").join("gn");
let output_directory_str = config.output_directory.to_str().unwrap();
println!("Skia args: {}", &gn_args);
let output = Command::new(gn_command)
.args(&[
"gen",
output_directory_str,
&format!("--script-executable={}", python2),
&format!("--args={}", gn_args),
])
.envs(env::vars())
.current_dir(PathBuf::from("./skia"))
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.output()
.expect("gn error");
if output.status.code() != Some(0) {
panic!("{:?}", String::from_utf8(output.stdout).unwrap());
}
// build Skia
let on_windows = cfg!(windows);
let ninja_command =
current_dir
.join("depot_tools")
.join(if on_windows { "ninja.exe" } else { "ninja" });
let ninja_status = Command::new(ninja_command)
.current_dir(PathBuf::from("./skia"))
.args(&["-C", output_directory_str])
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.status();
// reverse patches
//
// Even though we patch only the gn configuration, we wait until the ninja build went through,
// because ninja may regenerate its files by calling into gn again (happened once on the CI).
for patch in &build.skia_patches {
println!("reversing patch: {}", patch.name);
patch.reverse(&PathBuf::from("skia"));
}
assert!(
ninja_status
.expect("failed to run `ninja`, does the directory depot_tools/ exist?")
.success(),
"`ninja` returned an error, please check the output for details."
);
bindgen_gen(build, ¤t_dir, &config.output_directory)
}
fn bindgen_gen(build: &FinalBuildConfiguration, current_dir: &Path, output_directory: &Path) {
let mut builder = bindgen::Builder::default()
.generate_comments(false)
.layout_tests(true)
// on macOS some arrays that are used in opaque types get too large to support Debug.
// (for example High Sierra: [u16; 105])
// TODO: may reenable when const generics land in stable.
.derive_debug(false)
.default_enum_style(EnumVariation::Rust {
non_exhaustive: false,
})
.parse_callbacks(Box::new(ParseCallbacks))
.raw_line("#![allow(clippy::all)]")
// GrVkBackendContext contains u128 fields on macOS
.raw_line("#![allow(improper_ctypes)]")
// mem::uninitialized()
.raw_line("#![allow(invalid_value)]")
.raw_line("#![allow(deprecated)]")
.parse_callbacks(Box::new(ParseCallbacks))
.constified_enum(".*Mask")
.constified_enum(".*Flags")
.constified_enum(".*Bits")
.constified_enum("SkCanvas_SaveLayerFlagsSet")
.constified_enum("GrVkAlloc_Flag")
.constified_enum("GrGLBackendState")
.whitelist_function("C_.*")
.whitelist_function("SkAnnotateRectWithURL")
.whitelist_function("SkAnnotateNamedDestination")
.whitelist_function("SkAnnotateLinkToDestination")
.whitelist_function("SkColorTypeBytesPerPixel")
.whitelist_function("SkColorTypeIsAlwaysOpaque")
.whitelist_function("SkColorTypeValidateAlphaType")
.whitelist_function("SkRGBToHSV")
// this function does not whitelist (probably because of inlining):
.whitelist_function("SkColorToHSV")
.whitelist_function("SkHSVToColor")
.whitelist_function("SkPreMultiplyARGB")
.whitelist_function("SkPreMultiplyColor")
.whitelist_function("SkBlendMode_Name")
.whitelist_function("SkSwapRB")
// functions for which the doc generation fails.
.blacklist_function("SkColorFilter_asComponentTable")
// core/
.whitelist_type("SkAutoCanvasRestore")
.whitelist_type("SkColorSpacePrimaries")
.whitelist_type("SkContourMeasure")
.whitelist_type("SkContourMeasureIter")
.whitelist_type("SkCubicMap")
.whitelist_type("SkDataTable")
.whitelist_type("SkDocument")
.whitelist_type("SkDrawLooper")
.whitelist_type("SkDynamicMemoryWStream")
.whitelist_type("SkFontMgr")
.whitelist_type("SkGraphics")
.whitelist_type("SkMemoryStream")
.whitelist_type("SkMultiPictureDraw")
.whitelist_type("SkPathMeasure")
.whitelist_type("SkPictureRecorder")
.whitelist_type("SkVector4")
.whitelist_type("SkYUVASizeInfo")
// effects/
.whitelist_type("SkPath1DPathEffect")
.whitelist_type("SkLine2DPathEffect")
.whitelist_type("SkPath2DPathEffect")
.whitelist_type("SkCornerPathEffect")
.whitelist_type("SkDashPathEffect")
.whitelist_type("SkDiscretePathEffect")
.whitelist_type("SkGradientShader")
.whitelist_type("SkLayerDrawLooper_Bits")
.whitelist_type("SkPerlinNoiseShader")
.whitelist_type("SkTableColorFilter")
.whitelist_type("SkTableMaskFilter")
// gpu/
.whitelist_type("GrGLBackendState")
// gpu/vk/
.whitelist_type("GrVkDrawableInfo")
.whitelist_type("GrVkExtensionFlags")
.whitelist_type("GrVkFeatureFlags")
// pathops/
.whitelist_type("SkPathOp")
.whitelist_function("Op")
.whitelist_function("Simplify")
.whitelist_function("TightBounds")
.whitelist_function("AsWinding")
.whitelist_type("SkOpBuilder")
// svg/
.whitelist_type("SkSVGCanvas")
// utils/
.whitelist_function("Sk3LookAt")
.whitelist_function("Sk3Perspective")
.whitelist_function("Sk3MapPts")
.whitelist_function("SkUnitCubicInterp")
.whitelist_type("Sk3DView")
.whitelist_type("SkInterpolator")
.whitelist_type("SkParsePath")
.whitelist_type("SkShadowUtils")
.whitelist_type("SkShadowFlags")
.whitelist_type("SkTextUtils")
// modules/skshaper/
.whitelist_type("SkShaper")
.whitelist_type("RustRunHandler")
// modules/skparagraph
// pulls in a std::map<>, which we treat as opaque, but bindgen creates wrong bindings for
// std::_Tree* types
.blacklist_type("std::_Tree.*")
.blacklist_type("std::map.*")
// not used at all:
.blacklist_type("std::vector.*")
// Vulkan reexports that got swallowed by making them opaque.
.whitelist_type("VkPhysicalDeviceFeatures")
.whitelist_type("VkPhysicalDeviceFeatures2")
// misc
.whitelist_var("SK_Color.*")
.whitelist_var("kAll_GrBackendState")
//
.use_core()
.clang_arg("-std=c++14")
// required for macOS LLVM 8 to pick up C++ headers:
.clang_args(&["-x", "c++"])
.clang_arg("-v");
for opaque_type in OPAQUE_TYPES {
builder = builder.opaque_type(opaque_type)
}
let mut cc_build = Build::new();
for source in &build.binding_sources {
cc_build.file(source);
let source = source.to_str().unwrap();
cargo::add_dependent_path(source);
builder = builder.header(source);
}
// TODO: may put the include paths into the FinalBuildConfiguration?
let include_path = current_dir.join("skia");
cargo::add_dependent_path(include_path.join("include"));
builder = builder.clang_arg(format!("-I{}", include_path.display()));
cc_build.include(include_path);
let definitions = {
let mut definitions = Vec::new();
for ninja_file in &build.ninja_files {
let ninja_file = output_directory.join(ninja_file);
let contents = fs::read_to_string(ninja_file).unwrap();
definitions = definitions::combine(definitions, definitions::from_ninja(contents))
}
definitions::combine(definitions, build.definitions.clone())
};
for (name, value) in &definitions {
match value {
Some(value) => {
cc_build.define(name, value.as_str());
builder = builder.clang_arg(format!("-D{}={}", name, value));
}
None => {
cc_build.define(name, "");
builder = builder.clang_arg(format!("-D{}", name));
}
}
}
cc_build.cpp(true).out_dir(output_directory);
if !cfg!(windows) {
cc_build.flag("-std=c++14");
}
let target = cargo::target();
match target.as_strs() {
(arch, "linux", "android", _) => {
let target = &target.to_string();
cc_build.target(target);
for arg in android::additional_clang_args(target, arch) {
builder = builder.clang_arg(arg);
}
}
(arch, "apple", "ios", _) => {
for arg in ios::additional_clang_args(arch) {
builder = builder.clang_arg(arg);
}
}
_ => {}
}
println!("COMPILING BINDINGS: {:?}", build.binding_sources);
cc_build.compile(lib::SKIA_BINDINGS);
println!("GENERATING BINDINGS");
let bindings = builder.generate().expect("Unable to generate bindings");
let out_path = PathBuf::from("src");
bindings
.write_to_file(out_path.join("bindings.rs"))
.expect("Couldn't write bindings!");
}
const OPAQUE_TYPES: &[&str] = &[
// Types for which the binding generator pulls in stuff that can not be compiled.
"SkDeferredDisplayList",
"SkDeferredDisplayList_PendingPathsMap",
// Types for which a bindgen layout is wrong causing types that contain
// fields of them to fail their layout test.
// Windows:
"std::atomic",
"std::function",
"std::unique_ptr",
"SkAutoTMalloc",
"SkTHashMap",
// Ubuntu 18 LLVM 6: all types derived from SkWeakRefCnt
"SkWeakRefCnt",
"GrContext",
"GrContextThreadSafeProxy",
"GrContext_Base",
"GrGLInterface",
"GrImageContext",
"GrRecordingContext",
"GrSurfaceProxy",
"Sk2DPathEffect",
"SkCornerPathEffect",
"SkDataTable",
"SkDiscretePathEffect",
"SkDrawable",
"SkLine2DPathEffect",
"SkPath2DPathEffect",
"SkPathRef_GenIDChangeListener",
"SkPicture",
"SkPixelRef",
"SkSurface",
// Types not needed (for now):
"SkDeque",
"SkDeque_Iter",
"GrGLInterface_Functions",
// SkShaper (m77) Trivial*Iterator classes create two vtable pointers.
"SkShaper_TrivialBiDiRunIterator",
"SkShaper_TrivialFontRunIterator",
"SkShaper_TrivialLanguageRunIterator",
"SkShaper_TrivialScriptRunIterator",
// skparagraph
"std::vector",
"std::u16string",
// skparagraph (m78), (layout fails on macOS and Linux, not sure why, looks like an obscure alignment problem)
"skia::textlayout::FontCollection",
// skparagraph (m79), std::map is used in LineMetrics
"std::map",
// Vulkan reexports with the wrong field naming conventions.
"VkPhysicalDeviceFeatures",
"VkPhysicalDeviceFeatures2",
// Since Rust 1.39 beta (TODO: investigate why, and re-test when 1.39 goes stable).
"GrContextOptions_PersistentCache",
"GrContextOptions_ShaderErrorHandler",
"Sk1DPathEffect",
"SkBBHFactory",
"SkBitmap_Allocator",
"SkBitmap_HeapAllocator",
"SkColorFilter",
"SkDeque_F2BIter",
"SkDrawLooper",
"SkDrawLooper_Context",
"SkDrawable_GpuDrawHandler",
"SkFlattenable",
"SkFontMgr",
"SkFontStyleSet",
"SkMaskFilter",
"SkPathEffect",
"SkPicture_AbortCallback",
"SkPixelRef_GenIDChangeListener",
"SkRasterHandleAllocator",
"SkRefCnt",
"SkShader",
"SkStream",
"SkStreamAsset",
"SkStreamMemory",
"SkStreamRewindable",
"SkStreamSeekable",
"SkTypeface_LocalizedStrings",
"SkWStream",
"GrVkMemoryAllocator",
"SkShaper",
"SkShaper_BiDiRunIterator",
"SkShaper_FontRunIterator",
"SkShaper_LanguageRunIterator",
"SkShaper_RunHandler",
"SkShaper_RunIterator",
"SkShaper_ScriptRunIterator",
"SkContourMeasure",
"SkDocument",
];
#[derive(Debug)]
struct ParseCallbacks;
impl bindgen::callbacks::ParseCallbacks for ParseCallbacks {
/// Allows to rename an enum variant, replacing `_original_variant_name`.
fn enum_variant_name(
&self,
enum_name: Option<&str>,
original_variant_name: &str,
_variant_value: bindgen::callbacks::EnumVariantValue,
) -> Option<String> {
enum_name.and_then(|enum_name| {
ENUM_TABLE
.iter()
.find(|n| n.0 == enum_name)
.map(|(_, replacer)| replacer(enum_name, original_variant_name))
})
}
}
type EnumEntry = (&'static str, fn(&str, &str) -> String);
const ENUM_TABLE: &[EnumEntry] = &[
// DartTypes.h
("Affinity", replace::k_xxx),
("RectHeightStyle", replace::k_xxx),
("RectWidthStyle", replace::k_xxx),
("TextAlign", replace::k_xxx),
("TextDirection", replace::k_xxx_uppercase),
("TextBaseline", replace::k_xxx),
// TextStyle.h
("TextDecorationStyle", replace::k_xxx),
("StyleType", replace::k_xxx),
("PlaceholderAlignment", replace::k_xxx),
// Vk*
("VkChromaLocation", replace::vk),
("VkFilter", replace::vk),
("VkFormat", replace::vk),
("VkImageLayout", replace::vk),
("VkImageTiling", replace::vk),
("VkSamplerYcbcrModelConversion", replace::vk),
("VkSamplerYcbcrRange", replace::vk),
("VkStructureType", replace::vk),
];
pub(crate) mod replace {
use heck::ShoutySnakeCase;
use regex::Regex;
pub fn k_xxx_uppercase(name: &str, variant: &str) -> String {
k_xxx(name, variant).to_uppercase()
}
pub fn k_xxx(name: &str, variant: &str) -> String {
if variant.starts_with('k') {
variant[1..].into()
} else {
panic!(
"Variant name '{}' of enum type '{}' is expected to start with a 'k'",
variant, name
);
}
}
pub fn _k_xxx_enum(name: &str, variant: &str) -> String {
capture(variant, &format!("k(.*)_{}", name))
}
pub fn vk(name: &str, variant: &str) -> String {
let prefix = name.to_shouty_snake_case();
capture(variant, &format!("{}_(.*)", prefix))
}
fn capture(variant: &str, pattern: &str) -> String {
let re = Regex::new(pattern).unwrap();
re.captures(variant).unwrap()[1].into()
}
}
mod prerequisites {
use crate::build_support::{cargo, utils};
use flate2::read::GzDecoder;
use std::ffi::OsStr;
use std::fs;
use std::io::Cursor;
use std::path::Component;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
pub fn locate_python2_cmd() -> &'static str {
const PYTHON_CMDS: [&str; 2] = ["python", "python2"];
for python in PYTHON_CMDS.as_ref() {
println!("Probing '{}'", python);
if let Some(true) = is_python_version_2(python) {
return python;
}
}
panic!(">>>>> Probing for Python 2 failed, please make sure that it's available in PATH, probed executables are: {:?} <<<<<", PYTHON_CMDS);
}
/// Returns true if the given python executable is python version 2.
/// or None if the executable was not found.
pub fn is_python_version_2(exe: impl AsRef<str>) -> Option<bool> {
Command::new(exe.as_ref())
.arg("--version")
.output()
.map(|output| {
let mut str = String::from_utf8(output.stdout).unwrap();
if str.is_empty() {
// Python2 seems to push the version to stderr.
str = String::from_utf8(output.stderr).unwrap()
}
// Don't parse version output, for example output
// might be "Python 2.7.15+"
str.starts_with("Python 2.")
})
.ok()
}
/// Resolve the skia and depot_tools subdirectory contents, either by checking out the
/// submodules, or when the build.rs was called outside of the git repository,
/// by downloading and unpacking them from GitHub.
pub fn resolve_dependencies() {
if cargo::is_crate() {
// we are in a crate.
download_dependencies();
} else {
// we are not in a crate, assuming we are in our git repo.
// so just update all submodules.
assert!(
Command::new("git")
.args(&["submodule", "update", "--init", "--depth", "1"])
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.status()
.unwrap()
.success(),
"`git submodule update` failed"
);
}
}
/// Downloads the skia and depot_tools from their repositories.
///
/// The hashes are taken from the Cargo.toml section [package.metadata].
fn download_dependencies() {
let metadata = cargo::get_metadata();
for dep in dependencies() {
let repo_url = dep.url;
let repo_name = dep.repo;
let dir = PathBuf::from(repo_name);
// directory exists => assume that the download of the archive was successful.
if dir.exists() {
continue;
}
// hash available?
let (_, short_hash) = metadata
.iter()
.find(|(n, _)| n == repo_name)
.expect("metadata entry not found");
// remove unpacking directory, github will format it to repo_name-hash
let unpack_dir = &PathBuf::from(format!("{}-{}", repo_name, short_hash));
if unpack_dir.is_dir() {
fs::remove_dir_all(unpack_dir).unwrap();
}
// download
let archive_url = &format!("{}/{}", repo_url, short_hash);
println!("DOWNLOADING: {}", archive_url);
let archive = utils::download(archive_url)
.unwrap_or_else(|_| panic!("Failed to download {}", archive_url));
// unpack
{
let tar = GzDecoder::new(Cursor::new(archive));
let mut archive = tar::Archive::new(tar);
let dir = std::env::current_dir().unwrap();
for entry in archive.entries().expect("failed to iterate over archive") {
let mut entry = entry.unwrap();
let path = entry.path().unwrap();
let mut components = path.components();
let root = components.next().unwrap();
// skip pax headers.
if root.as_os_str() == unpack_dir.as_os_str()
&& (dep.path_filter)(components.as_path())
{
entry.unpack_in(&dir).unwrap();
}
}
}
// move unpack directory to the target repository directory
fs::rename(unpack_dir, repo_name).expect("failed to move directory");
}
}
// Specifies where to download Skia and Depot Tools archives from.
//
// We use codeload.github.com, otherwise the short hash will be expanded to a full hash as the root
// directory inside the tar.gz, and we run into filesystem path length restrictions
// with Skia.
struct Dependency {
pub repo: &'static str,
pub url: &'static str,
pub path_filter: fn(&Path) -> bool,
}
fn dependencies() -> &'static [Dependency] {
return &[
Dependency {
repo: "skia",
url: "https://codeload.github.com/google/skia/tar.gz",
path_filter: filter_skia,
},
Dependency {
repo: "depot_tools",
url: "https://codeload.github.com/rust-skia/depot_tools/tar.gz",
path_filter: filter_depot_tools,
},
];
// infra/ contains very long filenames which may hit the max path restriction on Windows.
// https://github.com/rust-skia/rust-skia/issues/169
fn filter_skia(p: &Path) -> bool {
match p.components().next() {
Some(Component::Normal(name)) if name == OsStr::new("infra") => false,
_ => true,
}
}
// we need only ninja from depot_tools.
// https://github.com/rust-skia/rust-skia/pull/165
fn filter_depot_tools(p: &Path) -> bool {
p.to_str().unwrap().starts_with("ninja")
}
}
}
use bindgen::EnumVariation;
pub use definitions::{Definition, Definitions};
pub(crate) mod definitions {
use std::collections::HashSet;
/// A preprocessor definition.
pub type Definition = (String, Option<String>);
/// A container for a number of preprocessor definitions.
pub type Definitions = Vec<Definition>;
/// Parse a defines = line from a ninja build file.
pub fn from_ninja(ninja_file: impl AsRef<str>) -> Definitions {
let lines: Vec<&str> = ninja_file.as_ref().lines().collect();
let defines = {
let prefix = "defines = ";
let defines = lines
.into_iter()
.find(|s| s.starts_with(prefix))
.expect("missing a line with the prefix 'defines =' in a .ninja file");
&defines[prefix.len()..]
};
let defines: Vec<&str> = {
let prefix = "-D";
defines
.split_whitespace()
.map(|d| {
if d.starts_with(prefix) {
&d[prefix.len()..]
} else {
panic!("missing '-D' prefix from a definition")
}
})
.collect()
};
defines
.into_iter()
.map(|d| {
let items: Vec<&str> = d.splitn(2, '=').collect();
match items.len() {
1 => (items[0].to_string(), None),
2 => (items[0].to_string(), Some(items[1].to_string())),
_ => panic!("internal error"),
}
})
.collect()
}
pub fn combine(a: Definitions, b: Definitions) -> Definitions {
remove_duplicates(a.into_iter().chain(b.into_iter()).collect())
}
pub fn remove_duplicates(mut definitions: Definitions) -> Definitions {
let mut uniques = HashSet::new();
definitions.retain(|e| uniques.insert(e.0.clone()));
definitions
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Patch {
name: String,
marked_file: PathBuf,
}
impl Patch {
fn apply(&self, root_dir: &Path) {
if !self.is_applied(root_dir) {
let patch_file = PathBuf::from("..").join(self.name.clone() + ".patch");
git::run(&["apply", patch_file.to_str().unwrap()], Some(root_dir));
}
}
fn reverse(&self, root_dir: &Path) {
if self.is_applied(root_dir) {
let patch_file = PathBuf::from("..").join(self.name.clone() + ".patch");
git::run(
&["apply", "--reverse", patch_file.to_str().unwrap()],
Some(root_dir),
);
}
}
fn is_applied(&self, root_dir: &Path) -> bool {
let build_gn = root_dir.join(&self.marked_file);
let contents = fs::read_to_string(build_gn).unwrap();
let patch_marker = format!(
"**SKIA-BINDINGS-PATCH-MARKER-{}**",
self.name.to_uppercase()
);
contents.contains(&patch_marker)
}
}
| 34.581981 | 147 | 0.554231 |
33e6653c553d64319db54db5857b0975ddefb693 | 231 | // variables2.rs
// Make me compile! Execute the command `rustlings hint variables2` if you want a hint :)
fn main() {
let x = 0u8;
if x == 10 {
println!("Ten!");
} else {
println!("Not ten!");
}
}
| 19.25 | 89 | 0.536797 |
bf3e9d4d19ac85b920c0a2bc735e6b5ecb47a203 | 319 | // enums1.rs
// Make me compile! Execute `rustlings hint enums1` for hints!
#[derive(Debug)]
enum Message {
Quit,
Echo,
Move,
ChangeColor
}
fn main() {
println!("{:?}", Message::Quit);
println!("{:?}", Message::Echo);
println!("{:?}", Message::Move);
println!("{:?}", Message::ChangeColor);
}
| 17.722222 | 62 | 0.579937 |
f79e631656f39fb589f0a3940ab2bc93075fad9e | 37,590 | #![doc = "generated by AutoRust"]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use super::models;
#[derive(Clone)]
pub struct Client {
endpoint: String,
credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>,
scopes: Vec<String>,
pipeline: azure_core::Pipeline,
}
#[derive(Clone)]
pub struct ClientBuilder {
credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>,
endpoint: Option<String>,
scopes: Option<Vec<String>>,
}
pub const DEFAULT_ENDPOINT: &str = "https://169.254.169.254/metadata";
impl ClientBuilder {
pub fn new(credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>) -> Self {
Self {
credential,
endpoint: None,
scopes: None,
}
}
pub fn endpoint(mut self, endpoint: impl Into<String>) -> Self {
self.endpoint = Some(endpoint.into());
self
}
pub fn scopes(mut self, scopes: &[&str]) -> Self {
self.scopes = Some(scopes.iter().map(|scope| (*scope).to_owned()).collect());
self
}
pub fn build(self) -> Client {
let endpoint = self.endpoint.unwrap_or_else(|| DEFAULT_ENDPOINT.to_owned());
let scopes = self.scopes.unwrap_or_else(|| vec![format!("{}/", endpoint)]);
Client::new(endpoint, self.credential, scopes)
}
}
impl Client {
pub(crate) fn endpoint(&self) -> &str {
self.endpoint.as_str()
}
pub(crate) fn token_credential(&self) -> &dyn azure_core::auth::TokenCredential {
self.credential.as_ref()
}
pub(crate) fn scopes(&self) -> Vec<&str> {
self.scopes.iter().map(String::as_str).collect()
}
pub(crate) async fn send(&self, request: impl Into<azure_core::Request>) -> Result<azure_core::Response, azure_core::Error> {
let mut context = azure_core::Context::default();
let mut request = request.into();
self.pipeline.send(&mut context, &mut request).await
}
pub fn new(
endpoint: impl Into<String>,
credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>,
scopes: Vec<String>,
) -> Self {
let endpoint = endpoint.into();
let pipeline = azure_core::Pipeline::new(
option_env!("CARGO_PKG_NAME"),
option_env!("CARGO_PKG_VERSION"),
azure_core::ClientOptions::default(),
Vec::new(),
Vec::new(),
);
Self {
endpoint,
credential,
scopes,
pipeline,
}
}
pub fn attested(&self) -> attested::Client {
attested::Client(self.clone())
}
pub fn identity(&self) -> identity::Client {
identity::Client(self.clone())
}
pub fn instances(&self) -> instances::Client {
instances::Client(self.clone())
}
}
#[non_exhaustive]
#[derive(Debug, thiserror :: Error)]
#[allow(non_camel_case_types)]
pub enum Error {
#[error(transparent)]
Instances_GetMetadata(#[from] instances::get_metadata::Error),
#[error(transparent)]
Attested_GetDocument(#[from] attested::get_document::Error),
#[error(transparent)]
Identity_GetToken(#[from] identity::get_token::Error),
#[error(transparent)]
Identity_GetInfo(#[from] identity::get_info::Error),
}
pub mod instances {
use super::models;
pub struct Client(pub(crate) super::Client);
impl Client {
pub fn get_metadata(&self, metadata: impl Into<String>) -> get_metadata::Builder {
get_metadata::Builder {
client: self.0.clone(),
metadata: metadata.into(),
}
}
}
pub mod get_metadata {
use super::models;
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("Error response #response_type")]
BadRequest400 { value: models::ErrorResponse },
#[error("Error response #response_type")]
Forbidden403 { value: models::ErrorResponse },
#[error("Error response #response_type")]
NotFound404 { value: models::ErrorResponse },
#[error("Error response #response_type")]
MethodNotAllowed405 { value: models::ErrorResponse },
#[error("Error response #response_type")]
TooManyRequests429 { value: models::ErrorResponse },
#[error("Error response #response_type")]
ServiceUnavailable503 { value: models::ErrorResponse },
#[error("Error response #response_type")]
InternalServerError500 { value: models::ErrorResponse },
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL")]
ParseUrl(#[source] url::ParseError),
#[error("Failed to build request")]
BuildRequest(#[source] http::Error),
#[error("Failed to serialize request body")]
Serialize(#[source] serde_json::Error),
#[error("Failed to get access token")]
GetToken(#[source] azure_core::Error),
#[error("Failed to execute request")]
SendRequest(#[source] azure_core::Error),
#[error("Failed to get response bytes")]
ResponseBytes(#[source] azure_core::StreamError),
#[error("Failed to deserialize response, body: {1:?}")]
Deserialize(#[source] serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) metadata: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Instance, Error>> {
Box::pin(async move {
let url_str = &format!("{}/instance", self.client.endpoint(),);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", "2018-10-01");
req_builder = req_builder.header("Metadata", &self.metadata);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Instance =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
http::StatusCode::BAD_REQUEST => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::BadRequest400 { value: rsp_value })
}
http::StatusCode::FORBIDDEN => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::Forbidden403 { value: rsp_value })
}
http::StatusCode::NOT_FOUND => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::NotFound404 { value: rsp_value })
}
http::StatusCode::METHOD_NOT_ALLOWED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::MethodNotAllowed405 { value: rsp_value })
}
http::StatusCode::TOO_MANY_REQUESTS => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::TooManyRequests429 { value: rsp_value })
}
http::StatusCode::SERVICE_UNAVAILABLE => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::ServiceUnavailable503 { value: rsp_value })
}
http::StatusCode::INTERNAL_SERVER_ERROR => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::InternalServerError500 { value: rsp_value })
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
}
pub mod attested {
use super::models;
pub struct Client(pub(crate) super::Client);
impl Client {
pub fn get_document(&self, metadata: impl Into<String>) -> get_document::Builder {
get_document::Builder {
client: self.0.clone(),
metadata: metadata.into(),
nonce: None,
}
}
}
pub mod get_document {
use super::models;
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("Error response #response_type")]
BadRequest400 { value: models::ErrorResponse },
#[error("Error response #response_type")]
Forbidden403 { value: models::ErrorResponse },
#[error("Error response #response_type")]
NotFound404 { value: models::ErrorResponse },
#[error("Error response #response_type")]
MethodNotAllowed405 { value: models::ErrorResponse },
#[error("Error response #response_type")]
TooManyRequests429 { value: models::ErrorResponse },
#[error("Error response #response_type")]
ServiceUnavailable503 { value: models::ErrorResponse },
#[error("Error response #response_type")]
InternalServerError500 { value: models::ErrorResponse },
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL")]
ParseUrl(#[source] url::ParseError),
#[error("Failed to build request")]
BuildRequest(#[source] http::Error),
#[error("Failed to serialize request body")]
Serialize(#[source] serde_json::Error),
#[error("Failed to get access token")]
GetToken(#[source] azure_core::Error),
#[error("Failed to execute request")]
SendRequest(#[source] azure_core::Error),
#[error("Failed to get response bytes")]
ResponseBytes(#[source] azure_core::StreamError),
#[error("Failed to deserialize response, body: {1:?}")]
Deserialize(#[source] serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) metadata: String,
pub(crate) nonce: Option<String>,
}
impl Builder {
pub fn nonce(mut self, nonce: impl Into<String>) -> Self {
self.nonce = Some(nonce.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::AttestedData, Error>> {
Box::pin(async move {
let url_str = &format!("{}/attested/document", self.client.endpoint(),);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", "2018-10-01");
if let Some(nonce) = &self.nonce {
url.query_pairs_mut().append_pair("nonce", nonce);
}
req_builder = req_builder.header("Metadata", &self.metadata);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::AttestedData =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
http::StatusCode::BAD_REQUEST => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::BadRequest400 { value: rsp_value })
}
http::StatusCode::FORBIDDEN => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::Forbidden403 { value: rsp_value })
}
http::StatusCode::NOT_FOUND => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::NotFound404 { value: rsp_value })
}
http::StatusCode::METHOD_NOT_ALLOWED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::MethodNotAllowed405 { value: rsp_value })
}
http::StatusCode::TOO_MANY_REQUESTS => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::TooManyRequests429 { value: rsp_value })
}
http::StatusCode::SERVICE_UNAVAILABLE => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::ServiceUnavailable503 { value: rsp_value })
}
http::StatusCode::INTERNAL_SERVER_ERROR => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::InternalServerError500 { value: rsp_value })
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
}
pub mod identity {
use super::models;
pub struct Client(pub(crate) super::Client);
impl Client {
pub fn get_token(&self, metadata: impl Into<String>, resource: impl Into<String>) -> get_token::Builder {
get_token::Builder {
client: self.0.clone(),
metadata: metadata.into(),
resource: resource.into(),
client_id: None,
object_id: None,
msi_res_id: None,
authority: None,
bypass_cache: None,
}
}
pub fn get_info(&self, metadata: impl Into<String>) -> get_info::Builder {
get_info::Builder {
client: self.0.clone(),
metadata: metadata.into(),
}
}
}
pub mod get_token {
use super::models;
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("Error response #response_type")]
BadRequest400 { value: models::IdentityErrorResponse },
#[error("Error response #response_type")]
NotFound404 { value: models::IdentityErrorResponse },
#[error("Error response #response_type")]
MethodNotAllowed405 { value: models::IdentityErrorResponse },
#[error("Error response #response_type")]
TooManyRequests429 { value: models::IdentityErrorResponse },
#[error("Error response #response_type")]
InternalServerError500 { value: models::IdentityErrorResponse },
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::IdentityErrorResponse,
},
#[error("Failed to parse request URL")]
ParseUrl(#[source] url::ParseError),
#[error("Failed to build request")]
BuildRequest(#[source] http::Error),
#[error("Failed to serialize request body")]
Serialize(#[source] serde_json::Error),
#[error("Failed to get access token")]
GetToken(#[source] azure_core::Error),
#[error("Failed to execute request")]
SendRequest(#[source] azure_core::Error),
#[error("Failed to get response bytes")]
ResponseBytes(#[source] azure_core::StreamError),
#[error("Failed to deserialize response, body: {1:?}")]
Deserialize(#[source] serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) metadata: String,
pub(crate) resource: String,
pub(crate) client_id: Option<String>,
pub(crate) object_id: Option<String>,
pub(crate) msi_res_id: Option<String>,
pub(crate) authority: Option<String>,
pub(crate) bypass_cache: Option<String>,
}
impl Builder {
pub fn client_id(mut self, client_id: impl Into<String>) -> Self {
self.client_id = Some(client_id.into());
self
}
pub fn object_id(mut self, object_id: impl Into<String>) -> Self {
self.object_id = Some(object_id.into());
self
}
pub fn msi_res_id(mut self, msi_res_id: impl Into<String>) -> Self {
self.msi_res_id = Some(msi_res_id.into());
self
}
pub fn authority(mut self, authority: impl Into<String>) -> Self {
self.authority = Some(authority.into());
self
}
pub fn bypass_cache(mut self, bypass_cache: impl Into<String>) -> Self {
self.bypass_cache = Some(bypass_cache.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::IdentityTokenResponse, Error>> {
Box::pin(async move {
let url_str = &format!("{}/identity/oauth2/token", self.client.endpoint(),);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", "2018-10-01");
req_builder = req_builder.header("Metadata", &self.metadata);
let resource = &self.resource;
url.query_pairs_mut().append_pair("resource", resource);
if let Some(client_id) = &self.client_id {
url.query_pairs_mut().append_pair("client_id", client_id);
}
if let Some(object_id) = &self.object_id {
url.query_pairs_mut().append_pair("object_id", object_id);
}
if let Some(msi_res_id) = &self.msi_res_id {
url.query_pairs_mut().append_pair("msi_res_id", msi_res_id);
}
if let Some(authority) = &self.authority {
url.query_pairs_mut().append_pair("authority", authority);
}
if let Some(bypass_cache) = &self.bypass_cache {
url.query_pairs_mut().append_pair("bypass_cache", bypass_cache);
}
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::IdentityTokenResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
http::StatusCode::BAD_REQUEST => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::IdentityErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::BadRequest400 { value: rsp_value })
}
http::StatusCode::NOT_FOUND => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::IdentityErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::NotFound404 { value: rsp_value })
}
http::StatusCode::METHOD_NOT_ALLOWED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::IdentityErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::MethodNotAllowed405 { value: rsp_value })
}
http::StatusCode::TOO_MANY_REQUESTS => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::IdentityErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::TooManyRequests429 { value: rsp_value })
}
http::StatusCode::INTERNAL_SERVER_ERROR => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::IdentityErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::InternalServerError500 { value: rsp_value })
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::IdentityErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod get_info {
use super::models;
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("Error response #response_type")]
BadRequest400 { value: models::IdentityErrorResponse },
#[error("Error response #response_type")]
NotFound404 { value: models::IdentityErrorResponse },
#[error("Error response #response_type")]
MethodNotAllowed405 { value: models::IdentityErrorResponse },
#[error("Error response #response_type")]
TooManyRequests429 { value: models::IdentityErrorResponse },
#[error("Error response #response_type")]
InternalServerError500 { value: models::IdentityErrorResponse },
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::IdentityErrorResponse,
},
#[error("Failed to parse request URL")]
ParseUrl(#[source] url::ParseError),
#[error("Failed to build request")]
BuildRequest(#[source] http::Error),
#[error("Failed to serialize request body")]
Serialize(#[source] serde_json::Error),
#[error("Failed to get access token")]
GetToken(#[source] azure_core::Error),
#[error("Failed to execute request")]
SendRequest(#[source] azure_core::Error),
#[error("Failed to get response bytes")]
ResponseBytes(#[source] azure_core::StreamError),
#[error("Failed to deserialize response, body: {1:?}")]
Deserialize(#[source] serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) metadata: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::IdentityInfoResponse, Error>> {
Box::pin(async move {
let url_str = &format!("{}/identity/info", self.client.endpoint(),);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", "2018-10-01");
req_builder = req_builder.header("Metadata", &self.metadata);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::IdentityInfoResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
http::StatusCode::BAD_REQUEST => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::IdentityErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::BadRequest400 { value: rsp_value })
}
http::StatusCode::NOT_FOUND => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::IdentityErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::NotFound404 { value: rsp_value })
}
http::StatusCode::METHOD_NOT_ALLOWED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::IdentityErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::MethodNotAllowed405 { value: rsp_value })
}
http::StatusCode::TOO_MANY_REQUESTS => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::IdentityErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::TooManyRequests429 { value: rsp_value })
}
http::StatusCode::INTERNAL_SERVER_ERROR => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::IdentityErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::InternalServerError500 { value: rsp_value })
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::IdentityErrorResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
}
| 55.9375 | 136 | 0.5307 |
50666b8c649bc3f3561d0ac90ae1e9bc92bf8758 | 1,641 | // Copyright 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.
use mpsc = std::sync::mpsc_queue;
use std::sync::arc::UnsafeArc;
pub enum PopResult<T> {
Inconsistent,
Empty,
Data(T),
}
pub fn queue<T: Send>() -> (Consumer<T>, Producer<T>) {
let (a, b) = UnsafeArc::new2(mpsc::Queue::new());
(Consumer { inner: a }, Producer { inner: b })
}
pub struct Producer<T> {
inner: UnsafeArc<mpsc::Queue<T>>,
}
pub struct Consumer<T> {
inner: UnsafeArc<mpsc::Queue<T>>,
}
impl<T: Send> Consumer<T> {
pub fn pop(&mut self) -> PopResult<T> {
match unsafe { (*self.inner.get()).pop() } {
mpsc::Inconsistent => Inconsistent,
mpsc::Empty => Empty,
mpsc::Data(t) => Data(t),
}
}
pub fn casual_pop(&mut self) -> Option<T> {
match unsafe { (*self.inner.get()).pop() } {
mpsc::Inconsistent => None,
mpsc::Empty => None,
mpsc::Data(t) => Some(t),
}
}
}
impl<T: Send> Producer<T> {
pub fn push(&mut self, t: T) {
unsafe { (*self.inner.get()).push(t); }
}
}
impl<T: Send> Clone for Producer<T> {
fn clone(&self) -> Producer<T> {
Producer { inner: self.inner.clone() }
}
}
| 26.467742 | 68 | 0.589275 |
1db6dccc89860037a6bc0f8f34291ae6ab1fa860 | 32,876 | // This file is part of sidh-rs.
// Copyright (c) 2017 Erkan Tairi
// See LICENSE for licensing information.
//
// Author:
// - Erkan Tairi <[email protected]>
//
use field::ExtensionFieldElement;
use curve::{ProjectiveCurveParameters, ProjectivePoint};
use isogeny::*;
use constants::*;
use fp::*;
use heapless::Vec;
use std::fmt::Debug;
use std::ops::Neg;
#[cfg(test)]
#[allow(unused_imports)]
use rand::{thread_rng, RngCore, CryptoRng};
#[cfg(not(test))]
use rand_core::{RngCore, CryptoRng};
#[cfg(test)]
use quickcheck::{Arbitrary, Gen, QuickCheck};
/// The secret key size, in bytes.
pub const SECRET_KEY_SIZE: usize = 48;
/// The public key size, in bytes.
pub const PUBLIC_KEY_SIZE: usize = 564;
/// The shared secret size, in bytes.
pub const SHARED_SECRET_SIZE: usize = 188;
const MAX_INT_POINTS_ALICE: usize = 8;
const MAX_INT_POINTS_BOB: usize = 10;
const MAX_ALICE: usize = 185;
/// Alice's isogeny strategy.
pub const ALICE_ISOGENY_STRATEGY: [u8; MAX_ALICE] = [0, 1, 1, 2, 2, 2, 3, 4, 4, 4, 4, 5, 5,
6, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 12, 11, 12, 12, 13, 14, 15, 16, 16, 16, 16,
16, 16, 17, 17, 18, 18, 17, 21, 17, 18, 21, 20, 21, 21, 21, 21, 21, 22, 25, 25,
25, 26, 27, 28, 28, 29, 30, 31, 32, 32, 32, 32, 32, 32, 32, 33, 33, 33, 35, 36,
36, 33, 36, 35, 36, 36, 35, 36, 36, 37, 38, 38, 39, 40, 41, 42, 38, 39, 40, 41,
42, 40, 46, 42, 43, 46, 46, 46, 46, 48, 48, 48, 48, 49, 49, 48, 53, 54, 51, 52,
53, 54, 55, 56, 57, 58, 59, 59, 60, 62, 62, 63, 64, 64, 64, 64, 64, 64, 64, 64,
65, 65, 65, 65, 65, 66, 67, 65, 66, 67, 66, 69, 70, 66, 67, 66, 69, 70, 69, 70,
70, 71, 72, 71, 72, 72, 74, 74, 75, 72, 72, 74, 74, 75, 72, 72, 74, 75, 75, 72,
72, 74, 75, 75, 77, 77, 79, 80, 80, 82];
const MAX_BOB: usize = 239;
/// Bob's isogeny strategy.
pub const BOB_ISOGENY_STRATEGY: [u8; MAX_BOB] = [0, 1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6,
7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 12, 12, 12, 12, 12, 12, 13, 14, 14, 15, 16,
16, 16, 16, 16, 17, 16, 16, 17, 19, 19, 20, 21, 22, 22, 22, 22, 22, 22, 22, 22,
22, 22, 24, 24, 25, 27, 27, 28, 28, 29, 28, 29, 28, 28, 28, 30, 28, 28, 28, 29,
30, 33, 33, 33, 33, 34, 35, 37, 37, 37, 37, 38, 38, 37, 38, 38, 38, 38, 38, 39,
43, 38, 38, 38, 38, 43, 40, 41, 42, 43, 48, 45, 46, 47, 47, 48, 49, 49, 49, 50,
51, 50, 49, 49, 49, 49, 51, 49, 53, 50, 51, 50, 51, 51, 51, 52, 55, 55, 55, 56,
56, 56, 56, 56, 58, 58, 61, 61, 61, 63, 63, 63, 64, 65, 65, 65, 65, 66, 66, 65,
65, 66, 66, 66, 66, 66, 66, 66, 71, 66, 73, 66, 66, 71, 66, 73, 66, 66, 71, 66,
73, 68, 68, 71, 71, 73, 73, 73, 75, 75, 78, 78, 78, 80, 80, 80, 81, 81, 82, 83,
84, 85, 86, 86, 86, 86, 86, 87, 86, 88, 86, 86, 86, 86, 88, 86, 88, 86, 86, 86,
88, 88, 86, 86, 86, 93, 90, 90, 92, 92, 92, 93, 93, 93, 93, 93, 97, 97, 97, 97,
97, 97];
/// Alice's public key.
#[derive(Copy, Clone)]
pub struct SIDHPublicKeyAlice {
pub affine_xP : ExtensionFieldElement,
pub affine_xQ : ExtensionFieldElement,
pub affine_xQmP: ExtensionFieldElement,
}
impl SIDHPublicKeyAlice {
/// Read a public key from a byte slice. The input must be at least 564 bytes long.
pub fn from_bytes(bytes: &[u8]) -> SIDHPublicKeyAlice {
assert!(bytes.len() >= 564, "Too short input to SIDH public key from_bytes, expected 564 bytes");
let affine_xP = ExtensionFieldElement::from_bytes(&bytes[0..188]);
let affine_xQ = ExtensionFieldElement::from_bytes(&bytes[188..376]);
let affine_xQmP = ExtensionFieldElement::from_bytes(&bytes[376..564]);
SIDHPublicKeyAlice{ affine_xP, affine_xQ, affine_xQmP }
}
/// Write a public key to a byte slice. The output will be 564 bytes long.
pub fn to_bytes(&self) -> [u8; 564] {
let mut bytes = [0u8; 564];
bytes[0..188].clone_from_slice(&self.affine_xP.to_bytes());
bytes[188..376].clone_from_slice(&self.affine_xQ.to_bytes());
bytes[376..564].clone_from_slice(&self.affine_xQmP.to_bytes());
bytes
}
}
/// Bob's public key.
#[derive(Copy, Clone)]
pub struct SIDHPublicKeyBob {
pub affine_xP : ExtensionFieldElement,
pub affine_xQ : ExtensionFieldElement,
pub affine_xQmP: ExtensionFieldElement,
}
impl SIDHPublicKeyBob {
/// Read a public key from a byte slice. The input must be at least 564 bytes long.
pub fn from_bytes(bytes: &[u8]) -> SIDHPublicKeyBob {
assert!(bytes.len() >= 564, "Too short input to SIDH public key from_bytes, expected 564 bytes");
let affine_xP = ExtensionFieldElement::from_bytes(&bytes[0..188]);
let affine_xQ = ExtensionFieldElement::from_bytes(&bytes[188..376]);
let affine_xQmP = ExtensionFieldElement::from_bytes(&bytes[376..564]);
SIDHPublicKeyBob{ affine_xP, affine_xQ, affine_xQmP }
}
/// Write a public key to a byte slice. The output will be 564 bytes long.
pub fn to_bytes(&self) -> [u8; 564] {
let mut bytes = [0u8; 564];
bytes[0..188].clone_from_slice(&self.affine_xP.to_bytes());
bytes[188..376].clone_from_slice(&self.affine_xQ.to_bytes());
bytes[376..564].clone_from_slice(&self.affine_xQmP.to_bytes());
bytes
}
}
/// Alice's secret key.
#[derive(Copy, Clone)]
pub struct SIDHSecretKeyAlice {
pub scalar: [u8; SECRET_KEY_SIZE],
}
impl Debug for SIDHSecretKeyAlice {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "SIDHSecretKeyAlice(scalar: {:?})", &self.scalar[..])
}
}
#[cfg(test)]
impl Arbitrary for SIDHSecretKeyAlice {
fn arbitrary(_g: &mut Gen) -> SIDHSecretKeyAlice {
let mut rng = rand::thread_rng();
let (_, alice_secret_key) = generate_alice_keypair(&mut rng);
alice_secret_key
}
}
impl SIDHSecretKeyAlice {
/// Compute the corresponding public key for the given secret key.
pub fn public_key(&self) -> SIDHPublicKeyAlice {
let mut xP = ProjectivePoint::from_affine_prime_field(&AFFINE_X_PB); // = ( x_P : 1) = x(P_B)
let mut xQ = ProjectivePoint::from_affine_prime_field(&AFFINE_X_PB); //
xQ.X = (&xQ.X).neg(); // = (-x_P : 1) = x(Q_B)
let mut xQmP = ProjectivePoint::distort_and_difference(&AFFINE_X_PB); // = x(Q_B - P_B)
let mut xR = ProjectivePoint::secret_point(&AFFINE_X_PA, &AFFINE_Y_PA, &self.scalar[..]);
// Starting curve has a = 0, so (A:C) = (0,1).
let current_curve = ProjectiveCurveParameters{ A: ExtensionFieldElement::zero(), C: ExtensionFieldElement::one() };
let (mut current_curve, firstPhi) = FirstFourIsogeny::compute_first_four_isogeny(¤t_curve);
xP = firstPhi.eval(&xP);
xQ = firstPhi.eval(&xQ);
xQmP = firstPhi.eval(&xQmP);
xR = firstPhi.eval(&xR);
let mut points: Vec<ProjectivePoint, MAX_INT_POINTS_ALICE> = Vec::new();
let mut indices: Vec<usize, MAX_INT_POINTS_ALICE> = Vec::new();
let mut i: usize = 0;
let mut phi: FourIsogeny;
for j in 1..MAX_ALICE {
while i < MAX_ALICE-j {
points.push(xR).unwrap();
indices.push(i).unwrap();
let k = ALICE_ISOGENY_STRATEGY[MAX_ALICE-i-j];
xR = xR.pow2k(¤t_curve, (2*k) as u32);
i = i + k as usize;
}
assign!{(current_curve, phi) = FourIsogeny::compute_four_isogeny(&xR)};
for k in 0..points.len() {
points[k] = phi.eval(&points[k]);
}
xP = phi.eval(&xP);
xQ = phi.eval(&xQ);
xQmP = phi.eval(&xQmP);
// Pop xR from pointsm and i from indices.
xR = points.pop().unwrap();
i = indices.pop().unwrap();
}
assign!{(current_curve, phi) = FourIsogeny::compute_four_isogeny(&xR)};
xP = phi.eval(&xP);
xQ = phi.eval(&xQ);
xQmP = phi.eval(&xQmP);
let (invZP, invZQ, invZQmP) = ExtensionFieldElement::batch3_inv(&xP.Z, &xQ.Z, &xQmP.Z);
let affine_xP = &xP.X * &invZP;
let affine_xQ = &xQ.X * &invZQ;
let affine_xQmP = &xQmP.X * &invZQmP;
SIDHPublicKeyAlice{ affine_xP, affine_xQ, affine_xQmP }
}
/// Compute (Alice's view of) a shared secret using Alice's secret key and Bob's public key.
pub fn shared_secret(&self, bob_public: &SIDHPublicKeyBob) -> [u8; SHARED_SECRET_SIZE] {
let current_curve = ProjectiveCurveParameters::recover_curve_parameters(&bob_public.affine_xP, &bob_public.affine_xQ, &bob_public.affine_xQmP);
let xP = ProjectivePoint::from_affine(&bob_public.affine_xP);
let xQ = ProjectivePoint::from_affine(&bob_public.affine_xQ);
let xQmP = ProjectivePoint::from_affine(&bob_public.affine_xQmP);
let mut xR = ProjectivePoint::right_to_left_ladder(&xP, &xQ, &xQmP, ¤t_curve, &self.scalar[..]);
let (mut current_curve, firstPhi) = FirstFourIsogeny::compute_first_four_isogeny(¤t_curve);
xR = firstPhi.eval(&xR);
let mut points: Vec<ProjectivePoint, MAX_INT_POINTS_ALICE> = Vec::new();
let mut indices: Vec<usize, MAX_INT_POINTS_ALICE> = Vec::new();
let mut i: usize = 0;
let mut phi: FourIsogeny;
for j in 1..MAX_ALICE {
while i < MAX_ALICE-j {
points.push(xR).unwrap();
indices.push(i).unwrap();
let k = ALICE_ISOGENY_STRATEGY[MAX_ALICE-i-j];
xR = xR.pow2k(¤t_curve, (2*k) as u32);
i = i + k as usize;
}
assign!{(current_curve, phi) = FourIsogeny::compute_four_isogeny(&xR)};
for k in 0..points.len() {
points[k] = phi.eval(&points[k]);
}
// Pop xR from pointsm and i from indices.
xR = points.pop().unwrap();
i = indices.pop().unwrap();
}
assign!{(current_curve, phi) = FourIsogeny::compute_four_isogeny(&xR)};
let j_inv = current_curve.j_invariant();
let shared_secret = j_inv.to_bytes();
shared_secret
}
}
/// Bob's secret key.
#[derive(Copy, Clone)]
pub struct SIDHSecretKeyBob {
pub scalar: [u8; SECRET_KEY_SIZE],
}
impl Debug for SIDHSecretKeyBob {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "SIDHSecretKeyBob(scalar: {:?})", &self.scalar[..])
}
}
#[cfg(test)]
impl Arbitrary for SIDHSecretKeyBob {
fn arbitrary(_g: &mut Gen) -> SIDHSecretKeyBob {
let mut rng = thread_rng();
let (_, bob_secret_key) = generate_bob_keypair(&mut rng);
bob_secret_key
}
}
impl SIDHSecretKeyBob {
/// Compute the public key corresponding to the secret key.
pub fn public_key(&self) -> SIDHPublicKeyBob {
let mut xP = ProjectivePoint::from_affine_prime_field(&AFFINE_X_PA); // = ( x_P : 1) = x(P_A)
let mut xQ = ProjectivePoint::from_affine_prime_field(&AFFINE_X_PA); //
xQ.X = (&xQ.X).neg(); // = (-x_P : 1) = x(Q_A)
let mut xQmP = ProjectivePoint::distort_and_difference(&AFFINE_X_PA); // = x(Q_B - P_B)
let mut xR = ProjectivePoint::secret_point(&AFFINE_X_PB, &AFFINE_Y_PB, &self.scalar[..]);
// Starting curve has a = 0, so (A:C) = (0,1).
let mut current_curve = ProjectiveCurveParameters{ A: ExtensionFieldElement::zero(), C: ExtensionFieldElement::one() };
let mut points: Vec<ProjectivePoint, MAX_INT_POINTS_BOB> = Vec::new();
let mut indices: Vec<usize, MAX_INT_POINTS_BOB> = Vec::new();
let mut i: usize = 0;
let mut phi: ThreeIsogeny;
for j in 1..MAX_BOB {
while i < MAX_BOB-j {
points.push(xR).unwrap();
indices.push(i).unwrap();
let k = BOB_ISOGENY_STRATEGY[MAX_BOB-i-j];
xR = xR.pow3k(¤t_curve, k as u32);
i = i + k as usize;
}
assign!{(current_curve, phi) = ThreeIsogeny::compute_three_isogeny(&xR)};
for k in 0..points.len() {
points[k] = phi.eval(&points[k]);
}
xP = phi.eval(&xP);
xQ = phi.eval(&xQ);
xQmP = phi.eval(&xQmP);
// Pop xR from points and i from indices.
xR = points.pop().unwrap();
i = indices.pop().unwrap();
}
assign!{(current_curve, phi) = ThreeIsogeny::compute_three_isogeny(&xR)};
xP = phi.eval(&xP);
xQ = phi.eval(&xQ);
xQmP = phi.eval(&xQmP);
let (invZP, invZQ, invZQmP) = ExtensionFieldElement::batch3_inv(&xP.Z, &xQ.Z, &xQmP.Z);
let affine_xP = &xP.X * &invZP;
let affine_xQ = &xQ.X * &invZQ;
let affine_xQmP = &xQmP.X * &invZQmP;
SIDHPublicKeyBob{ affine_xP, affine_xQ, affine_xQmP }
}
/// Compute (Bob's view of) a shared secret using Bob's secret key and Alice's public key.
pub fn shared_secret(&self, alice_public: &SIDHPublicKeyAlice) -> [u8; SHARED_SECRET_SIZE] {
let mut current_curve = ProjectiveCurveParameters::recover_curve_parameters(&alice_public.affine_xP, &alice_public.affine_xQ, &alice_public.affine_xQmP);
let xP = ProjectivePoint::from_affine(&alice_public.affine_xP);
let xQ = ProjectivePoint::from_affine(&alice_public.affine_xQ);
let xQmP = ProjectivePoint::from_affine(&alice_public.affine_xQmP);
let mut xR = ProjectivePoint::right_to_left_ladder(&xP, &xQ, &xQmP, ¤t_curve, &self.scalar[..]);
let mut points: Vec<ProjectivePoint, MAX_INT_POINTS_BOB> = Vec::new();
let mut indices: Vec<usize, MAX_INT_POINTS_BOB> = Vec::new();
let mut i: usize = 0;
let mut phi: ThreeIsogeny;
for j in 1..MAX_BOB {
while i < MAX_BOB-j {
points.push(xR).unwrap();
indices.push(i).unwrap();
let k = BOB_ISOGENY_STRATEGY[MAX_BOB-i-j];
xR = xR.pow3k(¤t_curve, k as u32);
i = i + k as usize;
}
assign!{(current_curve, phi) = ThreeIsogeny::compute_three_isogeny(&xR)};
for k in 0..points.len() {
points[k] = phi.eval(&points[k]);
}
// Pop xR from points and i from indices.
xR = points.pop().unwrap();
i = indices.pop().unwrap();
}
assign!{(current_curve, phi) = ThreeIsogeny::compute_three_isogeny(&xR)};
let j_inv = current_curve.j_invariant();
let shared_secret = j_inv.to_bytes();
shared_secret
}
}
/// Generate a keypair for "Alice". Note that because this library does not
/// implement SIDH validation, each keypair should be used for at most one
/// shared secret computation.
pub fn generate_alice_keypair<R: RngCore + CryptoRng>(rng: &mut R) -> (SIDHPublicKeyAlice, SIDHSecretKeyAlice) {
let mut scalar = [0u8; SECRET_KEY_SIZE];
rng.fill_bytes(&mut scalar[..]);
// Bit-twiddle to ensure scalar is in 2*[0,2^371):
scalar[47] = 0;
scalar[46] &= 15; // Clear high bits, so scalar < 2^372.
scalar[0] &= 254; // Clear low bit, so scalar is even.
// We actually want scalar in 2*(0,2^371), but the above procedure
// generates 0 with probability 2^(-371), which isn't worth checking
// for.
let secret_key = SIDHSecretKeyAlice{ scalar };
let public_key = secret_key.public_key();
(public_key, secret_key)
}
/// Generate a keypair for "Bob". Note that because this library does not
/// implement SIDH validation, each keypair should be used for at most one
/// shared secret computation.
pub fn generate_bob_keypair<R: RngCore + CryptoRng>(rng: &mut R) -> (SIDHPublicKeyBob, SIDHSecretKeyBob) {
let mut scalar = [0u8; SECRET_KEY_SIZE];
// Perform rejection sampling to obtain a random value in [0,3^238]:
let mut ok: u32 = 1;
for _ in 0..102 {
rng.fill_bytes(&mut scalar[..]);
// Mask the high bits to obtain a uniform value in [0,2^378):
scalar[47] &= 3;
// Accept if scalar < 3^238 (this happens with probability ~0.5828).
checklt238(&scalar, &mut ok);
if ok == 0 { break; }
}
// ok is nonzero if all 102 trials failed.
// This happens with probability 0.41719...^102 < 2^(-128), i.e., never.
if ok != 0 { panic!("All 102 trials failed!"); }
// Multiply by 3 to get a scalar in 3*[0,3^238):
mulby3(&mut scalar);
// We actually want scalar in 2*(0,2^371), but the above procedure
// generates 0 with probability 3^(-238), which isn't worth checking
// for.
let secret_key = SIDHSecretKeyBob{ scalar };
let public_key = secret_key.public_key();
(public_key, secret_key)
}
#[cfg(test)]
mod test {
use super::*;
// Perform Alice's (2-isogeny) key generation, using the slow but simple multiplication-based strategy.
//
// This function just exists to ensure that the fast isogeny-tree strategy works correctly.
pub fn alice_keygen_slow(secret_key: &SIDHSecretKeyAlice) -> SIDHPublicKeyAlice {
let mut xP = ProjectivePoint::from_affine_prime_field(&AFFINE_X_PB); // = ( x_P : 1) = x(P_B)
let mut xQ = ProjectivePoint::from_affine_prime_field(&AFFINE_X_PB); //
xQ.X = (&xQ.X).neg(); // = (-x_P : 1) = x(Q_B)
let mut xQmP = ProjectivePoint::distort_and_difference(&AFFINE_X_PB); // = x(Q_B - P_B)
let mut xR = ProjectivePoint::secret_point(&AFFINE_X_PA, &AFFINE_Y_PA, &secret_key.scalar[..]);
// Starting curve has a = 0, so (A:C) = (0,1).
let current_curve = ProjectiveCurveParameters{ A: ExtensionFieldElement::zero(), C: ExtensionFieldElement::one() };
let (mut current_curve, firstPhi) = FirstFourIsogeny::compute_first_four_isogeny(¤t_curve);
xP = firstPhi.eval(&xP);
xQ = firstPhi.eval(&xQ);
xQmP = firstPhi.eval(&xQmP);
xR = firstPhi.eval(&xR);
let mut phi: FourIsogeny;
// rev() makes the loop go from 368 down to 0.
for e in (0..(372 - 4 + 1)).rev().step_by(2) {
let xS = xR.pow2k(¤t_curve, e as u32);
assign!{(current_curve, phi) = FourIsogeny::compute_four_isogeny(&xS)};
xR = phi.eval(&xR);
xP = phi.eval(&xP);
xQ = phi.eval(&xQ);
xQmP = phi.eval(&xQmP);
}
let (invZP, invZQ, invZQmP) = ExtensionFieldElement::batch3_inv(&xP.Z, &xQ.Z, &xQmP.Z);
let affine_xP = &xP.X * &invZP;
let affine_xQ = &xQ.X * &invZQ;
let affine_xQmP = &xQmP.X * &invZQmP;
SIDHPublicKeyAlice{ affine_xP, affine_xQ, affine_xQmP }
}
// Perform Bob's (3-isogeny) key generation, using the slow but simple multiplication-based strategy.
//
// This function just exists to ensure that the fast isogeny-tree strategy works correctly.
pub fn bob_keygen_slow(secret_key: &SIDHSecretKeyBob) -> SIDHPublicKeyBob {
let mut xP = ProjectivePoint::from_affine_prime_field(&AFFINE_X_PA); // = ( x_P : 1) = x(P_A)
let mut xQ = ProjectivePoint::from_affine_prime_field(&AFFINE_X_PA); //
xQ.X = (&xQ.X).neg(); // = (-x_P : 1) = x(Q_A)
let mut xQmP = ProjectivePoint::distort_and_difference(&AFFINE_X_PA); // = x(Q_B - P_B)
let mut xR = ProjectivePoint::secret_point(&AFFINE_X_PB, &AFFINE_Y_PB, &secret_key.scalar[..]);
// Starting curve has a = 0, so (A:C) = (0,1).
let mut current_curve = ProjectiveCurveParameters{ A: ExtensionFieldElement::zero(), C: ExtensionFieldElement::one() };
let mut phi: ThreeIsogeny;
// rev() makes the loop go from 238 down to 0.
for e in (0..MAX_BOB).rev() {
let xS = xR.pow3k(¤t_curve, e as u32);
assign!{(current_curve, phi) = ThreeIsogeny::compute_three_isogeny(&xS)};
xR = phi.eval(&xR);
xP = phi.eval(&xP);
xQ = phi.eval(&xQ);
xQmP = phi.eval(&xQmP);
}
let (invZP, invZQ, invZQmP) = ExtensionFieldElement::batch3_inv(&xP.Z, &xQ.Z, &xQmP.Z);
let affine_xP = &xP.X * &invZP;
let affine_xQ = &xQ.X * &invZQ;
let affine_xQmP = &xQmP.X * &invZQmP;
SIDHPublicKeyBob{ affine_xP, affine_xQ, affine_xQmP }
}
// Perform Alice's key agreement, using the slow but simple multiplication-based strategy.
//
// This function just exists to ensure that the fast isogeny-tree strategy works correctly.
pub fn alice_shared_secret_slow(bob_public: &SIDHPublicKeyBob, alice_secret: &SIDHSecretKeyAlice) -> [u8; SHARED_SECRET_SIZE] {
let current_curve = ProjectiveCurveParameters::recover_curve_parameters(&bob_public.affine_xP, &bob_public.affine_xQ, &bob_public.affine_xQmP);
let xP = ProjectivePoint::from_affine(&bob_public.affine_xP);
let xQ = ProjectivePoint::from_affine(&bob_public.affine_xQ);
let xQmP = ProjectivePoint::from_affine(&bob_public.affine_xQmP);
let mut xR = ProjectivePoint::three_point_ladder(&xP, &xQ, &xQmP, ¤t_curve, &alice_secret.scalar[..]);
let (mut current_curve, firstPhi) = FirstFourIsogeny::compute_first_four_isogeny(¤t_curve);
xR = firstPhi.eval(&xR);
let mut phi: FourIsogeny;
// rev() makes the loop go from 368 down to 2.
for e in (2..(372 - 4 + 1)).rev().step_by(2) {
let xS = xR.pow2k(¤t_curve, e as u32);
assign!{(current_curve, phi) = FourIsogeny::compute_four_isogeny(&xS)};
xR = phi.eval(&xR);
}
assign!{(current_curve, phi) = FourIsogeny::compute_four_isogeny(&xR)};
let j_inv = current_curve.j_invariant();
let shared_secret = j_inv.to_bytes();
shared_secret
}
// Perform Bob's key agreement, using the slow but simple multiplication-based strategy.
//
// This function just exists to ensure that the fast isogeny-tree strategy works correctly.
pub fn bob_shared_secret_slow(alice_public: &SIDHPublicKeyAlice, bob_secret: &SIDHSecretKeyBob) -> [u8; SHARED_SECRET_SIZE] {
let mut current_curve = ProjectiveCurveParameters::recover_curve_parameters(&alice_public.affine_xP, &alice_public.affine_xQ, &alice_public.affine_xQmP);
let xP = ProjectivePoint::from_affine(&alice_public.affine_xP);
let xQ = ProjectivePoint::from_affine(&alice_public.affine_xQ);
let xQmP = ProjectivePoint::from_affine(&alice_public.affine_xQmP);
let mut xR = ProjectivePoint::three_point_ladder(&xP, &xQ, &xQmP, ¤t_curve, &bob_secret.scalar[..]);
let mut phi: ThreeIsogeny;
// rev() makes the loop go from 239 down to 1.
for e in (1..MAX_BOB).rev() {
let xS = xR.pow3k(¤t_curve, e as u32);
assign!{(current_curve, phi) = ThreeIsogeny::compute_three_isogeny(&xS)};
xR = phi.eval(&xR);
}
assign!{(current_curve, phi) = ThreeIsogeny::compute_three_isogeny(&xR)};
let j_inv = current_curve.j_invariant();
let shared_secret = j_inv.to_bytes();
shared_secret
}
#[test]
fn multiply_by_three() {
// sage: repr((3^238 -1).digits(256))
let mut three238_minus1: [u8; 48] = [248, 132, 131, 130, 138, 113, 205, 237, 20, 122, 66, 212, 191, 53, 59, 115, 56, 207, 215, 148, 207, 41, 130, 248, 214, 42, 124, 12, 153, 108, 197, 99, 199, 34, 66, 143, 126, 168, 88, 184, 245, 234, 37, 181, 198, 201, 84, 2];
// sage: repr((3*(3^238 -1)).digits(256))
let three_times_three238_minus1: [u8; 48] = [232, 142, 138, 135, 159, 84, 104, 201, 62, 110, 199, 124, 63, 161, 177, 89, 169, 109, 135, 190, 110, 125, 134, 233, 132, 128, 116, 37, 203, 69, 80, 43, 86, 104, 198, 173, 123, 249, 9, 41, 225, 192, 113, 31, 84, 93, 254, 6];
mulby3(&mut three238_minus1);
assert!(three238_minus1.iter().zip(three_times_three238_minus1.iter()).all(|(a, b)| a == b),
"\nExpected\n{:?}\nfound\n{:?}", &three_times_three238_minus1[..], &three238_minus1[..]);
}
#[test]
fn check_less_than_three238() {
let three238_minus1: [u8; 48] = [248, 132, 131, 130, 138, 113, 205, 237, 20, 122, 66, 212, 191, 53, 59, 115, 56, 207, 215, 148, 207, 41, 130, 248, 214, 42, 124, 12, 153, 108, 197, 99, 199, 34, 66, 143, 126, 168, 88, 184, 245, 234, 37, 181, 198, 201, 84, 2];
let three238: [u8; 48] = [249, 132, 131, 130, 138, 113, 205, 237, 20, 122, 66, 212, 191, 53, 59, 115, 56, 207, 215, 148, 207, 41, 130, 248, 214, 42, 124, 12, 153, 108, 197, 99, 199, 34, 66, 143, 126, 168, 88, 184, 245, 234, 37, 181, 198, 201, 84, 2];
let three238_plus1: [u8; 48] = [250, 132, 131, 130, 138, 113, 205, 237, 20, 122, 66, 212, 191, 53, 59, 115, 56, 207, 215, 148, 207, 41, 130, 248, 214, 42, 124, 12, 153, 108, 197, 99, 199, 34, 66, 143, 126, 168, 88, 184, 245, 234, 37, 181, 198, 201, 84, 2];
let mut result: u32 = 57;
checklt238(&three238_minus1, &mut result);
assert_eq!(result, 0, "\nExpected 0, got {}", result);
checklt238(&three238, &mut result);
assert_ne!(result, 0, "\nExpected nonzero, got {}", result);
checklt238(&three238_plus1, &mut result);
assert_ne!(result, 0, "\nExpected nonzero, got {}", result);
}
#[test]
fn ephemeral_shared_secret() {
fn shared_secrets_match(alice_secret: SIDHSecretKeyAlice, bob_secret: SIDHSecretKeyBob) -> bool {
let alice_public = alice_secret.public_key();
let bob_public = bob_secret.public_key();
let alice_shared_secret = alice_secret.shared_secret(&bob_public);
let bob_shared_secret = bob_secret.shared_secret(&alice_public);
alice_shared_secret.iter().zip(bob_shared_secret.iter()).all(|(a, b)| a == b)
}
QuickCheck::new().max_tests(8).quickcheck(shared_secrets_match as fn(SIDHSecretKeyAlice, SIDHSecretKeyBob) -> bool);
}
#[test]
fn alice_keygen_fast_vs_slow() {
// m_A = 2*randint(0,2^371)
let m_A: [u8; 48] = [248, 31, 9, 39, 165, 125, 79, 135, 70, 97, 87, 231, 221, 204, 245, 38, 150, 198, 187, 184, 199, 148, 156, 18, 137, 71, 248, 83, 111, 170, 138, 61, 112, 25, 188, 197, 132, 151, 1, 0, 207, 178, 24, 72, 171, 22, 11, 0];
let alice_secret_key = SIDHSecretKeyAlice{ scalar: m_A };
let fast_pubkey = alice_secret_key.public_key();
let slow_pubkey = alice_keygen_slow(&alice_secret_key);
assert!(fast_pubkey.affine_xP.vartime_eq(&slow_pubkey.affine_xP),
"\nExpected affine_xP = {:?}\nfound {:?}", fast_pubkey.affine_xP, slow_pubkey.affine_xP);
assert!(fast_pubkey.affine_xQ.vartime_eq(&slow_pubkey.affine_xQ),
"\nExpected affine_xQ = {:?}\nfound {:?}", fast_pubkey.affine_xQ, slow_pubkey.affine_xQ);
assert!(fast_pubkey.affine_xQmP.vartime_eq(&slow_pubkey.affine_xQmP),
"\nExpected affine_xQmP = {:?}\nfound {:?}", fast_pubkey.affine_xQmP, slow_pubkey.affine_xQmP);
}
#[test]
fn bob_keygen_fast_vs_slow() {
// m_B = 3*randint(0,3^238)
let m_B: [u8; 48] = [246, 217, 158, 190, 100, 227, 224, 181, 171, 32, 120, 72, 92, 115, 113, 62, 103, 57, 71, 252, 166, 121, 126, 201, 55, 99, 213, 234, 243, 228, 171, 68, 9, 239, 214, 37, 255, 242, 217, 180, 25, 54, 242, 61, 101, 245, 78, 0];
let bob_secret_key = SIDHSecretKeyBob{ scalar: m_B };
let fast_pubkey = bob_secret_key.public_key();
let slow_pubkey = bob_keygen_slow(&bob_secret_key);
assert!(fast_pubkey.affine_xP.vartime_eq(&slow_pubkey.affine_xP),
"\nExpected affine_xP = {:?}\nfound {:?}", fast_pubkey.affine_xP, slow_pubkey.affine_xP);
assert!(fast_pubkey.affine_xQ.vartime_eq(&slow_pubkey.affine_xQ),
"\nExpected affine_xQ = {:?}\nfound {:?}", fast_pubkey.affine_xQ, slow_pubkey.affine_xQ);
assert!(fast_pubkey.affine_xQmP.vartime_eq(&slow_pubkey.affine_xQmP),
"\nExpected affine_xQmP = {:?}\nfound {:?}", fast_pubkey.affine_xQmP, slow_pubkey.affine_xQmP);
}
#[test]
fn shared_secret() {
// m_A = 2*randint(0,2^371)
let m_A: [u8; 48] = [248, 31, 9, 39, 165, 125, 79, 135, 70, 97, 87, 231, 221, 204, 245, 38, 150, 198, 187, 184, 199, 148, 156, 18, 137, 71, 248, 83, 111, 170, 138, 61, 112, 25, 188, 197, 132, 151, 1, 0, 207, 178, 24, 72, 171, 22, 11, 0];
// m_B = 3*randint(0,3^238)
let m_B: [u8; 48] = [246, 217, 158, 190, 100, 227, 224, 181, 171, 32, 120, 72, 92, 115, 113, 62, 103, 57, 71, 252, 166, 121, 126, 201, 55, 99, 213, 234, 243, 228, 171, 68, 9, 239, 214, 37, 255, 242, 217, 180, 25, 54, 242, 61, 101, 245, 78, 0];
let alice_secret = SIDHSecretKeyAlice{ scalar: m_A };
let bob_secret = SIDHSecretKeyBob{ scalar: m_B };
let alice_public = alice_secret.public_key();
let bob_public = bob_secret.public_key();
let alice_shared_secret_slow = alice_shared_secret_slow(&bob_public, &alice_secret);
let alice_shared_secret_fast = alice_secret.shared_secret(&bob_public);
let bob_shared_secret_slow = bob_shared_secret_slow(&alice_public, &bob_secret);
let bob_shared_secret_fast = bob_secret.shared_secret(&alice_public);
assert!(alice_shared_secret_fast.iter().zip(bob_shared_secret_fast.iter()).all(|(a, b)| a == b),
"\nShared secret (fast) mismatch: Alice has {:?}\nBob has {:?}", &alice_shared_secret_fast[..], &bob_shared_secret_fast[..]);
assert!(alice_shared_secret_slow.iter().zip(bob_shared_secret_slow.iter()).all(|(a, b)| a == b),
"\nShared secret (slow) mismatch: Alice has {:?}\nBob has {:?}", &alice_shared_secret_slow[..], &bob_shared_secret_slow[..]);
assert!(alice_shared_secret_slow.iter().zip(bob_shared_secret_fast.iter()).all(|(a, b)| a == b),
"\nShared secret mismatch: Alice (slow) has {:?}\nBob (fast) has {:?}", &alice_shared_secret_slow[..], &bob_shared_secret_fast[..]);
}
#[test]
fn secret_point() {
// m_A = 2*randint(0,2^371)
let m_A: [u8; 48] = [248, 31, 9, 39, 165, 125, 79, 135, 70, 97, 87, 231, 221, 204, 245, 38, 150, 198, 187, 184, 199, 148, 156, 18, 137, 71, 248, 83, 111, 170, 138, 61, 112, 25, 188, 197, 132, 151, 1, 0, 207, 178, 24, 72, 171, 22, 11, 0];
// m_B = 3*randint(0,3^238)
let m_B: [u8; 48] = [246, 217, 158, 190, 100, 227, 224, 181, 171, 32, 120, 72, 92, 115, 113, 62, 103, 57, 71, 252, 166, 121, 126, 201, 55, 99, 213, 234, 243, 228, 171, 68, 9, 239, 214, 37, 255, 242, 217, 180, 25, 54, 242, 61, 101, 245, 78, 0];
let xR_A = ProjectivePoint::secret_point(&AFFINE_X_PA, &AFFINE_Y_PA, &m_A[..]);
let xR_B = ProjectivePoint::secret_point(&AFFINE_X_PB, &AFFINE_Y_PB, &m_B[..]);
let sage_affine_xR_A = ExtensionFieldElement{
A: Fp751Element([0x2103d089, 0x29f1dff1, 0x955e0d87, 0x7409b9bf, 0x1cca7288, 0xe812441c, 0xefba55f9, 0xc32b8b13, 0x696d83da, 0xc3b76a80, 0x3a3dc373, 0x185dd4f9, 0x115b6717, 0xfc07c1a9, 0x3b5c4254, 0x39bfcdd6, 0x1d41efd8, 0xc4d097d5, 0x389b21c7, 0x4f893494, 0x1d3d0446, 0x37343321, 0x5ccc3d22, 0x53c3]),
B: Fp751Element([0x33e40815, 0x722e718f, 0xdf715667, 0x8c5fc0f, 0xbbe8c74c, 0x850fd292, 0xfcbf5d3, 0x212938a6, 0xd58dc6e7, 0xfdb2a099, 0x63c9c205, 0x232f83ab, 0xa5543f5e, 0x23eda62f, 0x55d9d04f, 0x49b57588, 0x42ef25d1, 0x6b455e66, 0x37470202, 0x96511625, 0xf2e96ff0, 0xfeced582, 0xe0c0dea8, 0x33a9])
};
let sage_affine_xR_B = ExtensionFieldElement{
A: Fp751Element([0x6e8499f5, 0xdd4e6607, 0x907519da, 0xe7efddc6, 0xb337108c, 0xe31f9955, 0x79ffc5e1, 0x8e558c54, 0xd776bfc2, 0xfee963ea, 0x5846bf15, 0x33aa04c3, 0x23617a0d, 0xab77d91b, 0x746070e2, 0xbdd70948, 0xc277e942, 0x66f71291, 0x2f901fce, 0x187c39db, 0xd5d32aa2, 0x69262987, 0xb40057dc, 0xe1d]),
B: Fp751Element([0xcfd5c167, 0xd1b766ab, 0xc8a382fa, 0x4591059d, 0x736c223d, 0x1ddf9490, 0xbdf2b3dd, 0xc96db091, 0xc292f502, 0x7b8b9c3d, 0x5e4d3e33, 0xe5b18ad8, 0x6664b931, 0xc3f3479b, 0x299e21e6, 0xa4f17865, 0x32fa1c6e, 0x3f7ef5b3, 0xdab06119, 0x875bedb5, 0xa2e23b93, 0x9b5a06e, 0x8296fb26, 0x43d4])
};
let affine_xR_A = xR_A.to_affine();
assert!(sage_affine_xR_A.vartime_eq(&affine_xR_A),
"\nExpected\n{:?}\nfound\n{:?}", sage_affine_xR_A, affine_xR_A);
let affine_xR_B = xR_B.to_affine();
assert!(sage_affine_xR_B.vartime_eq(&affine_xR_B),
"\nExpected\n{:?}\nfound\n{:?}", sage_affine_xR_B, affine_xR_B);
}
} | 48.5613 | 315 | 0.612787 |
1c95656120323c3a2cb4d1f366b0cfda3e7413c5 | 351 | use raw::Local;
use cslice::CMutSlice;
// Suppress a spurious rustc warning about the use of CMutSlice.
#[allow(improper_ctypes)]
extern "C" {
#[link_name = "NeonSys_Buffer_New"]
pub fn new(out: &mut Local, size: u32) -> bool;
#[link_name = "NeonSys_Buffer_Data"]
pub fn data<'a, 'b>(out: &'a mut CMutSlice<'b, u8>, obj: Local);
}
| 23.4 | 68 | 0.655271 |
9b15a4d06991cf0c8826e49e3de3e5c4e2e26d34 | 3,444 | // Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use libc::c_void;
use base::{CFAllocatorRef, CFIndex, CFTypeID, Boolean};
use data::CFDataRef;
use date::CFTimeInterval;
use runloop::CFRunLoopSourceRef;
use string::CFStringRef;
#[repr(C)]
#[derive(Copy, Clone)]
#[derive(Debug)]
pub struct CFMessagePortContext {
pub version: CFIndex,
pub info: *mut c_void,
pub retain: Option<unsafe extern fn(info: *const c_void) -> *const c_void>,
pub release: Option<unsafe extern fn(info: *const c_void)>,
pub copyDescription: Option<unsafe extern fn(info: *const c_void)
-> CFStringRef>,
}
pub type CFMessagePortCallBack = Option<
unsafe extern fn(local: CFMessagePortRef,
msgid: i32,
data: CFDataRef,
info: *mut c_void) -> CFDataRef>;
pub type CFMessagePortInvalidationCallBack = Option<
unsafe extern "C" fn(ms: CFMessagePortRef, info: *mut c_void)>;
#[repr(C)]
pub struct __CFMessagePort(c_void);
pub type CFMessagePortRef = *const __CFMessagePort;
extern {
/*
* CFMessagePort.h
*/
pub fn CFMessagePortGetTypeID() -> CFTypeID;
pub fn CFMessagePortCreateLocal(allocator: CFAllocatorRef,
name: CFStringRef,
callout: CFMessagePortCallBack,
context: *const CFMessagePortContext,
shouldFreeInfo: *mut Boolean)
-> CFMessagePortRef;
pub fn CFMessagePortCreateRemote(allocator: CFAllocatorRef,
name: CFStringRef) -> CFMessagePortRef;
pub fn CFMessagePortIsRemote(ms: CFMessagePortRef) -> Boolean;
pub fn CFMessagePortGetName(ms: CFMessagePortRef) -> CFStringRef;
pub fn CFMessagePortSetName(ms: CFMessagePortRef, newName: CFStringRef)
-> Boolean;
pub fn CFMessagePortGetContext(ms: CFMessagePortRef,
context: *mut CFMessagePortContext);
pub fn CFMessagePortInvalidate(ms: CFMessagePortRef);
pub fn CFMessagePortIsValid(ms: CFMessagePortRef) -> Boolean;
pub fn CFMessagePortGetInvalidationCallBack(ms: CFMessagePortRef)
-> CFMessagePortInvalidationCallBack;
pub fn CFMessagePortSetInvalidationCallBack(ms: CFMessagePortRef,
callout: CFMessagePortInvalidationCallBack);
pub fn CFMessagePortSendRequest(remote: CFMessagePortRef, msgid: i32,
data: CFDataRef,
sendTimeout: CFTimeInterval,
rcvTimeout: CFTimeInterval,
replyMode: CFStringRef,
returnData: *mut CFDataRef) -> i32;
pub fn CFMessagePortCreateRunLoopSource(allocator: CFAllocatorRef,
local: CFMessagePortRef,
order: CFIndex)
-> CFRunLoopSourceRef;
// CFMessagePortSetDispatchQueue
}
| 43.05 | 92 | 0.624855 |
4bfe0537327ff1188f020c8235064f209c5bc16c | 878 | use actix::registry::SystemService;
use actix::*;
use chrono;
#[derive(Default)]
pub struct Ingestor;
impl Actor for Ingestor {
type Context = Context<Self>;
}
impl Supervised for Ingestor {}
impl SystemService for Ingestor {
fn service_started(&mut self, _ctx: &mut Context<Self>) {
info!("started Ingestor")
}
}
#[derive(Debug)]
pub struct IngestEvents<T> {
pub ingest_id: super::IngestId,
pub events: Vec<T>,
pub created_at: chrono::NaiveDateTime,
pub processed_at: Option<chrono::NaiveDateTime>,
}
impl<T> IngestEvents<T> {
pub fn new(events: Vec<T>) -> IngestEvents<T> {
IngestEvents {
ingest_id: super::IngestId::new(),
events,
created_at: chrono::Utc::now().naive_utc(),
processed_at: None,
}
}
}
impl<T> Message for IngestEvents<T> {
type Result = ();
}
| 22.512821 | 61 | 0.628702 |
fbfb2f0f36cf92c6c9fb9f9532f90ff7f6999659 | 5,307 | #![cfg_attr(not(feature = "std"), no_std)]
use sp_std::{prelude::*, vec::Vec, if_std};
use frame_support::{
decl_module, decl_event, decl_storage, decl_error,
ensure, dispatch,
traits::EnsureOrigin
};
use frame_system::{self as system, ensure_signed, RawOrigin};
/// Configure the pallet by specifying the parameters and types on which it depends.
pub trait Trait: system::Trait + did::Trait {
/// Because this pallet emits events, it depends on the runtime's definition of an event.
type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
}
// Errors inform users why an extrinsic failed.
decl_error! {
pub enum Error for Module<T: Trait> {
/// Cannot create the organization because it already exists.
OrganizationExists,
/// Cannot add users to a non-existent organization.
InvalidOrganization,
/// Cannot add a user to an organization to which they already belong.
MemberOfOrganization,
}
}
// Pallets use events to inform users when important changes are made.
// https://substrate.dev/docs/en/knowledgebase/runtime/events
decl_event!(
pub enum Event<T> where AccountId = <T as system::Trait>::AccountId {
/// An organization has been created. [creator, organization_id]
CreatedOrganization(AccountId, Vec<u8>),
/// An account was added to an organization. [account, organization_id]
AddedToOrganization(AccountId, Vec<u8>),
}
);
// The pallet's runtime storage items.
// https://substrate.dev/docs/en/knowledgebase/runtime/storage
decl_storage! {
trait Store for Module<T: Trait> as registrar {
/// The list of organizations in the supply chain consortium.
/// Organizations are identified by the ID of the account that created them.
pub Organizations get(fn organizations): Vec<T::AccountId>;
/// Maps organizations to their members.
pub OrganizationsOf get(fn organizations_of):map hasher(blake2_128_concat) T::AccountId => Vec<T::AccountId>;
}
}
// Dispatchable functions allows users to interact with the pallet and invoke state changes.
// These functions materialize as "extrinsics", which are often compared to transactions.
// Dispatchable functions must be annotated with a weight and must return a DispatchResult.
decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
fn deposit_event() = default;
type Error = Error<T>;
/// Create an organization. Will return an OrganizationExists error if the organization has already
/// been created. Will emit a CreatedOrganization event on success.
///
/// The dispatch origin for this call must be Signed.
#[weight = 10_000]
pub fn create_organization(origin, org_name: Vec<u8>) -> dispatch::DispatchResult {
let who = ensure_signed(origin)?;
let mut orgs = Self::organizations();
ensure!(!orgs.contains(&who), Error::<T>::OrganizationExists);
orgs.push(who.clone());
<Organizations<T>>::put(orgs);
// DID add attribute
<did::Module<T>>::create_attribute(who.clone(), &who, b"Org", &org_name, None)?;
Self::deposit_event(RawEvent::CreatedOrganization(who, org_name));
Ok(())
}
/// Add an account to an organization. Will return an InvalidOrganization error if the organization
/// does not exist or the account is already a member. Will emit a AddedToOrganization event on success.
///
/// The dispatch origin for this call must be Signed.
#[weight = 10_000]
pub fn add_to_organization(origin, account: T::AccountId) -> dispatch::DispatchResult {
let who = ensure_signed(origin)?;
// Organizations list.
let orgs = Self::organizations();
ensure!(orgs.contains(&who), Error::<T>::InvalidOrganization);
// Accounts that belong to a certain organization.
let mut orgs = Self::organizations_of(&account);
// Validate organization and account should not be part.
if !orgs.contains(&who) {
orgs.push(who.clone());
OrganizationsOf::<T>::insert(&account, orgs);
} else {
return Err(Error::<T>::MemberOfOrganization.into());
}
// Add account as a DID delegate.
<did::Module<T>>::create_delegate(&who, &who, &account, &b"OrgMember".to_vec(), None)?;
Self::deposit_event(RawEvent::AddedToOrganization(who, b"OrgMember".to_vec()));
Ok(())
}
}
}
impl<T: Trait> Module<T> {
/// Returns true if and only if the account is a member of an organization.
pub fn part_of_organization(account: &T::AccountId) -> bool {
let orgs = <Module<T>>::organizations();
for org in orgs.iter() {
if <did::Module<T>>::valid_delegate(org, &b"OrgMember".to_vec(), &account).is_ok() {
return true
}
}
false
}
}
/// Ensure that a consortium member is invoking a dispatch.
// https://substrate.dev/rustdocs/v2.0.0-rc4/frame_support/traits/trait.EnsureOrigin.html
pub struct EnsureOrg<T>(sp_std::marker::PhantomData<T>);
impl<T: Trait> EnsureOrigin<T::Origin> for EnsureOrg<T> {
type Success = T::AccountId;
fn try_origin(o: T::Origin) -> Result<Self::Success, T::Origin> {
if_std! {
println!("inside custom origin");
}
o.into().and_then(|o| match o {
RawOrigin::Signed(ref who)
if <Module<T>>::part_of_organization(&who) => Ok(who.clone()),
r => Err(T::Origin::from(r)),
})
}
#[cfg(feature = "runtime-benchmarks")]
fn successful_origin() -> T::Origin {
T::Origin::from(RawOrigin::Signed(Default::default()))
}
}
| 36.102041 | 112 | 0.707368 |
08ffd5ff8f7f7f86ee32ac0ee9892dedb6845c10 | 9,467 | use crate::crypto::keys::strip_secret;
use crate::error::ClientError;
use std::fmt::{Debug, Display};
#[derive(ApiType)]
pub enum ErrorCode {
NotImplemented = 1,
InvalidHex = 2,
InvalidBase64 = 3,
InvalidAddress = 4,
CallbackParamsCantBeConvertedToJson = 5,
WebsocketConnectError = 6,
WebsocketReceiveError = 7,
WebsocketSendError = 8,
HttpClientCreateError = 9,
HttpRequestCreateError = 10,
HttpRequestSendError = 11,
HttpRequestParseError = 12,
CallbackNotRegistered = 13,
NetModuleNotInit = 14,
InvalidConfig = 15,
CannotCreateRuntime = 16,
InvalidContextHandle = 17,
CannotSerializeResult = 18,
CannotSerializeError = 19,
CannotConvertJsValueToJson = 20,
CannotReceiveSpawnedResult = 21,
SetTimerError = 22,
InvalidParams = 23,
ContractsAddressConversionFailed = 24,
UnknownFunction = 25,
AppRequestError = 26,
NoSuchRequest = 27,
CanNotSendRequestResult = 28,
CanNotReceiveRequestResult = 29,
CanNotParseRequestResult = 30,
UnexpectedCallbackResponse = 31,
CanNotParseNumber = 32,
InternalError = 33,
InvalidHandle = 34,
}
pub struct Error;
fn error(code: ErrorCode, message: String) -> ClientError {
ClientError::with_code_message(code as u32, message)
}
pub const CANNOT_SERIALIZE_RESULT: &str = r#"{ "code": 18, "message": "Can not serialize result"}"#;
lazy_static! {
static ref SECRET_REGEX: regex::Regex =
regex::Regex::new(r#""secret"\s*:\s*"([0-9a-f]{64})""#).unwrap();
}
impl Error {
pub fn is_network_error(error: &ClientError) -> bool {
error.code == ErrorCode::WebsocketConnectError as u32
|| error.code == ErrorCode::WebsocketReceiveError as u32
|| error.code == ErrorCode::WebsocketSendError as u32
|| error.code == ErrorCode::HttpRequestSendError as u32
|| (error.code == crate::net::ErrorCode::GraphqlError as u32
&& error.data["server_code"].as_i64() >= Some(500)
&& error.data["server_code"].as_i64() <= Some(599)
)
}
pub fn internal_error<E: Display>(message: E) -> ClientError {
error(ErrorCode::InternalError, message.to_string())
}
pub fn not_implemented(message: &str) -> ClientError {
error(ErrorCode::NotImplemented, message.into())
}
pub fn invalid_hex<E: Display>(s: &str, err: E) -> ClientError {
error(
ErrorCode::InvalidHex,
format!("Invalid hex string: {}\r\nhex: [{}]", err, s),
)
}
pub fn invalid_base64<E: Display>(s: &str, err: E) -> ClientError {
error(
ErrorCode::InvalidBase64,
format!("Invalid base64 string: {}\r\nbase64: [{}]", err, s),
)
}
pub fn invalid_address<E: Display>(err: E, address: &str) -> ClientError {
error(
ErrorCode::InvalidAddress,
format!("Invalid address [{}]: {}", err, address),
)
}
pub fn callback_params_cant_be_converted_to_json<E: Display>(err: E) -> ClientError {
error(
ErrorCode::CallbackParamsCantBeConvertedToJson,
format!("Callback params can't be converted to json: {}", err),
)
}
pub fn websocket_connect_error<E: Display>(address: &str, err: E) -> ClientError {
error(
ErrorCode::WebsocketConnectError,
format!("Can not connect to webscocket URL {}: {}", address, err),
)
}
pub fn websocket_receive_error<E: Display>(err: E) -> ClientError {
error(
ErrorCode::WebsocketReceiveError,
format!("Can not receive message from websocket: {}", err),
)
}
pub fn websocket_send_error<E: Display>(err: E) -> ClientError {
error(
ErrorCode::WebsocketSendError,
format!("Can not send message to websocket: {}", err),
)
}
pub fn http_client_create_error<E: Display>(err: E) -> ClientError {
error(
ErrorCode::HttpClientCreateError,
format!("Can not create http client: {}", err),
)
}
pub fn http_request_create_error<E: Display>(err: E) -> ClientError {
error(
ErrorCode::HttpRequestCreateError,
format!("Can not create http request: {}", err),
)
}
pub fn http_request_send_error<E: Display>(err: E) -> ClientError {
error(
ErrorCode::HttpRequestSendError,
format!("Can not send http request: {}", err),
)
}
pub fn http_request_parse_error<E: Display>(err: E) -> ClientError {
error(
ErrorCode::HttpRequestParseError,
format!("Can not parse http request: {}", err),
)
}
pub fn callback_not_registered(callback_id: u32) -> ClientError {
error(
ErrorCode::CallbackNotRegistered,
format!("Callback with ID {} is not registered", callback_id),
)
}
pub fn net_module_not_init() -> ClientError {
error(
ErrorCode::NetModuleNotInit,
"SDK is initialized without network config".to_owned(),
)
}
pub fn invalid_config(message: String) -> ClientError {
error(ErrorCode::InvalidConfig, message)
}
pub fn cannot_create_runtime<E: Display>(err: E) -> ClientError {
error(
ErrorCode::CannotCreateRuntime,
format!("Can not create runtime: {}", err),
)
}
pub fn invalid_context_handle(context: u32) -> ClientError {
error(
ErrorCode::InvalidContextHandle,
format!("Invalid context handle: {}", context),
)
}
pub fn cannot_serialize_result(err: impl Display) -> ClientError {
error(
ErrorCode::CannotSerializeResult,
format!("Can't serialize result: {}", err),
)
}
pub fn invalid_params(params_json: &str, err: impl Display) -> ClientError {
let mut params_json_stripped = params_json.to_owned();
while let Some(captures) = SECRET_REGEX.captures(¶ms_json_stripped) {
let key = captures.get(1).unwrap().as_str();
let stripped = strip_secret(key);
params_json_stripped = params_json_stripped.replace(key, stripped.as_str());
}
error(
ErrorCode::InvalidParams,
format!(
"Invalid parameters: {}\nparams: {}",
err, params_json_stripped
),
)
}
pub fn contracts_address_conversion_failed(err: impl Display) -> ClientError {
error(
ErrorCode::ContractsAddressConversionFailed,
format!("Address conversion failed: {}", err),
)
}
pub fn unknown_function(name: &str) -> ClientError {
error(
ErrorCode::UnknownFunction,
format!("Unknown function: {}", name),
)
}
pub fn app_request_error(text: &str) -> ClientError {
error(
ErrorCode::AppRequestError,
format!("Application request returned error: {}", text),
)
}
pub fn no_such_request(id: u32) -> ClientError {
error(
ErrorCode::NoSuchRequest,
format!("No such request. ID {}", id),
)
}
pub fn can_not_send_request_result(id: u32) -> ClientError {
error(
ErrorCode::CanNotSendRequestResult,
format!(
"Can not send request result. Probably receiver is already dropped. Request ID {}",
id
),
)
}
pub fn can_not_receive_request_result(err: impl Display) -> ClientError {
error(
ErrorCode::CanNotReceiveRequestResult,
format!("Can not receive request result: {}", err),
)
}
pub fn can_not_parse_request_result(err: impl Display) -> ClientError {
error(
ErrorCode::CanNotParseRequestResult,
format!("Can not parse request result: {}", err),
)
}
pub fn unexpected_callback_response(expected: &str, received: impl Debug) -> ClientError {
error(
ErrorCode::UnexpectedCallbackResponse,
format!(
"Unexpected callback response. Expected {}, received {:#?}",
expected, received
),
)
}
pub fn can_not_parse_number(string: &str) -> ClientError {
error(
ErrorCode::CanNotParseNumber,
format!("Can not parse integer from string `{}`", string),
)
}
pub fn cannot_convert_jsvalue_to_json(value: impl std::fmt::Debug) -> ClientError {
error(
ErrorCode::CannotConvertJsValueToJson,
format!("Can not convert JS value to JSON: {:#?}", value),
)
}
pub fn can_not_receive_spawned_result(err: impl Display) -> ClientError {
error(
ErrorCode::CannotReceiveSpawnedResult,
format!("Can not receive result from spawned task: {}", err),
)
}
pub fn set_timer_error(err: impl Display) -> ClientError {
error(
ErrorCode::SetTimerError,
format!("Set timer error: {}", err),
)
}
pub fn invalid_handle(handle: u32, name: &str) -> ClientError {
error(
ErrorCode::InvalidHandle,
format!("Invalid {} handle: {}", name, handle),
)
}
}
| 31.039344 | 100 | 0.586669 |
2f4606a92818a423a160857c3e13da9da77adca8 | 1,559 | #[macro_use]
extern crate cpython;
use std::{
cell::RefCell,
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use cpython::{PyResult, Python};
use midas_rs::{default, Float, Int, MidasR as MidasR_, MidasRParams};
py_module_initializer!(midas, initmidas, PyInit_midas, |py, module| {
module.add(py, "__doc__", "MidasR implementation")?;
module.add(py, "hash", py_fn!(py, hash(string: String)))?;
module.add_class::<MidasR>(py)?;
Ok(())
});
fn hash(_py: Python, string: String) -> PyResult<Int> {
let mut hasher = DefaultHasher::new();
string.hash(&mut hasher);
Ok(hasher.finish() as Int)
}
py_class!(class MidasR |py| {
data value: RefCell<MidasR_>;
def __new__(
_cls,
rows: Int = default::NUM_ROWS,
buckets: Int = default::NUM_BUCKETS,
m_value: Int = default::M_VALUE,
alpha: Float = default::ALPHA
) -> PyResult<MidasR> {
MidasR::create_instance(py, RefCell::new(MidasR_::new(MidasRParams {
rows, buckets, m_value, alpha
})))
}
def insert(&self, source: Int, dest: Int, time: Int) -> PyResult<Float> {
Ok(self.value(py).borrow_mut().insert((source, dest, time)))
}
def query(&self, source: Int, dest: Int) -> PyResult<Float> {
Ok(self.value(py).borrow().query(source, dest))
}
def current_time(&self) -> PyResult<Int> {
Ok(self.value(py).borrow().current_time())
}
def alpha(&self) -> PyResult<Float> {
Ok(self.value(py).borrow().alpha())
}
});
| 27.350877 | 77 | 0.609365 |
6940425d3eeba28921bb47808674640e4faa7195 | 4,148 | use emd_c::{SignatureT, DistFeaturesT, emd_call};
pub fn emd(doc_bow1: &[f32], doc_bow2: &[f32], distance_matrix: &[f32]) -> f32 {
let (features1, weights1) = bow_to_features_weights(doc_bow1);
let (features2, weights2) = bow_to_features_weights(doc_bow2);
unsafe {
emd_call(
&mut SignatureT::new(features1.as_slice(), weights1.as_slice()),
&mut SignatureT::new(features2.as_slice(), weights2.as_slice()),
&mut DistFeaturesT::new(distance_matrix)
)
}
}
fn bow_to_features_weights(doc_bow: &[f32]) -> (Vec<i32>, Vec<f32>) {
let mut features: Vec<i32> = vec![];
let weights: Vec<f32> = doc_bow
.iter()
.enumerate()
.filter_map(|(i, w)|
if w < &1e-6f32 {
None
} else {
features.push(i as i32);
Some(*w)
})
.collect();
(features, weights)
}
#[cfg(test)]
mod testing {
use super::*;
#[test]
fn test_bow_to_features_weights() {
vec![
(vec![0f32; 5], vec![0i32; 0], vec![0f32; 0]),
(
vec![0.5f32, 0.0f32, 67.0f32, 0.01f32, 0.0f32, 105.567f32],
vec![0i32, 2i32, 3i32, 5i32],
vec![0.5f32, 67.0f32, 0.01f32, 105.567f32]
),
].into_iter()
.for_each(|(doc_bow, features_expected, weights_expected)| {
let (features_exist, weights_exist) = bow_to_features_weights(&doc_bow);
assert_eq!(features_exist.len(), weights_exist.len());
assert_eq!(features_exist, features_expected);
assert_eq!(weights_exist, weights_expected);
});
}
#[cfg(not(feature = "dumb"))]
#[test]
fn test_emd() {
let doc_bow1: &[f32] = &[0.5, 0.5, 0.0, 0.0];
let doc_bow2: &[f32] = &[0.0, 0.0, 0.5, 0.5];
let distance_matrix: &[f32] = &[
0., 0., 16.03984642, 22.11830902,
0., 0., 17.83054543, 14.92696762,
0., 0., 0., 0.,
0., 0., 0., 0.,
];
let exist = emd(&doc_bow1, &doc_bow2, &distance_matrix);
let expected = 15.483407f32;
assert_eq!(exist, expected);
}
}
#[cfg(test)]
mod bench {
use super::*;
use utils::random_f;
use test::Bencher;
fn prepare_data(sz: usize) -> (Vec<f32>, Vec<f32>, Vec<f32>) {
let rnd = random_f(0.3f32, 100.0f32);
let doc_bow1: Vec<f32> = vec![0f32; sz].into_iter().map(|_| rnd()).collect();
let doc_bow2: Vec<f32> = vec![0f32; sz].into_iter().map(|_| rnd()).collect();
let mut distance_matrix: Vec<f32> = vec![0f32; sz * sz];
{
let mut distance_2d: Vec<&mut [f32]> = distance_matrix.chunks_mut(sz).collect();
(0..sz).for_each(|i|
(i + 1..sz).for_each(|j| {
let value = rnd();
distance_2d[i][j] = value;
distance_2d[j][j] = value;
})
);
}
(doc_bow1, doc_bow2, distance_matrix)
}
fn bench_emd(sz: usize, b: &mut Bencher) {
let (doc_bow1, doc_bow2, distance_matrix) = prepare_data(sz);
b.iter(move || emd(&doc_bow1, &doc_bow2, &distance_matrix))
}
#[bench]
fn bench_emd_10(b: &mut Bencher) {
bench_emd(10, b);
}
#[bench]
fn bench_emd_20(b: &mut Bencher) {
bench_emd(20, b);
}
#[bench]
fn bench_emd_30(b: &mut Bencher) {
bench_emd(30, b);
}
#[bench]
fn bench_emd_40(b: &mut Bencher) {
bench_emd(40, b);
}
#[bench]
fn bench_emd_50(b: &mut Bencher) {
bench_emd(50, b);
}
#[bench]
fn bench_emd_60(b: &mut Bencher) {
bench_emd(60, b);
}
#[bench]
fn bench_emd_70(b: &mut Bencher) {
bench_emd(70, b);
}
#[bench]
fn bench_emd_80(b: &mut Bencher) {
bench_emd(80, b);
}
#[bench]
fn bench_emd_90(b: &mut Bencher) {
bench_emd(90, b);
}
#[bench]
fn bench_emd_100(b: &mut Bencher) {
bench_emd(100, b);
}
} | 25.925 | 92 | 0.511331 |
6a45b9d9ecde756f2343f9b484b366b9110767ae | 2,927 | // -*- mode: rust; -*-
//
// This file is part of dalek-frost.
// Copyright (c) 2020 isis lovecruft
// See LICENSE for licensing information.
//
// Authors:
// - isis agora lovecruft <[email protected]>
//! Zero-knowledge proofs.
use k256::AffinePoint;
use k256::ProjectivePoint;
use k256::Scalar;
#[cfg(feature = "std")]
use k256::elliptic_curve::Field;
use k256::elliptic_curve::PrimeField;
use k256::elliptic_curve::group::GroupEncoding;
#[cfg(feature = "std")]
use rand::{CryptoRng, Rng};
use sha3::Digest;
use sha3::Keccak256;
/// A proof of knowledge of a secret key, created by making a Schnorr signature
/// with the secret key.
///
/// This proof is created by making a pseudo-Schnorr signature,
/// \\( \sigma\_i = (s\_i, r\_i) \\) using \\( a\_{i0} \\) (from
/// `frost_secp256k1::keygen::DistributedKeyGeneration::<RoundOne>::compute_share`)
/// as the secret key, such that \\( k \stackrel{\\$}{\leftarrow} \mathbb{Z}\_q \\),
/// \\( M\_i = g^k \\), \\( s\_i = \mathcal{H}(i, \phi, g^{a\_{i0}}, M\_i) \\),
/// \\( r\_i = k + a\_{i0} \cdot s\_i \\).
///
/// Verification is done by calculating \\(M'\_i = g^r + A\_i^{-s}\\),
/// where \\(A\_i = g^{a_i}\\), and using it to compute
/// \\(s'\_i = \mathcal{H}(i, \phi, A\_i, M'\_i)\\), then finally
/// \\(s\_i \stackrel{?}{=} s'\_i\\).
#[derive(Clone, Debug)]
pub struct NizkOfSecretKey {
/// The scalar portion of the Schnorr signature encoding the context.
pub s: Scalar,
/// The scalar portion of the Schnorr signature which is the actual signature.
pub r: Scalar,
}
impl NizkOfSecretKey {
/// Prove knowledge of a secret key.
#[cfg(feature = "std")]
pub fn prove(
index: &u32,
secret_key: &Scalar,
public_key: &AffinePoint,
mut csprng: impl Rng + CryptoRng,
) -> Self
{
let k: Scalar = Scalar::random(&mut csprng);
let M: ProjectivePoint = AffinePoint::GENERATOR * &k;
let mut hram = Keccak256::default();
hram.update(&index.to_be_bytes());
hram.update(b"\xCE\xA6");
hram.update(&public_key.to_bytes());
hram.update(&M.to_affine().to_bytes());
let s = Scalar::from_repr(hram.finalize()).unwrap();
let r = k + (secret_key * &s);
NizkOfSecretKey { s, r }
}
/// Verify that the prover does indeed know the secret key.
pub fn verify(&self, index: &u32, public_key: &AffinePoint) -> Result<(), ()> {
let M_prime: ProjectivePoint = (AffinePoint::GENERATOR * &self.r) + (*public_key * &-self.s);
let mut hram = Keccak256::default();
hram.update(&index.to_be_bytes());
hram.update(b"\xCE\xA6");
hram.update(&public_key.to_bytes());
hram.update(&M_prime.to_affine().to_bytes());
let s_prime = Scalar::from_repr(hram.finalize()).unwrap();
if self.s == s_prime {
return Ok(());
}
Err(())
}
}
| 31.138298 | 101 | 0.599932 |
67602786aa64b9a4dbff5c5ca1fb3119eaed083c | 4,300 | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use crate::translate::*;
use crate::MainContext;
crate::wrapper! {
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Source(Shared<ffi::GSource>);
match fn {
ref => |ptr| ffi::g_source_ref(ptr),
unref => |ptr| ffi::g_source_unref(ptr),
get_type => || ffi::g_source_get_type(),
}
}
impl Source {
//#[doc(alias = "g_source_new")]
//pub fn new(source_funcs: /*Ignored*/&mut SourceFuncs, struct_size: u32) -> Source {
// unsafe { TODO: call ffi:g_source_new() }
//}
#[doc(alias = "g_source_add_child_source")]
pub fn add_child_source(&self, child_source: &Source) {
unsafe {
ffi::g_source_add_child_source(self.to_glib_none().0, child_source.to_glib_none().0);
}
}
//#[doc(alias = "g_source_add_poll")]
//pub fn add_poll(&self, fd: /*Ignored*/&mut PollFD) {
// unsafe { TODO: call ffi:g_source_add_poll() }
//}
//#[doc(alias = "g_source_add_unix_fd")]
//pub fn add_unix_fd(&self, fd: i32, events: IOCondition) -> /*Unimplemented*/Fundamental: Pointer {
// unsafe { TODO: call ffi:g_source_add_unix_fd() }
//}
#[doc(alias = "g_source_destroy")]
pub fn destroy(&self) {
unsafe {
ffi::g_source_destroy(self.to_glib_none().0);
}
}
#[doc(alias = "g_source_get_can_recurse")]
pub fn get_can_recurse(&self) -> bool {
unsafe { from_glib(ffi::g_source_get_can_recurse(self.to_glib_none().0)) }
}
#[doc(alias = "g_source_get_context")]
pub fn get_context(&self) -> Option<MainContext> {
unsafe { from_glib_none(ffi::g_source_get_context(self.to_glib_none().0)) }
}
#[doc(alias = "g_source_get_name")]
pub fn get_name(&self) -> Option<crate::GString> {
unsafe { from_glib_none(ffi::g_source_get_name(self.to_glib_none().0)) }
}
#[doc(alias = "g_source_get_priority")]
pub fn get_priority(&self) -> i32 {
unsafe { ffi::g_source_get_priority(self.to_glib_none().0) }
}
#[doc(alias = "g_source_get_ready_time")]
pub fn get_ready_time(&self) -> i64 {
unsafe { ffi::g_source_get_ready_time(self.to_glib_none().0) }
}
#[doc(alias = "g_source_get_time")]
pub fn get_time(&self) -> i64 {
unsafe { ffi::g_source_get_time(self.to_glib_none().0) }
}
#[doc(alias = "g_source_is_destroyed")]
pub fn is_destroyed(&self) -> bool {
unsafe { from_glib(ffi::g_source_is_destroyed(self.to_glib_none().0)) }
}
//#[doc(alias = "g_source_modify_unix_fd")]
//pub fn modify_unix_fd(&self, tag: /*Unimplemented*/Fundamental: Pointer, new_events: IOCondition) {
// unsafe { TODO: call ffi:g_source_modify_unix_fd() }
//}
//#[doc(alias = "g_source_query_unix_fd")]
//pub fn query_unix_fd(&self, tag: /*Unimplemented*/Fundamental: Pointer) -> IOCondition {
// unsafe { TODO: call ffi:g_source_query_unix_fd() }
//}
#[doc(alias = "g_source_remove_child_source")]
pub fn remove_child_source(&self, child_source: &Source) {
unsafe {
ffi::g_source_remove_child_source(self.to_glib_none().0, child_source.to_glib_none().0);
}
}
//#[doc(alias = "g_source_remove_poll")]
//pub fn remove_poll(&self, fd: /*Ignored*/&mut PollFD) {
// unsafe { TODO: call ffi:g_source_remove_poll() }
//}
//#[doc(alias = "g_source_remove_unix_fd")]
//pub fn remove_unix_fd(&self, tag: /*Unimplemented*/Fundamental: Pointer) {
// unsafe { TODO: call ffi:g_source_remove_unix_fd() }
//}
//#[doc(alias = "g_source_remove_by_funcs_user_data")]
//pub fn remove_by_funcs_user_data(funcs: /*Ignored*/&mut SourceFuncs, user_data: /*Unimplemented*/Option<Fundamental: Pointer>) -> bool {
// unsafe { TODO: call ffi:g_source_remove_by_funcs_user_data() }
//}
//#[doc(alias = "g_source_remove_by_user_data")]
//pub fn remove_by_user_data(user_data: /*Unimplemented*/Option<Fundamental: Pointer>) -> bool {
// unsafe { TODO: call ffi:g_source_remove_by_user_data() }
//}
}
unsafe impl Send for Source {}
unsafe impl Sync for Source {}
| 34.677419 | 142 | 0.634419 |
69babf27fbb778e3b6cb57df708052934b52ed73 | 7,416 | // Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use common_datavalues::DataSchemaRef;
use common_exception::ErrorCode;
use common_exception::Result;
use common_planners::*;
use common_tracing::tracing;
use crate::optimizers::Optimizer;
use crate::sessions::QueryContext;
pub struct TopNPushDownOptimizer {}
// TODO: left/right outer join can also apply top_n push down. For example,
// 'select * from A left join B where A.id = B.id order by A.id limit 10;'
// The top_n can be pushed down to table A.
struct TopNPushDownImpl {
before_group_by_schema: Option<DataSchemaRef>,
limit: Option<usize>,
order_by: Vec<Expression>,
}
impl PlanRewriter for TopNPushDownImpl {
fn rewrite_aggregate_partial(&mut self, plan: &AggregatorPartialPlan) -> Result<PlanNode> {
let new_input = self.rewrite_plan_node(&plan.input)?;
match self.before_group_by_schema {
Some(_) => Err(ErrorCode::LogicalError(
"Logical error: before group by schema must be None",
)),
None => {
self.before_group_by_schema = Some(new_input.schema());
let new_aggr_expr = self.rewrite_exprs(&new_input.schema(), &plan.aggr_expr)?;
let new_group_expr = self.rewrite_exprs(&new_input.schema(), &plan.group_expr)?;
PlanBuilder::from(&new_input)
.aggregate_partial(&new_aggr_expr, &new_group_expr)?
.build()
}
}
}
fn rewrite_aggregate_final(&mut self, plan: &AggregatorFinalPlan) -> Result<PlanNode> {
// With any aggregation in the plan pipeline, we clear the top n option.
self.limit = None;
let new_input = self.rewrite_plan_node(&plan.input)?;
match self.before_group_by_schema.take() {
None => Err(ErrorCode::LogicalError(
"Logical error: before group by schema must be Some",
)),
Some(schema_before_group_by) => {
let new_aggr_expr = self.rewrite_exprs(&new_input.schema(), &plan.aggr_expr)?;
let new_group_expr = self.rewrite_exprs(&new_input.schema(), &plan.group_expr)?;
PlanBuilder::from(&new_input)
.aggregate_final(schema_before_group_by, &new_aggr_expr, &new_group_expr)?
.build()
}
}
}
fn rewrite_limit(&mut self, plan: &LimitPlan) -> Result<PlanNode> {
let current_limit = self.limit;
let current_order_by = self.order_by.clone();
match plan.n {
Some(limit) if limit > 0 => self.limit = Some(limit + plan.offset),
_ => {}
}
let new_input = self.rewrite_plan_node(plan.input.as_ref())?;
let plan_node = PlanBuilder::from(&new_input)
.limit_offset(plan.n, plan.offset)?
.build();
self.limit = current_limit; // recover back to previous state
self.order_by = current_order_by;
plan_node
}
fn rewrite_read_data_source(&mut self, plan: &ReadDataSourcePlan) -> Result<PlanNode> {
// push the limit and order_by down to read_source_plan
if let Some(n) = self.limit {
let mut new_plan = plan.clone();
new_plan.push_downs = match &plan.push_downs {
Some(extras) => {
let new_limit = if let Some(current_limit) = extras.limit {
n.min(current_limit)
} else {
n
};
Some(Extras {
projection: extras.projection.clone(),
filters: extras.filters.clone(),
limit: Some(new_limit),
order_by: self.get_sort_columns(plan.schema())?,
})
}
None => {
let mut extras = Extras::default();
extras.limit = Some(n);
extras.order_by = self.get_sort_columns(plan.schema())?;
Some(extras)
}
};
return Ok(PlanNode::ReadSource(new_plan));
}
Ok(PlanNode::ReadSource(plan.clone()))
}
fn rewrite_subquery_plan(&mut self, subquery_plan: &PlanNode) -> Result<PlanNode> {
let mut optimizer = TopNPushDownOptimizer {};
optimizer.optimize(subquery_plan)
}
fn rewrite_sort(&mut self, plan: &SortPlan) -> Result<PlanNode> {
if self.limit.is_some() {
self.order_by = plan.order_by.clone();
}
let new_input = self.rewrite_plan_node(plan.input.as_ref())?;
let new_order_by = self.rewrite_exprs(&new_input.schema(), &plan.order_by)?;
PlanBuilder::from(&new_input).sort(&new_order_by)?.build()
}
}
impl TopNPushDownImpl {
pub fn new() -> TopNPushDownImpl {
TopNPushDownImpl {
before_group_by_schema: None,
limit: None,
order_by: vec![],
}
}
// For every order by columns, try the best to extract the native columns.
// For example 'order by age+3, number+5', will return expression of two columns,
// 'age' and 'number', since f(age)=age+3 and f(number)=number+5 are both monotonic functions.
fn get_sort_columns(&self, schema: DataSchemaRef) -> Result<Vec<Expression>> {
self.order_by
.iter()
.map(|expr| {
let columns = RequireColumnsVisitor::collect_columns_from_expr(expr)?;
if columns.len() != 1 {
// if 0 or >1 columns found, skip the monotonicity optimization.
return Ok(expr.clone());
}
let column_name = columns.iter().next().unwrap();
match ExpressionMonotonicityVisitor::extract_sort_column(
schema.clone(),
expr,
column_name,
) {
Ok(new_expr) => Ok(new_expr),
Err(error) => {
tracing::error!(
"Failed to extract column from sort expression {:?}, {}",
expr,
error
);
Ok(expr.clone())
}
}
})
.collect::<Result<Vec<_>>>()
}
}
impl Optimizer for TopNPushDownOptimizer {
fn name(&self) -> &str {
"TopNPushDown"
}
fn optimize(&mut self, plan: &PlanNode) -> Result<PlanNode> {
let mut visitor = TopNPushDownImpl::new();
visitor.rewrite_plan_node(plan)
}
}
impl TopNPushDownOptimizer {
pub fn create(_ctx: Arc<QueryContext>) -> TopNPushDownOptimizer {
TopNPushDownOptimizer {}
}
}
| 36.895522 | 98 | 0.570119 |
7abc998d3882fccc0ebfd88dd40df276b859b113 | 52,623 | //! A pass that promotes borrows of constant rvalues.
//!
//! The rvalues considered constant are trees of temps,
//! each with exactly one initialization, and holding
//! a constant value with no interior mutability.
//! They are placed into a new MIR constant body in
//! `promoted` and the borrow rvalue is replaced with
//! a `Literal::Promoted` using the index into `promoted`
//! of that constant MIR.
//!
//! This pass assumes that every use is dominated by an
//! initialization and can otherwise silence errors, if
//! move analysis runs after promotion on broken MIR.
use rustc_ast::LitKind;
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_middle::mir::traversal::ReversePostorder;
use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
use rustc_middle::mir::*;
use rustc_middle::ty::cast::CastTy;
use rustc_middle::ty::subst::InternalSubsts;
use rustc_middle::ty::{self, List, TyCtxt, TypeFoldable};
use rustc_span::symbol::sym;
use rustc_span::{Span, DUMMY_SP};
use rustc_index::vec::{Idx, IndexVec};
use rustc_target::spec::abi::Abi;
use std::cell::Cell;
use std::{cmp, iter, mem};
use crate::const_eval::{is_const_fn, is_unstable_const_fn};
use crate::transform::check_consts::{is_lang_panic_fn, qualifs, ConstCx};
use crate::transform::MirPass;
/// A `MirPass` for promotion.
///
/// Promotion is the extraction of promotable temps into separate MIR bodies. This pass also emits
/// errors when promotion of `#[rustc_args_required_const]` arguments fails.
///
/// After this pass is run, `promoted_fragments` will hold the MIR body corresponding to each
/// newly created `Constant`.
#[derive(Default)]
pub struct PromoteTemps<'tcx> {
pub promoted_fragments: Cell<IndexVec<Promoted, Body<'tcx>>>,
}
impl<'tcx> MirPass<'tcx> for PromoteTemps<'tcx> {
fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
// There's not really any point in promoting errorful MIR.
//
// This does not include MIR that failed const-checking, which we still try to promote.
if body.return_ty().references_error() {
tcx.sess.delay_span_bug(body.span, "PromoteTemps: MIR had errors");
return;
}
if body.source.promoted.is_some() {
return;
}
let mut rpo = traversal::reverse_postorder(body);
let ccx = ConstCx::new(tcx, body);
let (temps, all_candidates) = collect_temps_and_candidates(&ccx, &mut rpo);
let promotable_candidates = validate_candidates(&ccx, &temps, &all_candidates);
let promoted = promote_candidates(body, tcx, temps, promotable_candidates);
self.promoted_fragments.set(promoted);
}
}
/// State of a temporary during collection and promotion.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum TempState {
/// No references to this temp.
Undefined,
/// One direct assignment and any number of direct uses.
/// A borrow of this temp is promotable if the assigned
/// value is qualified as constant.
Defined { location: Location, uses: usize },
/// Any other combination of assignments/uses.
Unpromotable,
/// This temp was part of an rvalue which got extracted
/// during promotion and needs cleanup.
PromotedOut,
}
impl TempState {
pub fn is_promotable(&self) -> bool {
debug!("is_promotable: self={:?}", self);
matches!(self, TempState::Defined { .. } )
}
}
/// A "root candidate" for promotion, which will become the
/// returned value in a promoted MIR, unless it's a subset
/// of a larger candidate.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum Candidate {
/// Borrow of a constant temporary, candidate for lifetime extension.
Ref(Location),
/// Promotion of the `x` in `[x; 32]`.
Repeat(Location),
/// Currently applied to function calls where the callee has the unstable
/// `#[rustc_args_required_const]` attribute as well as the SIMD shuffle
/// intrinsic. The intrinsic requires the arguments are indeed constant and
/// the attribute currently provides the semantic requirement that arguments
/// must be constant.
Argument { bb: BasicBlock, index: usize },
/// `const` operand in asm!.
InlineAsm { bb: BasicBlock, index: usize },
}
impl Candidate {
/// Returns `true` if we should use the "explicit" rules for promotability for this `Candidate`.
fn forces_explicit_promotion(&self) -> bool {
match self {
Candidate::Ref(_) | Candidate::Repeat(_) => false,
Candidate::Argument { .. } | Candidate::InlineAsm { .. } => true,
}
}
}
fn args_required_const(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Vec<usize>> {
let attrs = tcx.get_attrs(def_id);
let attr = attrs.iter().find(|a| tcx.sess.check_name(a, sym::rustc_args_required_const))?;
let mut ret = vec![];
for meta in attr.meta_item_list()? {
match meta.literal()?.kind {
LitKind::Int(a, _) => {
ret.push(a as usize);
}
_ => bug!("invalid arg index"),
}
}
Some(ret)
}
struct Collector<'a, 'tcx> {
ccx: &'a ConstCx<'a, 'tcx>,
temps: IndexVec<Local, TempState>,
candidates: Vec<Candidate>,
}
impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
fn visit_local(&mut self, &index: &Local, context: PlaceContext, location: Location) {
debug!("visit_local: index={:?} context={:?} location={:?}", index, context, location);
// We're only interested in temporaries and the return place
match self.ccx.body.local_kind(index) {
LocalKind::Temp | LocalKind::ReturnPointer => {}
LocalKind::Arg | LocalKind::Var => return,
}
// Ignore drops, if the temp gets promoted,
// then it's constant and thus drop is noop.
// Non-uses are also irrelevant.
if context.is_drop() || !context.is_use() {
debug!(
"visit_local: context.is_drop={:?} context.is_use={:?}",
context.is_drop(),
context.is_use(),
);
return;
}
let temp = &mut self.temps[index];
debug!("visit_local: temp={:?}", temp);
if *temp == TempState::Undefined {
match context {
PlaceContext::MutatingUse(MutatingUseContext::Store)
| PlaceContext::MutatingUse(MutatingUseContext::Call) => {
*temp = TempState::Defined { location, uses: 0 };
return;
}
_ => { /* mark as unpromotable below */ }
}
} else if let TempState::Defined { ref mut uses, .. } = *temp {
// We always allow borrows, even mutable ones, as we need
// to promote mutable borrows of some ZSTs e.g., `&mut []`.
let allowed_use = match context {
PlaceContext::MutatingUse(MutatingUseContext::Borrow)
| PlaceContext::NonMutatingUse(_) => true,
PlaceContext::MutatingUse(_) | PlaceContext::NonUse(_) => false,
};
debug!("visit_local: allowed_use={:?}", allowed_use);
if allowed_use {
*uses += 1;
return;
}
/* mark as unpromotable below */
}
*temp = TempState::Unpromotable;
}
fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
self.super_rvalue(rvalue, location);
match *rvalue {
Rvalue::Ref(..) => {
self.candidates.push(Candidate::Ref(location));
}
Rvalue::Repeat(..) if self.ccx.tcx.features().const_in_array_repeat_expressions => {
// FIXME(#49147) only promote the element when it isn't `Copy`
// (so that code that can copy it at runtime is unaffected).
self.candidates.push(Candidate::Repeat(location));
}
_ => {}
}
}
fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
self.super_terminator(terminator, location);
match terminator.kind {
TerminatorKind::Call { ref func, .. } => {
if let ty::FnDef(def_id, _) = *func.ty(self.ccx.body, self.ccx.tcx).kind() {
let fn_sig = self.ccx.tcx.fn_sig(def_id);
if let Abi::RustIntrinsic | Abi::PlatformIntrinsic = fn_sig.abi() {
let name = self.ccx.tcx.item_name(def_id);
// FIXME(eddyb) use `#[rustc_args_required_const(2)]` for shuffles.
if name.as_str().starts_with("simd_shuffle") {
self.candidates
.push(Candidate::Argument { bb: location.block, index: 2 });
return; // Don't double count `simd_shuffle` candidates
}
}
if let Some(constant_args) = args_required_const(self.ccx.tcx, def_id) {
for index in constant_args {
self.candidates.push(Candidate::Argument { bb: location.block, index });
}
}
}
}
TerminatorKind::InlineAsm { ref operands, .. } => {
for (index, op) in operands.iter().enumerate() {
if let InlineAsmOperand::Const { .. } = op {
self.candidates.push(Candidate::InlineAsm { bb: location.block, index })
}
}
}
_ => {}
}
}
}
pub fn collect_temps_and_candidates(
ccx: &ConstCx<'mir, 'tcx>,
rpo: &mut ReversePostorder<'_, 'tcx>,
) -> (IndexVec<Local, TempState>, Vec<Candidate>) {
let mut collector = Collector {
temps: IndexVec::from_elem(TempState::Undefined, &ccx.body.local_decls),
candidates: vec![],
ccx,
};
for (bb, data) in rpo {
collector.visit_basic_block_data(bb, data);
}
(collector.temps, collector.candidates)
}
/// Checks whether locals that appear in a promotion context (`Candidate`) are actually promotable.
///
/// This wraps an `Item`, and has access to all fields of that `Item` via `Deref` coercion.
struct Validator<'a, 'tcx> {
ccx: &'a ConstCx<'a, 'tcx>,
temps: &'a IndexVec<Local, TempState>,
/// Explicit promotion happens e.g. for constant arguments declared via
/// `rustc_args_required_const`.
/// Implicit promotion has almost the same rules, except that disallows `const fn`
/// except for those marked `#[rustc_promotable]`. This is to avoid changing
/// a legitimate run-time operation into a failing compile-time operation
/// e.g. due to addresses being compared inside the function.
explicit: bool,
}
impl std::ops::Deref for Validator<'a, 'tcx> {
type Target = ConstCx<'a, 'tcx>;
fn deref(&self) -> &Self::Target {
&self.ccx
}
}
struct Unpromotable;
impl<'tcx> Validator<'_, 'tcx> {
/// Determines if this code could be executed at runtime and thus is subject to codegen.
/// That means even unused constants need to be evaluated.
///
/// `const_kind` should not be used in this file other than through this method!
fn maybe_runtime(&self) -> bool {
match self.const_kind {
None | Some(hir::ConstContext::ConstFn) => true,
Some(hir::ConstContext::Static(_) | hir::ConstContext::Const) => false,
}
}
fn validate_candidate(&self, candidate: Candidate) -> Result<(), Unpromotable> {
match candidate {
Candidate::Ref(loc) => {
assert!(!self.explicit);
let statement = &self.body[loc.block].statements[loc.statement_index];
match &statement.kind {
StatementKind::Assign(box (_, Rvalue::Ref(_, kind, place))) => {
match kind {
BorrowKind::Shared | BorrowKind::Mut { .. } => {}
// FIXME(eddyb) these aren't promoted here but *could*
// be promoted as part of a larger value because
// `validate_rvalue` doesn't check them, need to
// figure out what is the intended behavior.
BorrowKind::Shallow | BorrowKind::Unique => return Err(Unpromotable),
}
// We can only promote interior borrows of promotable temps (non-temps
// don't get promoted anyway).
self.validate_local(place.local)?;
if place.projection.contains(&ProjectionElem::Deref) {
return Err(Unpromotable);
}
let mut has_mut_interior =
self.qualif_local::<qualifs::HasMutInterior>(place.local);
// HACK(eddyb) this should compute the same thing as
// `<HasMutInterior as Qualif>::in_projection` from
// `check_consts::qualifs` but without recursion.
if has_mut_interior {
// This allows borrowing fields which don't have
// `HasMutInterior`, from a type that does, e.g.:
// `let _: &'static _ = &(Cell::new(1), 2).1;`
let mut place_projection = &place.projection[..];
// FIXME(eddyb) use a forward loop instead of a reverse one.
while let &[ref proj_base @ .., elem] = place_projection {
// FIXME(eddyb) this is probably excessive, with
// the exception of `union` member accesses.
let ty =
Place::ty_from(place.local, proj_base, self.body, self.tcx)
.projection_ty(self.tcx, elem)
.ty;
if ty.is_freeze(self.tcx.at(DUMMY_SP), self.param_env) {
has_mut_interior = false;
break;
}
place_projection = proj_base;
}
}
// FIXME(eddyb) this duplicates part of `validate_rvalue`.
if has_mut_interior {
return Err(Unpromotable);
}
if self.qualif_local::<qualifs::NeedsDrop>(place.local) {
return Err(Unpromotable);
}
if let BorrowKind::Mut { .. } = kind {
let ty = place.ty(self.body, self.tcx).ty;
// In theory, any zero-sized value could be borrowed
// mutably without consequences. However, only &mut []
// is allowed right now.
if let ty::Array(_, len) = ty.kind() {
match len.try_eval_usize(self.tcx, self.param_env) {
Some(0) => {}
_ => return Err(Unpromotable),
}
} else {
return Err(Unpromotable);
}
}
Ok(())
}
_ => bug!(),
}
}
Candidate::Repeat(loc) => {
assert!(!self.explicit);
let statement = &self.body[loc.block].statements[loc.statement_index];
match &statement.kind {
StatementKind::Assign(box (_, Rvalue::Repeat(ref operand, _))) => {
if !self.tcx.features().const_in_array_repeat_expressions {
return Err(Unpromotable);
}
self.validate_operand(operand)
}
_ => bug!(),
}
}
Candidate::Argument { bb, index } => {
assert!(self.explicit);
let terminator = self.body[bb].terminator();
match &terminator.kind {
TerminatorKind::Call { args, .. } => self.validate_operand(&args[index]),
_ => bug!(),
}
}
Candidate::InlineAsm { bb, index } => {
assert!(self.explicit);
let terminator = self.body[bb].terminator();
match &terminator.kind {
TerminatorKind::InlineAsm { operands, .. } => match &operands[index] {
InlineAsmOperand::Const { value } => self.validate_operand(value),
_ => bug!(),
},
_ => bug!(),
}
}
}
}
// FIXME(eddyb) maybe cache this?
fn qualif_local<Q: qualifs::Qualif>(&self, local: Local) -> bool {
if let TempState::Defined { location: loc, .. } = self.temps[local] {
let num_stmts = self.body[loc.block].statements.len();
if loc.statement_index < num_stmts {
let statement = &self.body[loc.block].statements[loc.statement_index];
match &statement.kind {
StatementKind::Assign(box (_, rhs)) => qualifs::in_rvalue::<Q, _>(
&self.ccx,
&mut |l| self.qualif_local::<Q>(l),
rhs,
),
_ => {
span_bug!(
statement.source_info.span,
"{:?} is not an assignment",
statement
);
}
}
} else {
let terminator = self.body[loc.block].terminator();
match &terminator.kind {
TerminatorKind::Call { .. } => {
let return_ty = self.body.local_decls[local].ty;
Q::in_any_value_of_ty(&self.ccx, return_ty)
}
kind => {
span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
}
}
}
} else {
let span = self.body.local_decls[local].source_info.span;
span_bug!(span, "{:?} not promotable, qualif_local shouldn't have been called", local);
}
}
// FIXME(eddyb) maybe cache this?
fn validate_local(&self, local: Local) -> Result<(), Unpromotable> {
if let TempState::Defined { location: loc, .. } = self.temps[local] {
let num_stmts = self.body[loc.block].statements.len();
if loc.statement_index < num_stmts {
let statement = &self.body[loc.block].statements[loc.statement_index];
match &statement.kind {
StatementKind::Assign(box (_, rhs)) => self.validate_rvalue(rhs),
_ => {
span_bug!(
statement.source_info.span,
"{:?} is not an assignment",
statement
);
}
}
} else {
let terminator = self.body[loc.block].terminator();
match &terminator.kind {
TerminatorKind::Call { func, args, .. } => self.validate_call(func, args),
TerminatorKind::Yield { .. } => Err(Unpromotable),
kind => {
span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
}
}
}
} else {
Err(Unpromotable)
}
}
fn validate_place(&self, place: PlaceRef<'tcx>) -> Result<(), Unpromotable> {
match place {
PlaceRef { local, projection: [] } => self.validate_local(local),
PlaceRef { local, projection: [proj_base @ .., elem] } => {
// Validate topmost projection, then recurse.
match *elem {
ProjectionElem::Deref => {
let mut promotable = false;
// This is a special treatment for cases like *&STATIC where STATIC is a
// global static variable.
// This pattern is generated only when global static variables are directly
// accessed and is qualified for promotion safely.
if let TempState::Defined { location, .. } = self.temps[local] {
let def_stmt =
self.body[location.block].statements.get(location.statement_index);
if let Some(Statement {
kind:
StatementKind::Assign(box (_, Rvalue::Use(Operand::Constant(c)))),
..
}) = def_stmt
{
if let Some(did) = c.check_static_ptr(self.tcx) {
// Evaluating a promoted may not read statics except if it got
// promoted from a static (this is a CTFE check). So we
// can only promote static accesses inside statics.
if let Some(hir::ConstContext::Static(..)) = self.const_kind {
// The `is_empty` predicate is introduced to exclude the case
// where the projection operations are [ .field, * ].
// The reason is because promotion will be illegal if field
// accesses precede the dereferencing.
// Discussion can be found at
// https://github.com/rust-lang/rust/pull/74945#discussion_r463063247
// There may be opportunity for generalization, but this needs to be
// accounted for.
if proj_base.is_empty()
&& !self.tcx.is_thread_local_static(did)
{
promotable = true;
}
}
}
}
}
if !promotable {
return Err(Unpromotable);
}
}
ProjectionElem::Downcast(..) => {
return Err(Unpromotable);
}
ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {}
ProjectionElem::Index(local) => {
self.validate_local(local)?;
}
ProjectionElem::Field(..) => {
if self.maybe_runtime() {
let base_ty =
Place::ty_from(place.local, proj_base, self.body, self.tcx).ty;
if let Some(def) = base_ty.ty_adt_def() {
// No promotion of union field accesses.
if def.is_union() {
return Err(Unpromotable);
}
}
}
}
}
self.validate_place(PlaceRef { local: place.local, projection: proj_base })
}
}
}
fn validate_operand(&self, operand: &Operand<'tcx>) -> Result<(), Unpromotable> {
match operand {
Operand::Copy(place) | Operand::Move(place) => self.validate_place(place.as_ref()),
// The qualifs for a constant (e.g. `HasMutInterior`) are checked in
// `validate_rvalue` upon access.
Operand::Constant(c) => {
if let Some(def_id) = c.check_static_ptr(self.tcx) {
// Only allow statics (not consts) to refer to other statics.
// FIXME(eddyb) does this matter at all for promotion?
// FIXME(RalfJung) it makes little sense to not promote this in `fn`/`const fn`,
// and in `const` this cannot occur anyway. The only concern is that we might
// promote even `let x = &STATIC` which would be useless, but this applies to
// promotion inside statics as well.
let is_static = matches!(self.const_kind, Some(hir::ConstContext::Static(_)));
if !is_static {
return Err(Unpromotable);
}
let is_thread_local = self.tcx.is_thread_local_static(def_id);
if is_thread_local {
return Err(Unpromotable);
}
}
Ok(())
}
}
}
fn validate_rvalue(&self, rvalue: &Rvalue<'tcx>) -> Result<(), Unpromotable> {
match *rvalue {
Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) => {
let operand_ty = operand.ty(self.body, self.tcx);
let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
if let (CastTy::Ptr(_) | CastTy::FnPtr, CastTy::Int(_)) = (cast_in, cast_out) {
// ptr-to-int casts are not possible in consts and thus not promotable
return Err(Unpromotable);
}
}
Rvalue::BinaryOp(op, ref lhs, _) => {
if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind() {
assert!(
op == BinOp::Eq
|| op == BinOp::Ne
|| op == BinOp::Le
|| op == BinOp::Lt
|| op == BinOp::Ge
|| op == BinOp::Gt
|| op == BinOp::Offset
);
// raw pointer operations are not allowed inside consts and thus not promotable
return Err(Unpromotable);
}
}
Rvalue::NullaryOp(NullOp::Box, _) => return Err(Unpromotable),
// FIXME(RalfJung): the rest is *implicitly considered promotable*... that seems dangerous.
_ => {}
}
match rvalue {
Rvalue::ThreadLocalRef(_) => Err(Unpromotable),
Rvalue::NullaryOp(..) => Ok(()),
Rvalue::Discriminant(place) | Rvalue::Len(place) => self.validate_place(place.as_ref()),
Rvalue::Use(operand)
| Rvalue::Repeat(operand, _)
| Rvalue::UnaryOp(_, operand)
| Rvalue::Cast(_, operand, _) => self.validate_operand(operand),
Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
self.validate_operand(lhs)?;
self.validate_operand(rhs)
}
Rvalue::AddressOf(_, place) => {
// We accept `&raw *`, i.e., raw reborrows -- creating a raw pointer is
// no problem, only using it is.
if let [proj_base @ .., ProjectionElem::Deref] = place.projection.as_ref() {
let base_ty = Place::ty_from(place.local, proj_base, self.body, self.tcx).ty;
if let ty::Ref(..) = base_ty.kind() {
return self.validate_place(PlaceRef {
local: place.local,
projection: proj_base,
});
}
}
Err(Unpromotable)
}
Rvalue::Ref(_, kind, place) => {
if let BorrowKind::Mut { .. } = kind {
let ty = place.ty(self.body, self.tcx).ty;
// In theory, any zero-sized value could be borrowed
// mutably without consequences. However, only &mut []
// is allowed right now.
if let ty::Array(_, len) = ty.kind() {
match len.try_eval_usize(self.tcx, self.param_env) {
Some(0) => {}
_ => return Err(Unpromotable),
}
} else {
return Err(Unpromotable);
}
}
// Special-case reborrows to be more like a copy of the reference.
let mut place = place.as_ref();
if let [proj_base @ .., ProjectionElem::Deref] = &place.projection {
let base_ty = Place::ty_from(place.local, proj_base, self.body, self.tcx).ty;
if let ty::Ref(..) = base_ty.kind() {
place = PlaceRef { local: place.local, projection: proj_base };
}
}
self.validate_place(place)?;
// HACK(eddyb) this should compute the same thing as
// `<HasMutInterior as Qualif>::in_projection` from
// `check_consts::qualifs` but without recursion.
let mut has_mut_interior =
self.qualif_local::<qualifs::HasMutInterior>(place.local);
if has_mut_interior {
let mut place_projection = place.projection;
// FIXME(eddyb) use a forward loop instead of a reverse one.
while let &[ref proj_base @ .., elem] = place_projection {
// FIXME(eddyb) this is probably excessive, with
// the exception of `union` member accesses.
let ty = Place::ty_from(place.local, proj_base, self.body, self.tcx)
.projection_ty(self.tcx, elem)
.ty;
if ty.is_freeze(self.tcx.at(DUMMY_SP), self.param_env) {
has_mut_interior = false;
break;
}
place_projection = proj_base;
}
}
if has_mut_interior {
return Err(Unpromotable);
}
Ok(())
}
Rvalue::Aggregate(_, ref operands) => {
for o in operands {
self.validate_operand(o)?;
}
Ok(())
}
}
}
fn validate_call(
&self,
callee: &Operand<'tcx>,
args: &[Operand<'tcx>],
) -> Result<(), Unpromotable> {
let fn_ty = callee.ty(self.body, self.tcx);
if !self.explicit && self.maybe_runtime() {
if let ty::FnDef(def_id, _) = *fn_ty.kind() {
// Never promote runtime `const fn` calls of
// functions without `#[rustc_promotable]`.
if !self.tcx.is_promotable_const_fn(def_id) {
return Err(Unpromotable);
}
}
}
let is_const_fn = match *fn_ty.kind() {
ty::FnDef(def_id, _) => {
is_const_fn(self.tcx, def_id)
|| is_unstable_const_fn(self.tcx, def_id).is_some()
|| is_lang_panic_fn(self.tcx, def_id)
}
_ => false,
};
if !is_const_fn {
return Err(Unpromotable);
}
self.validate_operand(callee)?;
for arg in args {
self.validate_operand(arg)?;
}
Ok(())
}
}
// FIXME(eddyb) remove the differences for promotability in `static`, `const`, `const fn`.
pub fn validate_candidates(
ccx: &ConstCx<'_, '_>,
temps: &IndexVec<Local, TempState>,
candidates: &[Candidate],
) -> Vec<Candidate> {
let mut validator = Validator { ccx, temps, explicit: false };
candidates
.iter()
.copied()
.filter(|&candidate| {
validator.explicit = candidate.forces_explicit_promotion();
// FIXME(eddyb) also emit the errors for shuffle indices
// and `#[rustc_args_required_const]` arguments here.
let is_promotable = validator.validate_candidate(candidate).is_ok();
// If we use explicit validation, we carry the risk of turning a legitimate run-time
// operation into a failing compile-time operation. Make sure that does not happen
// by asserting that there is no possible run-time behavior here in case promotion
// fails.
if validator.explicit && !is_promotable {
ccx.tcx.sess.delay_span_bug(
ccx.body.span,
"Explicit promotion requested, but failed to promote",
);
}
match candidate {
Candidate::Argument { bb, index } | Candidate::InlineAsm { bb, index }
if !is_promotable =>
{
let span = ccx.body[bb].terminator().source_info.span;
let msg = format!("argument {} is required to be a constant", index + 1);
ccx.tcx.sess.span_err(span, &msg);
}
_ => (),
}
is_promotable
})
.collect()
}
struct Promoter<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
source: &'a mut Body<'tcx>,
promoted: Body<'tcx>,
temps: &'a mut IndexVec<Local, TempState>,
extra_statements: &'a mut Vec<(Location, Statement<'tcx>)>,
/// If true, all nested temps are also kept in the
/// source MIR, not moved to the promoted MIR.
keep_original: bool,
}
impl<'a, 'tcx> Promoter<'a, 'tcx> {
fn new_block(&mut self) -> BasicBlock {
let span = self.promoted.span;
self.promoted.basic_blocks_mut().push(BasicBlockData {
statements: vec![],
terminator: Some(Terminator {
source_info: SourceInfo::outermost(span),
kind: TerminatorKind::Return,
}),
is_cleanup: false,
})
}
fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
let last = self.promoted.basic_blocks().last().unwrap();
let data = &mut self.promoted[last];
data.statements.push(Statement {
source_info: SourceInfo::outermost(span),
kind: StatementKind::Assign(box (Place::from(dest), rvalue)),
});
}
fn is_temp_kind(&self, local: Local) -> bool {
self.source.local_kind(local) == LocalKind::Temp
}
/// Copies the initialization of this temp to the
/// promoted MIR, recursing through temps.
fn promote_temp(&mut self, temp: Local) -> Local {
let old_keep_original = self.keep_original;
let loc = match self.temps[temp] {
TempState::Defined { location, uses } if uses > 0 => {
if uses > 1 {
self.keep_original = true;
}
location
}
state => {
span_bug!(self.promoted.span, "{:?} not promotable: {:?}", temp, state);
}
};
if !self.keep_original {
self.temps[temp] = TempState::PromotedOut;
}
let num_stmts = self.source[loc.block].statements.len();
let new_temp = self.promoted.local_decls.push(LocalDecl::new(
self.source.local_decls[temp].ty,
self.source.local_decls[temp].source_info.span,
));
debug!("promote({:?} @ {:?}/{:?}, {:?})", temp, loc, num_stmts, self.keep_original);
// First, take the Rvalue or Call out of the source MIR,
// or duplicate it, depending on keep_original.
if loc.statement_index < num_stmts {
let (mut rvalue, source_info) = {
let statement = &mut self.source[loc.block].statements[loc.statement_index];
let rhs = match statement.kind {
StatementKind::Assign(box (_, ref mut rhs)) => rhs,
_ => {
span_bug!(
statement.source_info.span,
"{:?} is not an assignment",
statement
);
}
};
(
if self.keep_original {
rhs.clone()
} else {
let unit = Rvalue::Use(Operand::Constant(box Constant {
span: statement.source_info.span,
user_ty: None,
literal: ty::Const::zero_sized(self.tcx, self.tcx.types.unit),
}));
mem::replace(rhs, unit)
},
statement.source_info,
)
};
self.visit_rvalue(&mut rvalue, loc);
self.assign(new_temp, rvalue, source_info.span);
} else {
let terminator = if self.keep_original {
self.source[loc.block].terminator().clone()
} else {
let terminator = self.source[loc.block].terminator_mut();
let target = match terminator.kind {
TerminatorKind::Call { destination: Some((_, target)), .. } => target,
ref kind => {
span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
}
};
Terminator {
source_info: terminator.source_info,
kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto { target }),
}
};
match terminator.kind {
TerminatorKind::Call { mut func, mut args, from_hir_call, fn_span, .. } => {
self.visit_operand(&mut func, loc);
for arg in &mut args {
self.visit_operand(arg, loc);
}
let last = self.promoted.basic_blocks().last().unwrap();
let new_target = self.new_block();
*self.promoted[last].terminator_mut() = Terminator {
kind: TerminatorKind::Call {
func,
args,
cleanup: None,
destination: Some((Place::from(new_temp), new_target)),
from_hir_call,
fn_span,
},
..terminator
};
}
ref kind => {
span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
}
};
};
self.keep_original = old_keep_original;
new_temp
}
fn promote_candidate(
mut self,
candidate: Candidate,
next_promoted_id: usize,
) -> Option<Body<'tcx>> {
let def = self.source.source.with_opt_param();
let mut rvalue = {
let promoted = &mut self.promoted;
let promoted_id = Promoted::new(next_promoted_id);
let tcx = self.tcx;
let mut promoted_operand = |ty, span| {
promoted.span = span;
promoted.local_decls[RETURN_PLACE] = LocalDecl::new(ty, span);
Operand::Constant(Box::new(Constant {
span,
user_ty: None,
literal: tcx.mk_const(ty::Const {
ty,
val: ty::ConstKind::Unevaluated(
def,
InternalSubsts::for_item(tcx, def.did, |param, _| {
if let ty::GenericParamDefKind::Lifetime = param.kind {
tcx.lifetimes.re_erased.into()
} else {
tcx.mk_param_from_def(param)
}
}),
Some(promoted_id),
),
}),
}))
};
let (blocks, local_decls) = self.source.basic_blocks_and_local_decls_mut();
match candidate {
Candidate::Ref(loc) => {
let statement = &mut blocks[loc.block].statements[loc.statement_index];
match statement.kind {
StatementKind::Assign(box (
_,
Rvalue::Ref(ref mut region, borrow_kind, ref mut place),
)) => {
// Use the underlying local for this (necessarily interior) borrow.
let ty = local_decls.local_decls()[place.local].ty;
let span = statement.source_info.span;
let ref_ty = tcx.mk_ref(
tcx.lifetimes.re_erased,
ty::TypeAndMut { ty, mutbl: borrow_kind.to_mutbl_lossy() },
);
*region = tcx.lifetimes.re_erased;
let mut projection = vec![PlaceElem::Deref];
projection.extend(place.projection);
place.projection = tcx.intern_place_elems(&projection);
// Create a temp to hold the promoted reference.
// This is because `*r` requires `r` to be a local,
// otherwise we would use the `promoted` directly.
let mut promoted_ref = LocalDecl::new(ref_ty, span);
promoted_ref.source_info = statement.source_info;
let promoted_ref = local_decls.push(promoted_ref);
assert_eq!(self.temps.push(TempState::Unpromotable), promoted_ref);
let promoted_ref_statement = Statement {
source_info: statement.source_info,
kind: StatementKind::Assign(Box::new((
Place::from(promoted_ref),
Rvalue::Use(promoted_operand(ref_ty, span)),
))),
};
self.extra_statements.push((loc, promoted_ref_statement));
Rvalue::Ref(
tcx.lifetimes.re_erased,
borrow_kind,
Place {
local: mem::replace(&mut place.local, promoted_ref),
projection: List::empty(),
},
)
}
_ => bug!(),
}
}
Candidate::Repeat(loc) => {
let statement = &mut blocks[loc.block].statements[loc.statement_index];
match statement.kind {
StatementKind::Assign(box (_, Rvalue::Repeat(ref mut operand, _))) => {
let ty = operand.ty(local_decls, self.tcx);
let span = statement.source_info.span;
Rvalue::Use(mem::replace(operand, promoted_operand(ty, span)))
}
_ => bug!(),
}
}
Candidate::Argument { bb, index } => {
let terminator = blocks[bb].terminator_mut();
match terminator.kind {
TerminatorKind::Call { ref mut args, .. } => {
let ty = args[index].ty(local_decls, self.tcx);
let span = terminator.source_info.span;
Rvalue::Use(mem::replace(&mut args[index], promoted_operand(ty, span)))
}
// We expected a `TerminatorKind::Call` for which we'd like to promote an
// argument. `qualify_consts` saw a `TerminatorKind::Call` here, but
// we are seeing a `Goto`. That means that the `promote_temps` method
// already promoted this call away entirely. This case occurs when calling
// a function requiring a constant argument and as that constant value
// providing a value whose computation contains another call to a function
// requiring a constant argument.
TerminatorKind::Goto { .. } => return None,
_ => bug!(),
}
}
Candidate::InlineAsm { bb, index } => {
let terminator = blocks[bb].terminator_mut();
match terminator.kind {
TerminatorKind::InlineAsm { ref mut operands, .. } => {
match &mut operands[index] {
InlineAsmOperand::Const { ref mut value } => {
let ty = value.ty(local_decls, self.tcx);
let span = terminator.source_info.span;
Rvalue::Use(mem::replace(value, promoted_operand(ty, span)))
}
_ => bug!(),
}
}
_ => bug!(),
}
}
}
};
assert_eq!(self.new_block(), START_BLOCK);
self.visit_rvalue(
&mut rvalue,
Location { block: BasicBlock::new(0), statement_index: usize::MAX },
);
let span = self.promoted.span;
self.assign(RETURN_PLACE, rvalue, span);
Some(self.promoted)
}
}
/// Replaces all temporaries with their promoted counterparts.
impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
fn tcx(&self) -> TyCtxt<'tcx> {
self.tcx
}
fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
if self.is_temp_kind(*local) {
*local = self.promote_temp(*local);
}
}
}
pub fn promote_candidates<'tcx>(
body: &mut Body<'tcx>,
tcx: TyCtxt<'tcx>,
mut temps: IndexVec<Local, TempState>,
candidates: Vec<Candidate>,
) -> IndexVec<Promoted, Body<'tcx>> {
// Visit candidates in reverse, in case they're nested.
debug!("promote_candidates({:?})", candidates);
let mut promotions = IndexVec::new();
let mut extra_statements = vec![];
for candidate in candidates.into_iter().rev() {
match candidate {
Candidate::Repeat(Location { block, statement_index })
| Candidate::Ref(Location { block, statement_index }) => {
if let StatementKind::Assign(box (place, _)) =
&body[block].statements[statement_index].kind
{
if let Some(local) = place.as_local() {
if temps[local] == TempState::PromotedOut {
// Already promoted.
continue;
}
}
}
}
Candidate::Argument { .. } | Candidate::InlineAsm { .. } => {}
}
// Declare return place local so that `mir::Body::new` doesn't complain.
let initial_locals = iter::once(LocalDecl::new(tcx.types.never, body.span)).collect();
let mut promoted = Body::new(
body.source, // `promoted` gets filled in below
IndexVec::new(),
// FIXME: maybe try to filter this to avoid blowing up
// memory usage?
body.source_scopes.clone(),
initial_locals,
IndexVec::new(),
0,
vec![],
body.span,
body.generator_kind,
);
promoted.ignore_interior_mut_in_const_validation = true;
let promoter = Promoter {
promoted,
tcx,
source: body,
temps: &mut temps,
extra_statements: &mut extra_statements,
keep_original: false,
};
//FIXME(oli-obk): having a `maybe_push()` method on `IndexVec` might be nice
if let Some(mut promoted) = promoter.promote_candidate(candidate, promotions.len()) {
promoted.source.promoted = Some(promotions.next_index());
promotions.push(promoted);
}
}
// Insert each of `extra_statements` before its indicated location, which
// has to be done in reverse location order, to not invalidate the rest.
extra_statements.sort_by_key(|&(loc, _)| cmp::Reverse(loc));
for (loc, statement) in extra_statements {
body[loc.block].statements.insert(loc.statement_index, statement);
}
// Eliminate assignments to, and drops of promoted temps.
let promoted = |index: Local| temps[index] == TempState::PromotedOut;
for block in body.basic_blocks_mut() {
block.statements.retain(|statement| match &statement.kind {
StatementKind::Assign(box (place, _)) => {
if let Some(index) = place.as_local() {
!promoted(index)
} else {
true
}
}
StatementKind::StorageLive(index) | StatementKind::StorageDead(index) => {
!promoted(*index)
}
_ => true,
});
let terminator = block.terminator_mut();
if let TerminatorKind::Drop { place, target, .. } = &terminator.kind {
if let Some(index) = place.as_local() {
if promoted(index) {
terminator.kind = TerminatorKind::Goto { target: *target };
}
}
}
}
promotions
}
/// This function returns `true` if the `const_in_array_repeat_expressions` feature attribute should
/// be suggested. This function is probably quite expensive, it shouldn't be run in the happy path.
/// Feature attribute should be suggested if `operand` can be promoted and the feature is not
/// enabled.
crate fn should_suggest_const_in_array_repeat_expressions_attribute<'tcx>(
ccx: &ConstCx<'_, 'tcx>,
operand: &Operand<'tcx>,
) -> bool {
let mut rpo = traversal::reverse_postorder(&ccx.body);
let (temps, _) = collect_temps_and_candidates(&ccx, &mut rpo);
let validator = Validator { ccx, temps: &temps, explicit: false };
let should_promote = validator.validate_operand(operand).is_ok();
let feature_flag = validator.ccx.tcx.features().const_in_array_repeat_expressions;
debug!(
"should_suggest_const_in_array_repeat_expressions_flag: def_id={:?} \
should_promote={:?} feature_flag={:?}",
validator.ccx.def_id(),
should_promote,
feature_flag
);
should_promote && !feature_flag
}
| 41.897293 | 109 | 0.488152 |
76e56fe49ed0c0d1a29748b7f8cbbac8e364d38d | 3,081 | use std::collections::HashMap;
const ALPHABETS: [(&'static str, &'static str); 26] = [
("numeric", "1234567890"),
("abcd", "abcd"),
("qwerty", "asdfqwerzxcvjklmiuopghtybn"),
("qwerty-homerow", "asdfjklgh"),
("qwerty-left-hand", "asdfqwerzcxv"),
("qwerty-right-hand", "jkluiopmyhn"),
("azerty", "qsdfazerwxcvjklmuiopghtybn"),
("azerty-homerow", "qsdfjkmgh"),
("azerty-left-hand", "qsdfazerwxcv"),
("azerty-right-hand", "jklmuiophyn"),
("qwertz", "asdfqweryxcvjkluiopmghtzbn"),
("qwertz-homerow", "asdfghjkl"),
("qwertz-left-hand", "asdfqweryxcv"),
("qwertz-right-hand", "jkluiopmhzn"),
("dvorak", "aoeuqjkxpyhtnsgcrlmwvzfidb"),
("dvorak-homerow", "aoeuhtnsid"),
("dvorak-left-hand", "aoeupqjkyix"),
("dvorak-right-hand", "htnsgcrlmwvz"),
("colemak", "arstqwfpzxcvneioluymdhgjbk"),
("colemak-homerow", "arstneiodh"),
("colemak-left-hand", "arstqwfpzxcv"),
("colemak-right-hand", "neioluymjhk"),
("workman", "thsawrdqcmxzneoilfupgybvjk"),
("workman-homerow", "thsaneo"),
("workman-left-hand", "thsawrdqcmxz"),
("workman-right-hand", "neoifuplk"),
];
pub struct Alphabet<'a> {
letters: &'a str,
}
impl<'a> Alphabet<'a> {
fn new(letters: &'a str) -> Alphabet {
Alphabet { letters }
}
pub fn hints(&self, matches: usize) -> Vec<String> {
let letters: Vec<String> = self.letters.chars().map(|s| s.to_string()).collect();
let mut expansion = letters.clone();
let mut expanded: Vec<String> = Vec::new();
loop {
if expansion.len() + expanded.len() >= matches {
break;
}
if expansion.is_empty() {
break;
}
let prefix = expansion.pop().expect("Ouch!");
let sub_expansion: Vec<String> = letters
.iter()
.take(matches - expansion.len() - expanded.len())
.map(|s| prefix.clone() + s)
.collect();
expanded.splice(0..0, sub_expansion);
}
expansion = expansion.iter().take(matches - expanded.len()).cloned().collect();
expansion.append(&mut expanded);
expansion
}
}
pub fn get_alphabet(alphabet_name: &str) -> Alphabet {
let alphabets: HashMap<&str, &str> = ALPHABETS.iter().cloned().collect();
alphabets
.get(alphabet_name)
.expect(format!("Unknown alphabet: {}", alphabet_name).as_str()); // FIXME
Alphabet::new(alphabets[alphabet_name])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn simple_matches() {
let alphabet = Alphabet::new("abcd");
let hints = alphabet.hints(3);
assert_eq!(hints, ["a", "b", "c"]);
}
#[test]
fn composed_matches() {
let alphabet = Alphabet::new("abcd");
let hints = alphabet.hints(6);
assert_eq!(hints, ["a", "b", "c", "da", "db", "dc"]);
}
#[test]
fn composed_matches_multiple() {
let alphabet = Alphabet::new("abcd");
let hints = alphabet.hints(8);
assert_eq!(hints, ["a", "b", "ca", "cb", "da", "db", "dc", "dd"]);
}
#[test]
fn composed_matches_max() {
let alphabet = Alphabet::new("ab");
let hints = alphabet.hints(8);
assert_eq!(hints, ["aa", "ab", "ba", "bb"]);
}
}
| 27.265487 | 85 | 0.605972 |
8f9f4223f650fd2e5169d53e846c1e26e5534d9f | 5,506 | #[doc = "Register `WPMR` reader"]
pub struct R(crate::R<WPMR_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<WPMR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<WPMR_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<WPMR_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `WPMR` writer"]
pub struct W(crate::W<WPMR_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<WPMR_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<WPMR_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<WPMR_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `WPEN` reader - Write Protection Enable"]
pub struct WPEN_R(crate::FieldReader<bool, bool>);
impl WPEN_R {
pub(crate) fn new(bits: bool) -> Self {
WPEN_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for WPEN_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `WPEN` writer - Write Protection Enable"]
pub struct WPEN_W<'a> {
w: &'a mut W,
}
impl<'a> WPEN_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | (value as u32 & 0x01);
self.w
}
}
#[doc = "Write Protection Key\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u32)]
pub enum WPKEY_A {
#[doc = "5591873: Writing any other value in this field aborts the write operation of the WPEN bit. Always reads as 0."]
PASSWD = 5591873,
}
impl From<WPKEY_A> for u32 {
#[inline(always)]
fn from(variant: WPKEY_A) -> Self {
variant as _
}
}
#[doc = "Field `WPKEY` reader - Write Protection Key"]
pub struct WPKEY_R(crate::FieldReader<u32, WPKEY_A>);
impl WPKEY_R {
pub(crate) fn new(bits: u32) -> Self {
WPKEY_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<WPKEY_A> {
match self.bits {
5591873 => Some(WPKEY_A::PASSWD),
_ => None,
}
}
#[doc = "Checks if the value of the field is `PASSWD`"]
#[inline(always)]
pub fn is_passwd(&self) -> bool {
**self == WPKEY_A::PASSWD
}
}
impl core::ops::Deref for WPKEY_R {
type Target = crate::FieldReader<u32, WPKEY_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `WPKEY` writer - Write Protection Key"]
pub struct WPKEY_W<'a> {
w: &'a mut W,
}
impl<'a> WPKEY_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: WPKEY_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "Writing any other value in this field aborts the write operation of the WPEN bit. Always reads as 0."]
#[inline(always)]
pub fn passwd(self) -> &'a mut W {
self.variant(WPKEY_A::PASSWD)
}
#[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 & !(0x00ff_ffff << 8)) | ((value as u32 & 0x00ff_ffff) << 8);
self.w
}
}
impl R {
#[doc = "Bit 0 - Write Protection Enable"]
#[inline(always)]
pub fn wpen(&self) -> WPEN_R {
WPEN_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bits 8:31 - Write Protection Key"]
#[inline(always)]
pub fn wpkey(&self) -> WPKEY_R {
WPKEY_R::new(((self.bits >> 8) & 0x00ff_ffff) as u32)
}
}
impl W {
#[doc = "Bit 0 - Write Protection Enable"]
#[inline(always)]
pub fn wpen(&mut self) -> WPEN_W {
WPEN_W { w: self }
}
#[doc = "Bits 8:31 - Write Protection Key"]
#[inline(always)]
pub fn wpkey(&mut self) -> WPKEY_W {
WPKEY_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 = "Write Protection Mode 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 [wpmr](index.html) module"]
pub struct WPMR_SPEC;
impl crate::RegisterSpec for WPMR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [wpmr::R](R) reader structure"]
impl crate::Readable for WPMR_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [wpmr::W](W) writer structure"]
impl crate::Writable for WPMR_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets WPMR to value 0"]
impl crate::Resettable for WPMR_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| 29.762162 | 415 | 0.58409 |
693aabb78b4d8fe39076e157bb47f71b46a59868 | 2,888 | use std::{
convert::From,
error, fmt,
io::{self, prelude::*},
num::ParseIntError,
};
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ErrorKind {
ConnectionLost,
InvalidBytesRead,
IOError,
}
#[derive(Debug)]
enum Repr {
Simple(ErrorKind),
Extended(ExtendedError),
}
#[derive(Debug)]
struct ExtendedError {
kind: ErrorKind,
error: Box<dyn error::Error + Send + Sync>,
}
impl fmt::Display for ErrorKind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let reason = match self {
Self::ConnectionLost => "connection with the server is lost",
Self::InvalidBytesRead => "stream returned invalid string for message bytes length",
Self::IOError => "IO Error",
};
write!(f, "{}", reason)
}
}
#[derive(Debug)]
pub struct Error {
repr: Repr,
}
impl Error {
pub fn kind(&self) -> ErrorKind {
match self.repr {
Repr::Simple(kind) => kind,
Repr::Extended(ref extended) => extended.kind,
}
}
}
impl error::Error for Error {}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &self.repr {
Repr::Simple(kind) => write!(f, "Reading from stream failed: {}", kind),
Repr::Extended(extended) => write!(
f,
"Reading from stream failed: {}, previous error: {}",
extended.kind, extended.error
),
}
}
}
impl From<ErrorKind> for Error {
fn from(kind: ErrorKind) -> Error {
Error {
repr: Repr::Simple(kind),
}
}
}
impl From<ParseIntError> for Error {
fn from(error: ParseIntError) -> Error {
Error {
repr: Repr::Extended(ExtendedError {
kind: ErrorKind::InvalidBytesRead,
error: Box::new(error),
}),
}
}
}
impl From<io::Error> for Error {
fn from(error: io::Error) -> Error {
Error {
repr: Repr::Extended(ExtendedError {
kind: ErrorKind::IOError,
error: Box::new(error),
}),
}
}
}
pub type ReadResult = Result<String, Error>;
pub fn read(reader: &mut impl io::BufRead) -> ReadResult {
let mut message = String::new();
debug!("Waiting for incoming message");
match reader.read_line(&mut message) {
Ok(0) => return Err(Error::from(ErrorKind::ConnectionLost)),
Ok(_) => (),
Err(e) => return Err(Error::from(e)),
}
debug!("Received {:?} from server", message);
let size = message.trim_end().to_string().parse::<u64>()?;
debug!("Message is {} bytes long", size);
let mut buffer = Vec::new();
reader.take(size).read_to_end(&mut buffer)?;
let message = String::from_utf8_lossy(&buffer).to_string();
Ok(message)
}
| 23.867769 | 96 | 0.553324 |
ed99f80478781f3a006d3793016ded32d5c32be4 | 17,042 | //! Parsing implementation for Tor authority certificates
//!
//! An "authority certificate" is a short signed document that binds a
//! directory authority's permanent "identity key" to its medium-term
//! "signing key". Using separate keys here enables the authorities
//! to keep their identity keys securely offline, while using the
//! signing keys to sign votes and consensuses.
use crate::parse::keyword::Keyword;
use crate::parse::parser::SectionRules;
use crate::parse::tokenize::{ItemResult, NetDocReader};
use crate::types::misc::{Fingerprint, Iso8601TimeSp, RsaPublic};
use crate::util::str::Extent;
use crate::{Error, Result};
use tor_checkable::{signed, timed};
use tor_llcrypto::pk::rsa;
use tor_llcrypto::{d, pk, pk::rsa::RsaIdentity};
use once_cell::sync::Lazy;
use std::{net, time};
use digest::Digest;
#[cfg(feature = "build_docs")]
mod build;
#[cfg(feature = "build_docs")]
pub use build::AuthCertBuilder;
decl_keyword! {
AuthCertKwd {
"dir-key-certificate-version" => DIR_KEY_CERTIFICATE_VERSION,
"dir-address" => DIR_ADDRESS,
"fingerprint" => FINGERPRINT,
"dir-identity-key" => DIR_IDENTITY_KEY,
"dir-key-published" => DIR_KEY_PUBLISHED,
"dir-key-expires" => DIR_KEY_EXPIRES,
"dir-signing-key" => DIR_SIGNING_KEY,
"dir-key-crosscert" => DIR_KEY_CROSSCERT,
"dir-key-certification" => DIR_KEY_CERTIFICATION,
}
}
/// Rules about entries that must appear in an AuthCert, and how they must
/// be formed.
static AUTHCERT_RULES: Lazy<SectionRules<AuthCertKwd>> = Lazy::new(|| {
use AuthCertKwd::*;
let mut rules = SectionRules::new();
rules.add(DIR_KEY_CERTIFICATE_VERSION.rule().required().args(1..));
rules.add(DIR_ADDRESS.rule().args(1..));
rules.add(FINGERPRINT.rule().required().args(1..));
rules.add(DIR_IDENTITY_KEY.rule().required().no_args().obj_required());
rules.add(DIR_SIGNING_KEY.rule().required().no_args().obj_required());
rules.add(DIR_KEY_PUBLISHED.rule().required());
rules.add(DIR_KEY_EXPIRES.rule().required());
rules.add(DIR_KEY_CROSSCERT.rule().required().no_args().obj_required());
rules.add(
DIR_KEY_CERTIFICATION
.rule()
.required()
.no_args()
.obj_required(),
);
rules
});
/// A single authority certificate.
///
/// Authority certificates bind a long-term RSA identity key from a
/// directory authority to a medium-term signing key. The signing
/// keys are the ones used to sign votes and consensuses; the identity
/// keys can be kept offline.
#[allow(dead_code)]
#[derive(Clone, Debug)]
pub struct AuthCert {
/// An IPv4 address for this authority.
address: Option<net::SocketAddrV4>,
/// The long-term RSA identity key for this authority
identity_key: rsa::PublicKey,
/// The medium-term RSA signing key for this authority
signing_key: rsa::PublicKey,
/// Declared time when this certificate was published
published: time::SystemTime,
/// Declared time when this certificate expires.
expires: time::SystemTime,
/// Derived field: fingerprints of the certificate's keys
key_ids: AuthCertKeyIds,
}
/// A pair of key identities that identifies a certificate.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
#[allow(clippy::exhaustive_structs)]
pub struct AuthCertKeyIds {
/// Fingerprint of identity key
pub id_fingerprint: rsa::RsaIdentity,
/// Fingerprint of signing key
pub sk_fingerprint: rsa::RsaIdentity,
}
/// An authority certificate whose signature and validity time we
/// haven't checked.
pub struct UncheckedAuthCert {
/// Where we found this AuthCert within the string containing it.
location: Option<Extent>,
/// The actual unchecked certificate.
c: signed::SignatureGated<timed::TimerangeBound<AuthCert>>,
}
impl UncheckedAuthCert {
/// If this AuthCert was originally parsed from `haystack`, return its
/// text.
///
/// TODO: This is a pretty bogus interface; there should be a
/// better way to remember where to look for this thing if we want
/// it without keeping the input alive forever. We should
/// refactor.
pub fn within<'a>(&self, haystack: &'a str) -> Option<&'a str> {
self.location
.as_ref()
.and_then(|ext| ext.reconstruct(haystack))
}
}
impl AuthCert {
/// Make an [`AuthCertBuilder`] object that can be used to
/// construct authority certificates for testing.
#[cfg(feature = "build_docs")]
pub fn builder() -> AuthCertBuilder {
AuthCertBuilder::new()
}
/// Parse an authority certificate from a string.
///
/// This function verifies the certificate's signatures, but doesn't
/// check its expiration dates.
pub fn parse(s: &str) -> Result<UncheckedAuthCert> {
let mut reader = NetDocReader::new(s);
let result = AuthCert::take_from_reader(&mut reader).map_err(|e| e.within(s));
reader.should_be_exhausted()?;
result
}
/// Return an iterator yielding authority certificates from a string.
pub fn parse_multiple(s: &str) -> impl Iterator<Item = Result<UncheckedAuthCert>> + '_ {
AuthCertIterator(NetDocReader::new(s))
}
/*
/// Return true if this certificate is expired at a given time, or
/// not yet valid at that time.
pub fn is_expired_at(&self, when: time::SystemTime) -> bool {
when < self.published || when > self.expires
}
*/
/// Return the signing key certified by this certificate.
pub fn signing_key(&self) -> &rsa::PublicKey {
&self.signing_key
}
/// Return an AuthCertKeyIds object describing the keys in this
/// certificate.
pub fn key_ids(&self) -> &AuthCertKeyIds {
&self.key_ids
}
/// Return an RsaIdentity for this certificate's identity key.
pub fn id_fingerprint(&self) -> &rsa::RsaIdentity {
&self.key_ids.id_fingerprint
}
/// Return an RsaIdentity for this certificate's signing key.
pub fn sk_fingerprint(&self) -> &rsa::RsaIdentity {
&self.key_ids.sk_fingerprint
}
/// Return the time when this certificate says it was published.
pub fn published(&self) -> time::SystemTime {
self.published
}
/// Return the time when this certificate says it should expire.
pub fn expires(&self) -> time::SystemTime {
self.expires
}
/// Parse an authority certificate from a reader.
fn take_from_reader(reader: &mut NetDocReader<'_, AuthCertKwd>) -> Result<UncheckedAuthCert> {
use AuthCertKwd::*;
let mut start_found = false;
let mut iter = reader.pause_at(|item| {
let is_start = item.is_ok_with_kwd(DIR_KEY_CERTIFICATE_VERSION);
let pause = is_start && start_found;
if is_start {
start_found = true;
}
pause
});
let body = AUTHCERT_RULES.parse(&mut iter)?;
// Make sure first and last element are correct types. We can
// safely call unwrap() on first and last, since there are required
// tokens in the rules, so we know that at least one token will have
// been parsed.
let start_pos = {
// Unwrap should be safe because `.parse()` would have already
// returned an Error
#[allow(clippy::unwrap_used)]
let first_item = body.first_item().unwrap();
if first_item.kwd() != DIR_KEY_CERTIFICATE_VERSION {
return Err(Error::WrongStartingToken(
first_item.kwd_str().into(),
first_item.pos(),
));
}
first_item.pos()
};
let end_pos = {
// Unwrap should be safe because `.parse()` would have already
// returned an Error
#[allow(clippy::unwrap_used)]
let last_item = body.last_item().unwrap();
if last_item.kwd() != DIR_KEY_CERTIFICATION {
return Err(Error::WrongEndingToken(
last_item.kwd_str().into(),
last_item.pos(),
));
}
last_item.end_pos()
};
let version = body
.required(DIR_KEY_CERTIFICATE_VERSION)?
.parse_arg::<u32>(0)?;
if version != 3 {
return Err(Error::BadDocumentVersion(version));
}
let signing_key: rsa::PublicKey = body
.required(DIR_SIGNING_KEY)?
.parse_obj::<RsaPublic>("RSA PUBLIC KEY")?
.check_len(1024..)?
.check_exponent(65537)?
.into();
let identity_key: rsa::PublicKey = body
.required(DIR_IDENTITY_KEY)?
.parse_obj::<RsaPublic>("RSA PUBLIC KEY")?
.check_len(1024..)?
.check_exponent(65537)?
.into();
let published = body
.required(DIR_KEY_PUBLISHED)?
.args_as_str()
.parse::<Iso8601TimeSp>()?
.into();
let expires = body
.required(DIR_KEY_EXPIRES)?
.args_as_str()
.parse::<Iso8601TimeSp>()?
.into();
{
// Check fingerprint for consistency with key.
let fp_tok = body.required(FINGERPRINT)?;
let fingerprint: RsaIdentity = fp_tok.args_as_str().parse::<Fingerprint>()?.into();
if fingerprint != identity_key.to_rsa_identity() {
return Err(Error::BadArgument(
fp_tok.pos(),
"fingerprint does not match RSA identity".into(),
));
}
}
let address = body
.maybe(DIR_ADDRESS)
.parse_args_as_str::<net::SocketAddrV4>()?;
// check crosscert
let v_crosscert = {
let crosscert = body.required(DIR_KEY_CROSSCERT)?;
// Unwrap should be safe because `.parse()` and `required()` would
// have already returned an Error
#[allow(clippy::unwrap_used)]
let mut tag = crosscert.obj_tag().unwrap();
// we are required to support both.
if tag != "ID SIGNATURE" && tag != "SIGNATURE" {
tag = "ID SIGNATURE";
}
let sig = crosscert.obj(tag)?;
let signed = identity_key.to_rsa_identity();
// TODO: we need to accept prefixes here. COMPAT BLOCKER.
rsa::ValidatableRsaSignature::new(&signing_key, &sig, signed.as_bytes())
};
// check the signature
let v_sig = {
let signature = body.required(DIR_KEY_CERTIFICATION)?;
let sig = signature.obj("SIGNATURE")?;
let mut sha1 = d::Sha1::new();
let s = reader.str();
// Unwrap should be safe because `.parse()` would have already
// returned an Error
#[allow(clippy::unwrap_used)]
let start_offset = body.first_item().unwrap().offset_in(s).unwrap();
#[allow(clippy::unwrap_used)]
let end_offset = body.last_item().unwrap().offset_in(s).unwrap();
let end_offset = end_offset + "dir-key-certification\n".len();
sha1.update(&s[start_offset..end_offset]);
let sha1 = sha1.finalize();
// TODO: we need to accept prefixes here. COMPAT BLOCKER.
rsa::ValidatableRsaSignature::new(&identity_key, &sig, &sha1)
};
let id_fingerprint = identity_key.to_rsa_identity();
let sk_fingerprint = signing_key.to_rsa_identity();
let key_ids = AuthCertKeyIds {
id_fingerprint,
sk_fingerprint,
};
let location = {
let s = reader.str();
let start_idx = start_pos.offset_within(s);
let end_idx = end_pos.offset_within(s);
match (start_idx, end_idx) {
(Some(a), Some(b)) => Extent::new(s, &s[a..b + 1]),
_ => None,
}
};
let authcert = AuthCert {
address,
identity_key,
signing_key,
published,
expires,
key_ids,
};
let signatures: Vec<Box<dyn pk::ValidatableSignature>> =
vec![Box::new(v_crosscert), Box::new(v_sig)];
let timed = timed::TimerangeBound::new(authcert, published..expires);
let signed = signed::SignatureGated::new(timed, signatures);
let unchecked = UncheckedAuthCert {
location,
c: signed,
};
Ok(unchecked)
}
/// Skip tokens from the reader until the next token (if any) is
/// the start of cert.
fn advance_reader_to_next(reader: &mut NetDocReader<'_, AuthCertKwd>) {
use AuthCertKwd::*;
let iter = reader.iter();
while let Some(Ok(item)) = iter.peek() {
if item.kwd() == DIR_KEY_CERTIFICATE_VERSION {
return;
}
iter.next();
}
}
}
/// Iterator type to read a series of concatenated certificates from a
/// string.
struct AuthCertIterator<'a>(NetDocReader<'a, AuthCertKwd>);
impl tor_checkable::SelfSigned<timed::TimerangeBound<AuthCert>> for UncheckedAuthCert {
type Error = signature::Error;
fn dangerously_assume_wellsigned(self) -> timed::TimerangeBound<AuthCert> {
self.c.dangerously_assume_wellsigned()
}
fn is_well_signed(&self) -> std::result::Result<(), Self::Error> {
self.c.is_well_signed()
}
}
impl<'a> Iterator for AuthCertIterator<'a> {
type Item = Result<UncheckedAuthCert>;
fn next(&mut self) -> Option<Result<UncheckedAuthCert>> {
if self.0.is_exhausted() {
return None;
}
let pos_orig = self.0.pos();
let result = AuthCert::take_from_reader(&mut self.0);
if result.is_err() {
if self.0.pos() == pos_orig {
// No tokens were consumed from the reader. We need
// to drop at least one token to ensure we aren't in
// an infinite loop.
//
// (This might not be able to happen, but it's easier to
// explicitly catch this case than it is to prove that
// it's impossible.)
let _ = self.0.iter().next();
}
AuthCert::advance_reader_to_next(&mut self.0);
}
Some(result.map_err(|e| e.within(self.0.str())))
}
}
#[cfg(test)]
mod test {
#![allow(clippy::unwrap_used)]
use super::*;
use crate::{Error, Pos};
const TESTDATA: &str = include_str!("../../testdata/authcert1.txt");
fn bad_data(fname: &str) -> String {
use std::fs;
use std::path::PathBuf;
let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
path.push("testdata");
path.push("bad-certs");
path.push(fname);
fs::read_to_string(path).unwrap()
}
#[test]
fn parse_one() -> Result<()> {
use tor_checkable::{SelfSigned, Timebound};
let _rd = AuthCert::parse(TESTDATA)?
.check_signature()
.unwrap()
.dangerously_assume_timely();
Ok(())
}
#[test]
fn parse_bad() {
fn check(fname: &str, err: &Error) {
let contents = bad_data(fname);
let cert = AuthCert::parse(&contents);
assert!(cert.is_err());
assert_eq!(&cert.err().unwrap(), err);
}
check("bad-cc-tag", &Error::WrongObject(Pos::from_line(27, 12)));
check(
"bad-fingerprint",
&Error::BadArgument(
Pos::from_line(2, 1),
"fingerprint does not match RSA identity".into(),
),
);
check("bad-version", &Error::BadDocumentVersion(4));
check(
"wrong-end",
&Error::WrongEndingToken("dir-key-crosscert".into(), Pos::from_line(37, 1)),
);
check(
"wrong-start",
&Error::WrongStartingToken("fingerprint".into(), Pos::from_line(1, 1)),
);
}
#[test]
fn test_recovery_1() {
let mut data = "<><><<><>\nfingerprint ABC\n".to_string();
data += TESTDATA;
let res: Vec<Result<_>> = AuthCert::parse_multiple(&data).collect();
// We should recover from the failed case and read the next data fine.
assert!(res[0].is_err());
assert!(res[1].is_ok());
assert_eq!(res.len(), 2);
}
#[test]
fn test_recovery_2() {
let mut data = bad_data("bad-version");
data += TESTDATA;
let res: Vec<Result<_>> = AuthCert::parse_multiple(&data).collect();
// We should recover from the failed case and read the next data fine.
assert!(res[0].is_err());
assert!(res[1].is_ok());
assert_eq!(res.len(), 2);
}
}
| 34.015968 | 98 | 0.586023 |
d90be4fb1c9f0447a034dba4977c089e6a481189 | 42,861 | // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;
use std::ops::Index;
use std::str::FromStr;
use std::sync::Arc;
use memchr::memchr;
use syntax;
use error::Error;
use exec::{Exec, ExecNoSyncStr};
use expand::expand_str;
use re_builder::unicode::RegexBuilder;
use re_plugin::Plugin;
use re_trait::{self, RegularExpression, Locations, SubCapturesPosIter};
/// Escapes all regular expression meta characters in `text`.
///
/// The string returned may be safely used as a literal in a regular
/// expression.
pub fn escape(text: &str) -> String {
syntax::escape(text)
}
/// Match represents a single match of a regex in a haystack.
///
/// The lifetime parameter `'t` refers to the lifetime of the matched text.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Match<'t> {
text: &'t str,
start: usize,
end: usize,
}
impl<'t> Match<'t> {
/// Returns the starting byte offset of the match in the haystack.
#[inline]
pub fn start(&self) -> usize {
self.start
}
/// Returns the ending byte offset of the match in the haystack.
#[inline]
pub fn end(&self) -> usize {
self.end
}
/// Returns the matched text.
#[inline]
pub fn as_str(&self) -> &'t str {
&self.text[self.start..self.end]
}
/// Creates a new match from the given haystack and byte offsets.
#[inline]
fn new(haystack: &'t str, start: usize, end: usize) -> Match<'t> {
Match {
text: haystack,
start: start,
end: end,
}
}
}
/// A compiled regular expression for matching Unicode strings.
///
/// It is represented as either a sequence of bytecode instructions (dynamic)
/// or as a specialized Rust function (native). It can be used to search, split
/// or replace text. All searching is done with an implicit `.*?` at the
/// beginning and end of an expression. To force an expression to match the
/// whole string (or a prefix or a suffix), you must use an anchor like `^` or
/// `$` (or `\A` and `\z`).
///
/// While this crate will handle Unicode strings (whether in the regular
/// expression or in the search text), all positions returned are **byte
/// indices**. Every byte index is guaranteed to be at a Unicode code point
/// boundary.
///
/// The lifetimes `'r` and `'t` in this crate correspond to the lifetime of a
/// compiled regular expression and text to search, respectively.
///
/// The only methods that allocate new strings are the string replacement
/// methods. All other methods (searching and splitting) return borrowed
/// pointers into the string given.
///
/// # Examples
///
/// Find the location of a US phone number:
///
/// ```rust
/// # use regex::Regex;
/// let re = Regex::new("[0-9]{3}-[0-9]{3}-[0-9]{4}").unwrap();
/// let mat = re.find("phone: 111-222-3333").unwrap();
/// assert_eq!((mat.start(), mat.end()), (7, 19));
/// ```
///
/// # Using the `std::str::pattern` methods with `Regex`
///
/// > **Note**: This section requires that this crate is compiled with the
/// > `pattern` Cargo feature enabled, which **requires nightly Rust**.
///
/// Since `Regex` implements `Pattern`, you can use regexes with methods
/// defined on `&str`. For example, `is_match`, `find`, `find_iter`
/// and `split` can be replaced with `str::contains`, `str::find`,
/// `str::match_indices` and `str::split`.
///
/// Here are some examples:
///
/// ```rust,ignore
/// # use regex::Regex;
/// let re = Regex::new(r"\d+").unwrap();
/// let haystack = "a111b222c";
///
/// assert!(haystack.contains(&re));
/// assert_eq!(haystack.find(&re), Some(1));
/// assert_eq!(haystack.match_indices(&re).collect::<Vec<_>>(),
/// vec![(1, 4), (5, 8)]);
/// assert_eq!(haystack.split(&re).collect::<Vec<_>>(), vec!["a", "b", "c"]);
/// ```
#[derive(Clone)]
pub struct Regex(#[doc(hidden)] pub _Regex);
#[derive(Clone)]
#[doc(hidden)]
pub enum _Regex {
// The representation of `Regex` is exported to support the `regex!`
// syntax extension. Do not rely on it.
//
// See the comments for the `internal` module in `lib.rs` for a more
// detailed explanation for what `regex!` requires.
#[doc(hidden)]
Dynamic(Exec),
#[doc(hidden)]
Plugin(Plugin),
}
impl fmt::Display for Regex {
/// Shows the original regular expression.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
impl fmt::Debug for Regex {
/// Shows the original regular expression.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
#[doc(hidden)]
impl From<Exec> for Regex {
fn from(exec: Exec) -> Regex {
Regex(_Regex::Dynamic(exec))
}
}
impl FromStr for Regex {
type Err = Error;
/// Attempts to parse a string into a regular expression
fn from_str(s: &str) -> Result<Regex, Error> {
Regex::new(s)
}
}
/// Core regular expression methods.
impl Regex {
/// Compiles a regular expression. Once compiled, it can be used repeatedly
/// to search, split or replace text in a string.
///
/// If an invalid expression is given, then an error is returned.
pub fn new(re: &str) -> Result<Regex, Error> {
RegexBuilder::new(re).build()
}
/// Returns true if and only if the regex matches the string given.
///
/// It is recommended to use this method if all you need to do is test
/// a match, since the underlying matching engine may be able to do less
/// work.
///
/// # Example
///
/// Test if some text contains at least one word with exactly 13
/// Unicode word characters:
///
/// ```rust
/// # extern crate regex; use regex::Regex;
/// # fn main() {
/// let text = "I categorically deny having triskaidekaphobia.";
/// assert!(Regex::new(r"\b\w{13}\b").unwrap().is_match(text));
/// # }
/// ```
pub fn is_match(&self, text: &str) -> bool {
self.is_match_at(text, 0)
}
/// Returns the start and end byte range of the leftmost-first match in
/// `text`. If no match exists, then `None` is returned.
///
/// Note that this should only be used if you want to discover the position
/// of the match. Testing the existence of a match is faster if you use
/// `is_match`.
///
/// # Example
///
/// Find the start and end location of the first word with exactly 13
/// Unicode word characters:
///
/// ```rust
/// # extern crate regex; use regex::Regex;
/// # fn main() {
/// let text = "I categorically deny having triskaidekaphobia.";
/// let mat = Regex::new(r"\b\w{13}\b").unwrap().find(text).unwrap();
/// assert_eq!(mat.start(), 2);
/// assert_eq!(mat.end(), 15);
/// # }
/// ```
pub fn find<'t>(&self, text: &'t str) -> Option<Match<'t>> {
self.find_at(text, 0)
}
/// Returns an iterator for each successive non-overlapping match in
/// `text`, returning the start and end byte indices with respect to
/// `text`.
///
/// # Example
///
/// Find the start and end location of every word with exactly 13 Unicode
/// word characters:
///
/// ```rust
/// # extern crate regex; use regex::Regex;
/// # fn main() {
/// let text = "Retroactively relinquishing remunerations is reprehensible.";
/// for mat in Regex::new(r"\b\w{13}\b").unwrap().find_iter(text) {
/// println!("{:?}", mat);
/// }
/// # }
/// ```
pub fn find_iter<'r, 't>(&'r self, text: &'t str) -> Matches<'r, 't> {
match self.0 {
_Regex::Dynamic(ref exec) => {
let it = exec.searcher_str().find_iter(text);
Matches(MatchesInner::Dynamic(it))
}
_Regex::Plugin(ref plug) => {
let it = plug.find_iter(text);
Matches(MatchesInner::Plugin(it))
}
}
}
/// Returns the capture groups corresponding to the leftmost-first
/// match in `text`. Capture group `0` always corresponds to the entire
/// match. If no match is found, then `None` is returned.
///
/// You should only use `captures` if you need access to the location of
/// capturing group matches. Otherwise, `find` is faster for discovering
/// the location of the overall match.
///
/// # Examples
///
/// Say you have some text with movie names and their release years,
/// like "'Citizen Kane' (1941)". It'd be nice if we could search for text
/// looking like that, while also extracting the movie name and its release
/// year separately.
///
/// ```rust
/// # extern crate regex; use regex::Regex;
/// # fn main() {
/// let re = Regex::new(r"'([^']+)'\s+\((\d{4})\)").unwrap();
/// let text = "Not my favorite movie: 'Citizen Kane' (1941).";
/// let caps = re.captures(text).unwrap();
/// assert_eq!(caps.get(1).unwrap().as_str(), "Citizen Kane");
/// assert_eq!(caps.get(2).unwrap().as_str(), "1941");
/// assert_eq!(caps.get(0).unwrap().as_str(), "'Citizen Kane' (1941)");
/// // You can also access the groups by index using the Index notation.
/// // Note that this will panic on an invalid index.
/// assert_eq!(&caps[1], "Citizen Kane");
/// assert_eq!(&caps[2], "1941");
/// assert_eq!(&caps[0], "'Citizen Kane' (1941)");
/// # }
/// ```
///
/// Note that the full match is at capture group `0`. Each subsequent
/// capture group is indexed by the order of its opening `(`.
///
/// We can make this example a bit clearer by using *named* capture groups:
///
/// ```rust
/// # extern crate regex; use regex::Regex;
/// # fn main() {
/// let re = Regex::new(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)")
/// .unwrap();
/// let text = "Not my favorite movie: 'Citizen Kane' (1941).";
/// let caps = re.captures(text).unwrap();
/// assert_eq!(&caps["title"], "Citizen Kane");
/// assert_eq!(&caps["year"], "1941");
/// assert_eq!(caps.get(0).unwrap().as_str(), "'Citizen Kane' (1941)");
/// // You can also access the groups by name using the Index notation.
/// // Note that this will panic on an invalid group name.
/// assert_eq!(&caps["title"], "Citizen Kane");
/// assert_eq!(&caps["year"], "1941");
/// assert_eq!(&caps[0], "'Citizen Kane' (1941)");
///
/// # }
/// ```
///
/// Here we name the capture groups, which we can access with the `name`
/// method or the `Index` notation with a `&str`. Note that the named
/// capture groups are still accessible with `get` or the `Index` notation
/// with a `usize`.
///
/// The `0`th capture group is always unnamed, so it must always be
/// accessed with `at(0)` or `[0]`.
pub fn captures<'t>(&self, text: &'t str) -> Option<Captures<'t>> {
let mut locs = self.locations();
self.read_captures_at(&mut locs, text, 0).map(|_| Captures {
text: text,
locs: locs,
named_groups: NamedGroups::from_regex(self)
})
}
/// Returns an iterator over all the non-overlapping capture groups matched
/// in `text`. This is operationally the same as `find_iter`, except it
/// yields information about capturing group matches.
///
/// # Example
///
/// We can use this to find all movie titles and their release years in
/// some text, where the movie is formatted like "'Title' (xxxx)":
///
/// ```rust
/// # extern crate regex; use regex::Regex;
/// # fn main() {
/// let re = Regex::new(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)")
/// .unwrap();
/// let text = "'Citizen Kane' (1941), 'The Wizard of Oz' (1939), 'M' (1931).";
/// for caps in re.captures_iter(text) {
/// println!("Movie: {:?}, Released: {:?}",
/// &caps["title"], &caps["year"]);
/// }
/// // Output:
/// // Movie: Citizen Kane, Released: 1941
/// // Movie: The Wizard of Oz, Released: 1939
/// // Movie: M, Released: 1931
/// # }
/// ```
pub fn captures_iter<'r, 't>(
&'r self,
text: &'t str,
) -> CaptureMatches<'r, 't> {
match self.0 {
_Regex::Dynamic(ref exec) => {
let it = exec.searcher_str().captures_iter(text);
CaptureMatches(CaptureMatchesInner::Dynamic(it))
}
_Regex::Plugin(ref plug) => {
let it = plug.captures_iter(text);
CaptureMatches(CaptureMatchesInner::Plugin(it))
}
}
}
/// Returns an iterator of substrings of `text` delimited by a match of the
/// regular expression. Namely, each element of the iterator corresponds to
/// text that *isn't* matched by the regular expression.
///
/// This method will *not* copy the text given.
///
/// # Example
///
/// To split a string delimited by arbitrary amounts of spaces or tabs:
///
/// ```rust
/// # extern crate regex; use regex::Regex;
/// # fn main() {
/// let re = Regex::new(r"[ \t]+").unwrap();
/// let fields: Vec<&str> = re.split("a b \t c\td e").collect();
/// assert_eq!(fields, vec!["a", "b", "c", "d", "e"]);
/// # }
/// ```
pub fn split<'r, 't>(&'r self, text: &'t str) -> Split<'r, 't> {
Split {
finder: self.find_iter(text),
last: 0,
}
}
/// Returns an iterator of at most `limit` substrings of `text` delimited
/// by a match of the regular expression. (A `limit` of `0` will return no
/// substrings.) Namely, each element of the iterator corresponds to text
/// that *isn't* matched by the regular expression. The remainder of the
/// string that is not split will be the last element in the iterator.
///
/// This method will *not* copy the text given.
///
/// # Example
///
/// Get the first two words in some text:
///
/// ```rust
/// # extern crate regex; use regex::Regex;
/// # fn main() {
/// let re = Regex::new(r"\W+").unwrap();
/// let fields: Vec<&str> = re.splitn("Hey! How are you?", 3).collect();
/// assert_eq!(fields, vec!("Hey", "How", "are you?"));
/// # }
/// ```
pub fn splitn<'r, 't>(&'r self, text: &'t str, limit: usize)
-> SplitN<'r, 't> {
SplitN {
splits: self.split(text),
n: limit,
}
}
/// Replaces the leftmost-first match with the replacement provided.
/// The replacement can be a regular string (where `$N` and `$name` are
/// expanded to match capture groups) or a function that takes the matches'
/// `Captures` and returns the replaced string.
///
/// If no match is found, then a copy of the string is returned unchanged.
///
/// # Replacement string syntax
///
/// All instances of `$name` in the replacement text is replaced with the
/// corresponding capture group `name`.
///
/// `name` may be an integer corresponding to the index of the
/// capture group (counted by order of opening parenthesis where `0` is the
/// entire match) or it can be a name (consisting of letters, digits or
/// underscores) corresponding to a named capture group.
///
/// If `name` isn't a valid capture group (whether the name doesn't exist
/// or isn't a valid index), then it is replaced with the empty string.
///
/// The longest possible name is used. e.g., `$1a` looks up the capture
/// group named `1a` and not the capture group at index `1`. To exert more
/// precise control over the name, use braces, e.g., `${1}a`.
///
/// To write a literal `$` use `$$`.
///
/// # Examples
///
/// Note that this function is polymorphic with respect to the replacement.
/// In typical usage, this can just be a normal string:
///
/// ```rust
/// # extern crate regex; use regex::Regex;
/// # fn main() {
/// let re = Regex::new("[^01]+").unwrap();
/// assert_eq!(re.replace("1078910", ""), "1010");
/// # }
/// ```
///
/// But anything satisfying the `Replacer` trait will work. For example,
/// a closure of type `|&Captures| -> String` provides direct access to the
/// captures corresponding to a match. This allows one to access
/// capturing group matches easily:
///
/// ```rust
/// # extern crate regex; use regex::Regex;
/// # use regex::Captures; fn main() {
/// let re = Regex::new(r"([^,\s]+),\s+(\S+)").unwrap();
/// let result = re.replace("Springsteen, Bruce", |caps: &Captures| {
/// format!("{} {}", &caps[2], &caps[1])
/// });
/// assert_eq!(result, "Bruce Springsteen");
/// # }
/// ```
///
/// But this is a bit cumbersome to use all the time. Instead, a simple
/// syntax is supported that expands `$name` into the corresponding capture
/// group. Here's the last example, but using this expansion technique
/// with named capture groups:
///
/// ```rust
/// # extern crate regex; use regex::Regex;
/// # fn main() {
/// let re = Regex::new(r"(?P<last>[^,\s]+),\s+(?P<first>\S+)").unwrap();
/// let result = re.replace("Springsteen, Bruce", "$first $last");
/// assert_eq!(result, "Bruce Springsteen");
/// # }
/// ```
///
/// Note that using `$2` instead of `$first` or `$1` instead of `$last`
/// would produce the same result. To write a literal `$` use `$$`.
///
/// Sometimes the replacement string requires use of curly braces to
/// delineate a capture group replacement and surrounding literal text.
/// For example, if we wanted to join two words together with an
/// underscore:
///
/// ```rust
/// # extern crate regex; use regex::Regex;
/// # fn main() {
/// let re = Regex::new(r"(?P<first>\w+)\s+(?P<second>\w+)").unwrap();
/// let result = re.replace("deep fried", "${first}_$second");
/// assert_eq!(result, "deep_fried");
/// # }
/// ```
///
/// Without the curly braces, the capture group name `first_` would be
/// used, and since it doesn't exist, it would be replaced with the empty
/// string.
///
/// Finally, sometimes you just want to replace a literal string with no
/// regard for capturing group expansion. This can be done by wrapping a
/// byte string with `NoExpand`:
///
/// ```rust
/// # extern crate regex; use regex::Regex;
/// # fn main() {
/// use regex::NoExpand;
///
/// let re = Regex::new(r"(?P<last>[^,\s]+),\s+(\S+)").unwrap();
/// let result = re.replace("Springsteen, Bruce", NoExpand("$2 $last"));
/// assert_eq!(result, "$2 $last");
/// # }
/// ```
pub fn replace<'t, R: Replacer>(
&self,
text: &'t str,
rep: R,
) -> Cow<'t, str> {
self.replacen(text, 1, rep)
}
/// Replaces all non-overlapping matches in `text` with the replacement
/// provided. This is the same as calling `replacen` with `limit` set to
/// `0`.
///
/// See the documentation for `replace` for details on how to access
/// capturing group matches in the replacement string.
pub fn replace_all<'t, R: Replacer>(
&self,
text: &'t str,
rep: R,
) -> Cow<'t, str> {
self.replacen(text, 0, rep)
}
/// Replaces at most `limit` non-overlapping matches in `text` with the
/// replacement provided. If `limit` is 0, then all non-overlapping matches
/// are replaced.
///
/// See the documentation for `replace` for details on how to access
/// capturing group matches in the replacement string.
pub fn replacen<'t, R: Replacer>(
&self,
text: &'t str,
limit: usize,
mut rep: R,
) -> Cow<'t, str> {
// If we know that the replacement doesn't have any capture expansions,
// then we can fast path. The fast path can make a tremendous
// difference:
//
// 1) We use `find_iter` instead of `captures_iter`. Not asking for
// captures generally makes the regex engines faster.
// 2) We don't need to look up all of the capture groups and do
// replacements inside the replacement string. We just push it
// at each match and be done with it.
if let Some(rep) = rep.no_expansion() {
let mut new = String::with_capacity(text.len());
let mut last_match = 0;
for (i, m) in self.find_iter(text).enumerate() {
if limit > 0 && i >= limit {
break
}
new.push_str(&text[last_match..m.start()]);
new.push_str(&rep);
last_match = m.end();
}
if last_match == 0 {
return Cow::Borrowed(text);
}
new.push_str(&text[last_match..]);
return Cow::Owned(new);
}
// The slower path, which we use if the replacement needs access to
// capture groups.
let mut it = self.captures_iter(text).enumerate().peekable();
if it.peek().is_none() {
return Cow::Borrowed(text);
}
let mut new = String::with_capacity(text.len());
let mut last_match = 0;
for (i, cap) in it {
if limit > 0 && i >= limit {
break
}
// unwrap on 0 is OK because captures only reports matches
let m = cap.get(0).unwrap();
new.push_str(&text[last_match..m.start()]);
rep.replace_append(&cap, &mut new);
last_match = m.end();
}
new.push_str(&text[last_match..]);
Cow::Owned(new)
}
}
/// Advanced or "lower level" search methods.
impl Regex {
/// Returns the end location of a match in the text given.
///
/// This method may have the same performance characteristics as
/// `is_match`, except it provides an end location for a match. In
/// particular, the location returned *may be shorter* than the proper end
/// of the leftmost-first match.
///
/// # Example
///
/// Typically, `a+` would match the entire first sequence of `a` in some
/// text, but `shortest_match` can give up as soon as it sees the first
/// `a`.
///
/// ```rust
/// # extern crate regex; use regex::Regex;
/// # fn main() {
/// let text = "aaaaa";
/// let pos = Regex::new(r"a+").unwrap().shortest_match(text);
/// assert_eq!(pos, Some(1));
/// # }
/// ```
pub fn shortest_match(&self, text: &str) -> Option<usize> {
self.shortest_match_at(text, 0)
}
/// Returns the same as shortest_match, but starts the search at the given
/// offset.
///
/// The significance of the starting point is that it takes the surrounding
/// context into consideration. For example, the `\A` anchor can only
/// match when `start == 0`.
#[doc(hidden)]
pub fn shortest_match_at(
&self,
text: &str,
start: usize,
) -> Option<usize> {
match self.0 {
_Regex::Dynamic(ref exec) => {
exec.searcher_str().shortest_match_at(text, start)
}
_Regex::Plugin(ref plug) => plug.shortest_match_at(text, start),
}
}
/// Returns the same as is_match, but starts the search at the given
/// offset.
///
/// The significance of the starting point is that it takes the surrounding
/// context into consideration. For example, the `\A` anchor can only
/// match when `start == 0`.
#[doc(hidden)]
pub fn is_match_at(&self, text: &str, start: usize) -> bool {
self.shortest_match_at(text, start).is_some()
}
/// Returns the same as find, but starts the search at the given
/// offset.
///
/// The significance of the starting point is that it takes the surrounding
/// context into consideration. For example, the `\A` anchor can only
/// match when `start == 0`.
#[doc(hidden)]
pub fn find_at<'t>(
&self,
text: &'t str,
start: usize,
) -> Option<Match<'t>> {
match self.0 {
_Regex::Dynamic(ref exec) => {
exec.searcher_str().find_at(text, start).map(|(s, e)| {
Match::new(text, s, e)
})
}
_Regex::Plugin(ref plug) => {
plug.find_at(text, start).map(|(s, e)| Match::new(text, s, e))
}
}
}
/// Returns the same as captures, but starts the search at the given
/// offset and populates the capture locations given.
///
/// The significance of the starting point is that it takes the surrounding
/// context into consideration. For example, the `\A` anchor can only
/// match when `start == 0`.
#[doc(hidden)]
pub fn read_captures_at<'t>(
&self,
locs: &mut Locations,
text: &'t str,
start: usize,
) -> Option<Match<'t>> {
match self.0 {
_Regex::Dynamic(ref exec) => {
exec.searcher_str().read_captures_at(locs, text, start)
.map(|(s, e)| Match::new(text, s, e))
}
_Regex::Plugin(ref plug) => {
plug.read_captures_at(locs, text, start)
.map(|(s, e)| Match::new(text, s, e))
}
}
}
}
/// Auxiliary methods.
impl Regex {
/// Returns the original string of this regex.
pub fn as_str(&self) -> &str {
match self.0 {
_Regex::Dynamic(ref exec) => &exec.regex_strings()[0],
_Regex::Plugin(ref plug) => &plug.original,
}
}
/// Returns an iterator over the capture names.
pub fn capture_names(&self) -> CaptureNames {
CaptureNames(match self.0 {
_Regex::Plugin(ref n) => _CaptureNames::Plugin(n.names.iter()),
_Regex::Dynamic(ref d) => {
_CaptureNames::Dynamic(d.capture_names().iter())
}
})
}
/// Returns the number of captures.
pub fn captures_len(&self) -> usize {
match self.0 {
_Regex::Plugin(ref n) => n.names.len(),
_Regex::Dynamic(ref d) => d.capture_names().len()
}
}
/// Returns an empty set of locations that can be reused in multiple calls
/// to `read_captures`.
#[doc(hidden)]
pub fn locations(&self) -> Locations {
match self.0 {
_Regex::Dynamic(ref exec) => {
exec.searcher_str().locations()
}
_Regex::Plugin(ref plug) => plug.locations(),
}
}
}
/// An iterator over the names of all possible captures.
///
/// `None` indicates an unnamed capture; the first element (capture 0, the
/// whole matched region) is always unnamed.
///
/// `'r` is the lifetime of the compiled regular expression.
pub struct CaptureNames<'r>(_CaptureNames<'r>);
enum _CaptureNames<'r> {
Plugin(::std::slice::Iter<'r, Option<&'static str>>),
Dynamic(::std::slice::Iter<'r, Option<String>>)
}
impl<'r> Iterator for CaptureNames<'r> {
type Item = Option<&'r str>;
fn next(&mut self) -> Option<Option<&'r str>> {
match self.0 {
_CaptureNames::Plugin(ref mut i) => i.next().cloned(),
_CaptureNames::Dynamic(ref mut i) => {
i.next().as_ref().map(|o| o.as_ref().map(|s| s.as_ref()))
}
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
match self.0 {
_CaptureNames::Plugin(ref i) => i.size_hint(),
_CaptureNames::Dynamic(ref i) => i.size_hint(),
}
}
}
/// Yields all substrings delimited by a regular expression match.
///
/// `'r` is the lifetime of the compiled regular expression and `'t` is the
/// lifetime of the string being split.
pub struct Split<'r, 't> {
finder: Matches<'r, 't>,
last: usize,
}
impl<'r, 't> Iterator for Split<'r, 't> {
type Item = &'t str;
fn next(&mut self) -> Option<&'t str> {
let text = self.finder.text();
match self.finder.next() {
None => {
if self.last >= text.len() {
None
} else {
let s = &text[self.last..];
self.last = text.len();
Some(s)
}
}
Some(m) => {
let matched = &text[self.last..m.start()];
self.last = m.end();
Some(matched)
}
}
}
}
/// Yields at most `N` substrings delimited by a regular expression match.
///
/// The last substring will be whatever remains after splitting.
///
/// `'r` is the lifetime of the compiled regular expression and `'t` is the
/// lifetime of the string being split.
pub struct SplitN<'r, 't> {
splits: Split<'r, 't>,
n: usize,
}
impl<'r, 't> Iterator for SplitN<'r, 't> {
type Item = &'t str;
fn next(&mut self) -> Option<&'t str> {
if self.n == 0 {
return None
}
self.n -= 1;
if self.n == 0 {
let text = self.splits.finder.text();
Some(&text[self.splits.last..])
} else {
self.splits.next()
}
}
}
enum NamedGroups {
Plugin(&'static [(&'static str, usize)]),
Dynamic(Arc<HashMap<String, usize>>),
}
impl NamedGroups {
fn from_regex(regex: &Regex) -> NamedGroups {
match regex.0 {
_Regex::Plugin(ref plug) => NamedGroups::Plugin(&plug.groups),
_Regex::Dynamic(ref exec) => {
NamedGroups::Dynamic(exec.capture_name_idx().clone())
}
}
}
fn pos(&self, name: &str) -> Option<usize> {
match *self {
NamedGroups::Plugin(groups) => {
groups.binary_search_by(|&(n, _)| n.cmp(name))
.ok().map(|i| groups[i].1)
},
NamedGroups::Dynamic(ref groups) => {
groups.get(name).map(|i| *i)
},
}
}
fn iter<'n>(&'n self) -> NamedGroupsIter<'n> {
match *self {
NamedGroups::Plugin(g) => NamedGroupsIter::Plugin(g.iter()),
NamedGroups::Dynamic(ref g) => NamedGroupsIter::Dynamic(g.iter()),
}
}
}
enum NamedGroupsIter<'n> {
Plugin(::std::slice::Iter<'static, (&'static str, usize)>),
Dynamic(::std::collections::hash_map::Iter<'n, String, usize>),
}
impl<'n> Iterator for NamedGroupsIter<'n> {
type Item = (&'n str, usize);
fn next(&mut self) -> Option<Self::Item> {
match *self {
NamedGroupsIter::Plugin(ref mut it) => it.next().map(|&v| v),
NamedGroupsIter::Dynamic(ref mut it) => {
it.next().map(|(s, i)| (s.as_ref(), *i))
}
}
}
}
/// Captures represents a group of captured strings for a single match.
///
/// The 0th capture always corresponds to the entire match. Each subsequent
/// index corresponds to the next capture group in the regex. If a capture
/// group is named, then the matched string is *also* available via the `name`
/// method. (Note that the 0th capture is always unnamed and so must be
/// accessed with the `get` method.)
///
/// Positions returned from a capture group are always byte indices.
///
/// `'t` is the lifetime of the matched text.
pub struct Captures<'t> {
text: &'t str,
locs: Locations,
named_groups: NamedGroups,
}
impl<'t> Captures<'t> {
/// Returns the match associated with the capture group at index `i`. If
/// `i` does not correspond to a capture group, or if the capture group
/// did not participate in the match, then `None` is returned.
///
/// # Examples
///
/// Get the text of the match with a default of an empty string if this
/// group didn't participate in the match:
///
/// ```rust
/// # use regex::Regex;
/// let re = Regex::new(r"[a-z]+(?:([0-9]+)|([A-Z]+))").unwrap();
/// let caps = re.captures("abc123").unwrap();
///
/// let text1 = caps.get(1).map_or("", |m| m.as_str());
/// let text2 = caps.get(2).map_or("", |m| m.as_str());
/// assert_eq!(text1, "123");
/// assert_eq!(text2, "");
/// ```
pub fn get(&self, i: usize) -> Option<Match<'t>> {
self.locs.pos(i).map(|(s, e)| Match::new(self.text, s, e))
}
/// Returns the match for the capture group named `name`. If `name` isn't a
/// valid capture group or didn't match anything, then `None` is returned.
pub fn name(&self, name: &str) -> Option<Match<'t>> {
self.named_groups.pos(name).and_then(|i| self.get(i))
}
/// An iterator that yields all capturing matches in the order in which
/// they appear in the regex. If a particular capture group didn't
/// participate in the match, then `None` is yielded for that capture.
///
/// The first match always corresponds to the overall match of the regex.
pub fn iter<'c>(&'c self) -> SubCaptureMatches<'c, 't> {
SubCaptureMatches {
caps: self,
it: self.locs.iter(),
}
}
/// Expands all instances of `$name` in `text` to the corresponding capture
/// group `name`, and writes them to the `dst` buffer given.
///
/// `name` may be an integer corresponding to the index of the
/// capture group (counted by order of opening parenthesis where `0` is the
/// entire match) or it can be a name (consisting of letters, digits or
/// underscores) corresponding to a named capture group.
///
/// If `name` isn't a valid capture group (whether the name doesn't exist
/// or isn't a valid index), then it is replaced with the empty string.
///
/// The longest possible name is used. e.g., `$1a` looks up the capture
/// group named `1a` and not the capture group at index `1`. To exert more
/// precise control over the name, use braces, e.g., `${1}a`.
///
/// To write a literal `$` use `$$`.
pub fn expand(&self, replacement: &str, dst: &mut String) {
expand_str(self, replacement, dst)
}
/// Returns the number of captured groups.
///
/// This is always at least `1`, since every regex has at least one capture
/// group that corresponds to the full match.
#[inline]
pub fn len(&self) -> usize {
self.locs.len()
}
}
impl<'t> fmt::Debug for Captures<'t> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("Captures").field(&CapturesDebug(self)).finish()
}
}
struct CapturesDebug<'c, 't: 'c>(&'c Captures<'t>);
impl<'c, 't> fmt::Debug for CapturesDebug<'c, 't> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// We'd like to show something nice here, even if it means an
// allocation to build a reverse index.
let slot_to_name: HashMap<usize, &str> =
self.0.named_groups.iter().map(|(a, b)| (b, a)).collect();
let mut map = f.debug_map();
for (slot, m) in self.0.locs.iter().enumerate() {
let m = m.map(|(s, e)| &self.0.text[s..e]);
if let Some(ref name) = slot_to_name.get(&slot) {
map.entry(&name, &m);
} else {
map.entry(&slot, &m);
}
}
map.finish()
}
}
/// Get a group by index.
///
/// `'t` is the lifetime of the matched text.
///
/// The text can't outlive the `Captures` object if this method is
/// used, because of how `Index` is defined (normally `a[i]` is part
/// of `a` and can't outlive it); to do that, use `get()` instead.
///
/// # Panics
///
/// If there is no group at the given index.
impl<'t> Index<usize> for Captures<'t> {
type Output = str;
fn index(&self, i: usize) -> &str {
self.get(i).map(|m| m.as_str())
.unwrap_or_else(|| panic!("no group at index '{}'", i))
}
}
/// Get a group by name.
///
/// `'t` is the lifetime of the matched text and `'i` is the lifetime
/// of the group name (the index).
///
/// The text can't outlive the `Captures` object if this method is
/// used, because of how `Index` is defined (normally `a[i]` is part
/// of `a` and can't outlive it); to do that, use `name` instead.
///
/// # Panics
///
/// If there is no group named by the given value.
impl<'t, 'i> Index<&'i str> for Captures<'t> {
type Output = str;
fn index<'a>(&'a self, name: &'i str) -> &'a str {
self.name(name).map(|m| m.as_str())
.unwrap_or_else(|| panic!("no group named '{}'", name))
}
}
/// An iterator that yields all capturing matches in the order in which they
/// appear in the regex.
///
/// If a particular capture group didn't participate in the match, then `None`
/// is yielded for that capture. The first match always corresponds to the
/// overall match of the regex.
///
/// The lifetime `'c` corresponds to the lifetime of the `Captures` value, and
/// the lifetime `'t` corresponds to the originally matched text.
pub struct SubCaptureMatches<'c, 't: 'c> {
caps: &'c Captures<'t>,
it: SubCapturesPosIter<'c>,
}
impl<'c, 't> Iterator for SubCaptureMatches<'c, 't> {
type Item = Option<Match<'t>>;
fn next(&mut self) -> Option<Option<Match<'t>>> {
self.it.next()
.map(|cap| cap.map(|(s, e)| Match::new(self.caps.text, s, e)))
}
}
/// An iterator that yields all non-overlapping capture groups matching a
/// particular regular expression.
///
/// The iterator stops when no more matches can be found.
///
/// `'r` is the lifetime of the compiled regular expression and `'t` is the
/// lifetime of the matched string.
pub struct CaptureMatches<'r, 't>(CaptureMatchesInner<'r, 't>);
enum CaptureMatchesInner<'r, 't> {
Dynamic(re_trait::CaptureMatches<'t, ExecNoSyncStr<'r>>),
Plugin(re_trait::CaptureMatches<'t, Plugin>),
}
impl<'r, 't> Iterator for CaptureMatches<'r, 't> {
type Item = Captures<'t>;
fn next(&mut self) -> Option<Captures<'t>> {
match self.0 {
CaptureMatchesInner::Dynamic(ref mut it) => {
let named = it.regex().capture_name_idx().clone();
it.next().map(|locs| Captures {
text: it.text(),
locs: locs,
named_groups: NamedGroups::Dynamic(named),
})
}
CaptureMatchesInner::Plugin(ref mut it) => {
it.next().map(|locs| Captures {
text: it.text(),
locs: locs,
named_groups: NamedGroups::Plugin(it.regex().groups),
})
}
}
}
}
/// An iterator over all non-overlapping matches for a particular string.
///
/// The iterator yields a `Match` value. The iterator stops when no more
/// matches can be found.
///
/// `'r` is the lifetime of the compiled regular expression and `'t` is the
/// lifetime of the matched string.
pub struct Matches<'r, 't>(MatchesInner<'r, 't>);
enum MatchesInner<'r, 't> {
Dynamic(re_trait::Matches<'t, ExecNoSyncStr<'r>>),
Plugin(re_trait::Matches<'t, Plugin>),
}
impl<'r, 't> Matches<'r, 't> {
fn text(&self) -> &'t str {
match self.0 {
MatchesInner::Dynamic(ref it) => it.text(),
MatchesInner::Plugin(ref it) => it.text(),
}
}
}
impl<'r, 't> Iterator for Matches<'r, 't> {
type Item = Match<'t>;
fn next(&mut self) -> Option<Match<'t>> {
let text = self.text();
match self.0 {
MatchesInner::Dynamic(ref mut it) => {
it.next().map(|(s, e)| Match::new(text, s, e))
}
MatchesInner::Plugin(ref mut it) => {
it.next().map(|(s, e)| Match::new(text, s, e))
}
}
}
}
/// Replacer describes types that can be used to replace matches in a string.
///
/// In general, users of this crate shouldn't need to implement this trait,
/// since implementations are already provided for `&str` and
/// `FnMut(&Captures) -> String`, which covers most use cases.
pub trait Replacer {
/// Appends text to `dst` to replace the current match.
///
/// The current match is represented by `caps`, which is guaranteed to
/// have a match at capture group `0`.
///
/// For example, a no-op replacement would be
/// `dst.extend(caps.get(0).unwrap().as_str())`.
fn replace_append(&mut self, caps: &Captures, dst: &mut String);
/// Return a fixed unchanging replacement string.
///
/// When doing replacements, if access to `Captures` is not needed (e.g.,
/// the replacement byte string does not need `$` expansion), then it can
/// be beneficial to avoid finding sub-captures.
///
/// In general, this is called once for every call to `replacen`.
fn no_expansion<'r>(&'r mut self) -> Option<Cow<'r, str>> {
None
}
}
impl<'a> Replacer for &'a str {
fn replace_append(&mut self, caps: &Captures, dst: &mut String) {
caps.expand(*self, dst);
}
fn no_expansion<'r>(&'r mut self) -> Option<Cow<'r, str>> {
match memchr(b'$', self.as_bytes()) {
Some(_) => None,
None => Some(Cow::Borrowed(*self)),
}
}
}
impl<F> Replacer for F where F: FnMut(&Captures) -> String {
fn replace_append(&mut self, caps: &Captures, dst: &mut String) {
dst.push_str(&(*self)(caps));
}
}
/// NoExpand indicates literal string replacement.
///
/// It can be used with `replace` and `replace_all` to do a literal string
/// replacement without expanding `$name` to their corresponding capture
/// groups. This can be both convenient (to avoid escaping `$`, for example)
/// and performant (since capture groups don't need to be found).
///
/// `'t` is the lifetime of the literal text.
pub struct NoExpand<'t>(pub &'t str);
impl<'t> Replacer for NoExpand<'t> {
fn replace_append(&mut self, _: &Captures, dst: &mut String) {
dst.push_str(self.0);
}
fn no_expansion<'r>(&'r mut self) -> Option<Cow<'r, str>> {
Some(Cow::Borrowed(self.0))
}
}
| 34.621163 | 83 | 0.568256 |
e4697127e4182b6b9056053cfe4edaffbdc3211a | 2,744 | #[allow(unused_imports)]
use builtin::*;
mod pervasive;
use pervasive::*;
use state_machines_macros::state_machine;
use state_machines_macros::case_on_next;
use state_machines_macros::case_on_init;
state_machine!{
B {
fields {
pub number: int,
}
init!{
initialize() {
init number = 0;
}
}
transition!{
add(n: int) {
require(n % 2 == 0);
update number = pre.number + n;
}
}
#[invariant]
pub fn is_even(&self) -> bool {
self.number % 2 == 0
}
#[inductive(initialize)]
fn initialize_inductive(post: Self) { }
#[inductive(add)]
fn add_inductive(pre: Self, post: Self, n: int) { }
}
}
state_machine!{
A {
fields {
pub number: int,
}
init!{
initialize() {
init number = 0;
}
}
transition!{
add(n: int) {
update number = pre.number + n;
}
}
#[inductive(initialize)]
fn initialize_inductive(post: Self) { }
#[inductive(add)]
fn add_inductive(pre: Self, post: Self, n: int) { }
}
}
#[spec]
fn interp(a: A::State) -> B::State {
B::State {
number: a.number * 2,
}
}
#[proof]
fn next_refines_next(pre: A::State, post: A::State) {
requires(pre.invariant()
&& post.invariant()
&& interp(pre).invariant()
&& A::State::next(pre, post)
);
ensures(B::State::next(interp(pre), interp(post)));
reveal(A::State::next);
match choose(|step: A::Step| A::State::next_by(pre, post, step)) {
A::Step::add(n) => {
assert_by(A::State::add(pre, post, n), { reveal(A::State::next_by); });
B::show::add(interp(pre), interp(post), 2 * n);
}
A::Step::dummy_to_use_type_params(_) => {
assume(false); // TODO
}
}
}
#[proof]
fn next_refines_next_with_macro(pre: A::State, post: A::State) {
requires(pre.invariant()
&& post.invariant()
&& interp(pre).invariant()
&& A::State::next(pre, post)
);
ensures(B::State::next(interp(pre), interp(post)));
case_on_next!{pre, post, A => {
add(n) => {
B::show::add(interp(pre), interp(post), 2 * n);
}
}}
}
#[proof]
fn init_refines_init_with_macro(post: A::State) {
requires(post.invariant() && A::State::init(post));
ensures(B::State::init(interp(post)));
case_on_init!{post, A => {
initialize() => {
B::show::initialize(interp(post));
}
}}
}
fn main() { }
| 21.107692 | 83 | 0.492347 |
f7c07cb204e33ca3b6dede13a2edfa6388edfcc3 | 12,079 | use crate::{app::ldtk_entity::*, app::ldtk_int_cell::*};
use bevy::prelude::*;
/// Provides functions to register [Bundle]s to bevy's [App] for particular LDtk layer identifiers,
/// entity identifiers, and IntGrid values.
///
/// After being registered, [Entity]s will be spawned with these bundles when some IntGrid tile or
/// entity meets the criteria you specify.
///
/// Not necessarily intended for custom implementations on your own types.
pub trait RegisterLdtkObjects {
/// Used internally by all the other LDtk entity registration functions.
///
/// Similar to [RegisterLdtkObjects::register_ldtk_entity_for_layer], except it provides
/// defaulting functionality:
/// - Setting `layer_identifier` to [None] will make the registration apply to any Entity layer.
/// - Setting `entity_identifier` to [None] will make the registration apply to any LDtk entity.
///
/// This defaulting functionality means that a particular instance of an LDtk entity may match
/// multiple registrations.
/// In these cases, registrations are prioritized in order of most to least specific:
/// 1. `layer_identifier` and `entity_identifier` are specified
/// 2. Just `entity_identifier` is specified
/// 3. Just `layer_identifier` is specified
/// 4. Neither `entity_identifier` nor `layer_identifier` are specified
fn register_ldtk_entity_for_layer_optional<B: LdtkEntity + Bundle>(
&mut self,
layer_identifier: Option<String>,
entity_identifier: Option<String>,
) -> &mut Self;
/// Registers [LdtkEntity] types to be spawned for a given Entity identifier and layer
/// identifier in an LDtk file.
///
/// This example lets the plugin know that it should spawn a MyBundle when it encounters a
/// "my_entity_identifier" entity on a "MyLayerIdentifier" layer.
/// ```no_run
/// use bevy::prelude::*;
/// use bevy_ecs_ldtk::prelude::*;
///
/// fn main() {
/// App::empty()
/// .add_plugin(LdtkPlugin)
/// .register_ldtk_entity_for_layer::<MyBundle>("MyLayerIdentifier", "my_entity_identifier")
/// // add other systems, plugins, resources...
/// .run();
/// }
///
/// # #[derive(Component, Default)]
/// # struct ComponentA;
/// # #[derive(Component, Default)]
/// # struct ComponentB;
/// # #[derive(Component, Default)]
/// # struct ComponentC;
/// #[derive(Bundle, LdtkEntity)]
/// pub struct MyBundle {
/// a: ComponentA,
/// b: ComponentB,
/// c: ComponentC,
/// }
/// ```
///
/// You can find more details on the `#[derive(LdtkEntity)]` macro at [LdtkEntity].
fn register_ldtk_entity_for_layer<B: LdtkEntity + Bundle>(
&mut self,
layer_identifier: &str,
entity_identifier: &str,
) -> &mut Self {
self.register_ldtk_entity_for_layer_optional::<B>(
Some(layer_identifier.to_string()),
Some(entity_identifier.to_string()),
)
}
/// Similar to [RegisterLdtkObjects::register_ldtk_entity_for_layer], except it applies the
/// registration to all layers.
fn register_ldtk_entity<B: LdtkEntity + Bundle>(
&mut self,
entity_identifier: &str,
) -> &mut Self {
self.register_ldtk_entity_for_layer_optional::<B>(None, Some(entity_identifier.to_string()))
}
/// Similar to [RegisterLdtkObjects::register_ldtk_entity_for_layer], except it applies the
/// registration to all entities on the given layer.
fn register_default_ldtk_entity_for_layer<B: LdtkEntity + Bundle>(
&mut self,
layer_identifier: &str,
) -> &mut Self {
self.register_ldtk_entity_for_layer_optional::<B>(Some(layer_identifier.to_string()), None)
}
/// Similar to [RegisterLdtkObjects::register_ldtk_entity_for_layer], except it applies the
/// registration to any entity and any layer.
fn register_default_ldtk_entity<B: LdtkEntity + Bundle>(&mut self) -> &mut Self {
self.register_ldtk_entity_for_layer_optional::<B>(None, None)
}
/// Used internally by all the other LDtk int cell registration functions.
///
/// Similar to [RegisterLdtkObjects::register_ldtk_int_cell_for_layer], except it provides
/// defaulting functionality:
/// - Setting `layer_identifier` to [None] will make the registration apply to any IntGrid layer.
/// - Setting `value` to [None] will make the registration apply to any IntGrid tile.
///
/// This defaulting functionality means that a particular LDtk IntGrid tile may match multiple
/// registrations.
/// In these cases, registrations are prioritized in order of most to least specific:
/// 1. `layer_identifier` and `value` are specified
/// 2. Just `value` is specified
/// 3. Just `layer_identifier` is specified
/// 4. Neither `value` nor `layer_identifier` are specified
fn register_ldtk_int_cell_for_layer_optional<B: LdtkIntCell + Bundle>(
&mut self,
layer_identifier: Option<String>,
value: Option<i32>,
) -> &mut Self;
/// Registers [LdtkIntCell] types to be inserted for a given IntGrid value and layer identifier
/// in an LDtk file.
///
/// This example lets the plugin know that it should spawn a MyBundle when it encounters an
/// IntGrid tile whose value is `1` on a "MyLayerIdentifier" layer.
/// ```no_run
/// use bevy::prelude::*;
/// use bevy_ecs_ldtk::prelude::*;
///
/// fn main() {
/// App::empty()
/// .add_plugin(LdtkPlugin)
/// .register_ldtk_int_cell_for_layer::<MyBundle>("MyLayerIdentifier", 1)
/// // add other systems, plugins, resources...
/// .run();
/// }
///
/// # #[derive(Component, Default)]
/// # struct ComponentA;
/// # #[derive(Component, Default)]
/// # struct ComponentB;
/// # #[derive(Component, Default)]
/// # struct ComponentC;
/// #[derive(Bundle, LdtkIntCell)]
/// pub struct MyBundle {
/// a: ComponentA,
/// b: ComponentB,
/// c: ComponentC,
/// }
/// ```
///
/// You can find more details on the `#[derive(LdtkIntCell)]` macro at [LdtkIntCell].
fn register_ldtk_int_cell_for_layer<B: LdtkIntCell + Bundle>(
&mut self,
layer_identifier: &str,
value: i32,
) -> &mut Self {
self.register_ldtk_int_cell_for_layer_optional::<B>(
Some(layer_identifier.to_string()),
Some(value),
)
}
/// Similar to [RegisterLdtkObjects::register_ldtk_int_cell_for_layer], except it applies the
/// registration to all layers.
fn register_ldtk_int_cell<B: LdtkIntCell + Bundle>(&mut self, value: i32) -> &mut Self {
self.register_ldtk_int_cell_for_layer_optional::<B>(None, Some(value))
}
/// Similar to [RegisterLdtkObjects::register_ldtk_int_cell_for_layer], except it applies the
/// registration to all tiles on the given layer.
fn register_default_ldtk_int_cell_for_layer<B: LdtkIntCell + Bundle>(
&mut self,
layer_identifier: &str,
) -> &mut Self {
self.register_ldtk_int_cell_for_layer_optional::<B>(
Some(layer_identifier.to_string()),
None,
)
}
/// Similar to [RegisterLdtkObjects::register_ldtk_int_cell_for_layer], except it applies the
/// registration to any tile and any layer.
fn register_default_ldtk_int_cell<B: LdtkIntCell + Bundle>(&mut self) -> &mut Self {
self.register_ldtk_int_cell_for_layer_optional::<B>(None, None)
}
}
impl RegisterLdtkObjects for App {
fn register_ldtk_entity_for_layer_optional<B: LdtkEntity + Bundle>(
&mut self,
layer_identifier: Option<String>,
entity_identifier: Option<String>,
) -> &mut Self {
let new_entry = Box::new(PhantomLdtkEntity::<B>::new());
match self.world.get_non_send_resource_mut::<LdtkEntityMap>() {
Some(mut entries) => {
entries.insert((layer_identifier, entity_identifier), new_entry);
}
None => {
let mut bundle_map = LdtkEntityMap::new();
bundle_map.insert((layer_identifier, entity_identifier), new_entry);
self.world.insert_non_send::<LdtkEntityMap>(bundle_map);
}
}
self
}
fn register_ldtk_int_cell_for_layer_optional<B: LdtkIntCell + Bundle>(
&mut self,
layer_identifier: Option<String>,
value: Option<i32>,
) -> &mut Self {
let new_entry = Box::new(PhantomLdtkIntCell::<B>::new());
match self.world.get_non_send_resource_mut::<LdtkIntCellMap>() {
Some(mut entries) => {
entries.insert((layer_identifier, value), new_entry);
}
None => {
let mut bundle_map = LdtkIntCellMap::new();
bundle_map.insert((layer_identifier, value), new_entry);
self.world.insert_non_send::<LdtkIntCellMap>(bundle_map);
}
}
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
components::{EntityInstance, IntGridCell},
ldtk::{LayerInstance, TilesetDefinition},
};
#[derive(Default, Component, Debug)]
struct ComponentA;
#[derive(Default, Component, Debug)]
struct ComponentB;
#[derive(Default, Bundle, Debug)]
struct LdtkEntityBundle {
a: ComponentA,
b: ComponentB,
}
impl LdtkEntity for LdtkEntityBundle {
fn bundle_entity(
_: &EntityInstance,
_: &LayerInstance,
_: Option<&Handle<Image>>,
_: Option<&TilesetDefinition>,
_: &AssetServer,
_: &mut Assets<TextureAtlas>,
) -> LdtkEntityBundle {
LdtkEntityBundle::default()
}
}
#[derive(Default, Bundle)]
struct LdtkIntCellBundle {
a: ComponentA,
b: ComponentB,
}
impl LdtkIntCell for LdtkIntCellBundle {
fn bundle_int_cell(_: IntGridCell, _: &LayerInstance) -> LdtkIntCellBundle {
LdtkIntCellBundle::default()
}
}
#[test]
fn test_ldtk_entity_registrations() {
let mut app = App::new();
app.register_ldtk_entity_for_layer::<LdtkEntityBundle>("layer", "entity_for_layer")
.register_ldtk_entity::<LdtkEntityBundle>("entity")
.register_default_ldtk_entity_for_layer::<LdtkEntityBundle>("default_entity_for_layer")
.register_default_ldtk_entity::<LdtkEntityBundle>();
let ldtk_entity_map = app.world.get_non_send_resource::<LdtkEntityMap>().unwrap();
assert!(ldtk_entity_map.contains_key(&(
Some("layer".to_string()),
Some("entity_for_layer".to_string())
)));
assert!(ldtk_entity_map.contains_key(&(None, Some("entity".to_string()))));
assert!(ldtk_entity_map.contains_key(&(Some("default_entity_for_layer".to_string()), None)));
assert!(ldtk_entity_map.contains_key(&(None, None)));
}
#[test]
fn test_ldtk_int_cell_registrations() {
let mut app = App::new();
app.register_ldtk_int_cell_for_layer::<LdtkIntCellBundle>("layer", 1)
.register_ldtk_int_cell::<LdtkIntCellBundle>(2)
.register_default_ldtk_int_cell_for_layer::<LdtkIntCellBundle>(
"default_int_cell_for_layer",
)
.register_default_ldtk_int_cell::<LdtkIntCellBundle>();
let ldtk_int_cell_map = app.world.get_non_send_resource::<LdtkIntCellMap>().unwrap();
assert!(ldtk_int_cell_map.contains_key(&(Some("layer".to_string()), Some(1))));
assert!(ldtk_int_cell_map.contains_key(&(None, Some(2))));
assert!(
ldtk_int_cell_map.contains_key(&(Some("default_int_cell_for_layer".to_string()), None))
);
assert!(ldtk_int_cell_map.contains_key(&(None, None)));
}
}
| 38.104101 | 104 | 0.632585 |
edce187e7c88b02ee4909d29c50d0c6b5c73202f | 6,576 | #![cfg(feature = "std")]
const VALUES: &[&str] = &[
"Rust",
"C",
"C++",
"C#",
"JavaScript",
"TypeScript",
"Java",
"Kotlin",
"Go",
];
const EXPECTED_LEFT: &[&str] = &[
"Rust------",
"C---------",
"C++-------",
"C#--------",
"JavaScript",
"TypeScript",
"Java------",
"Kotlin----",
"Go--------",
];
const EXPECTED_RIGHT: &[&str] = &[
"------Rust",
"---------C",
"-------C++",
"--------C#",
"JavaScript",
"TypeScript",
"------Java",
"----Kotlin",
"--------Go",
];
const EXPECTED_CENTER_LEFT: &[&str] = &[
"---Rust---",
"----C-----",
"---C++----",
"----C#----",
"JavaScript",
"TypeScript",
"---Java---",
"--Kotlin--",
"----Go----",
];
const EXPECTED_CENTER_RIGHT: &[&str] = &[
"---Rust---",
"-----C----",
"----C++---",
"----C#----",
"JavaScript",
"TypeScript",
"---Java---",
"--Kotlin--",
"----Go----",
];
macro_rules! test_case {
(
$name:ident
where
pad = $pad:ident,
alignment = $alignment:ident,
values = $values:expr,
expectation = $expected:ident,
) => {
mod $name {
use super::*;
use fmt_iter::FmtIter;
use pipe_trait::Pipe;
use pretty_assertions::assert_eq;
use zero_copy_pads::{$pad, Alignment, PaddedColumn, Width};
#[test]
fn pad_instance() {
let values = $values;
let padded_column = PaddedColumn {
values: values.into_iter(),
pad_block: '-',
pad: $pad,
};
let actual: Vec<_> = padded_column.into_iter().map(|x| x.to_string()).collect();
assert_eq!(actual, $expected);
}
#[test]
fn alignment() {
let values = $values;
let padded_column = PaddedColumn {
values: values.into_iter(),
pad_block: '-',
pad: Alignment::$alignment,
};
let actual: Vec<_> = padded_column.into_iter().map(|x| x.to_string()).collect();
assert_eq!(actual, $expected);
}
#[test]
fn fmt_iter_width() {
let values = $values;
let actual = PaddedColumn {
values: values.iter(),
pad_block: '-',
pad: $pad,
}
.into_iter()
.pipe(FmtIter::from)
.width();
let expected = values
.iter()
.map(|x| x.len())
.max()
.expect("length of the longest string")
.pipe(|x| x * values.len());
assert_eq!(actual, expected);
}
}
};
}
test_case! {
align_left_array_of_str_slices
where
pad = AlignLeft,
alignment = Left,
values = VALUES,
expectation = EXPECTED_LEFT,
}
test_case! {
align_right_array_of_str_slices
where
pad = AlignRight,
alignment = Right,
values = VALUES,
expectation = EXPECTED_RIGHT,
}
test_case! {
align_center_left_array_of_str_slices
where
pad = AlignCenterLeft,
alignment = CenterLeft,
values = VALUES,
expectation = EXPECTED_CENTER_LEFT,
}
test_case! {
align_center_right_array_of_str_slices
where
pad = AlignCenterRight,
alignment = CenterRight,
values = VALUES,
expectation = EXPECTED_CENTER_RIGHT,
}
test_case! {
align_left_vec_of_str_indirect_references
where
pad = AlignLeft,
alignment = Left,
values = VALUES.iter().collect::<Vec<&&str>>(),
expectation = EXPECTED_LEFT,
}
test_case! {
align_right_vec_of_str_indirect_references
where
pad = AlignRight,
alignment = Right,
values = VALUES.iter().collect::<Vec<&&str>>(),
expectation = EXPECTED_RIGHT,
}
test_case! {
align_center_left_vec_of_str_indirect_references
where
pad = AlignCenterLeft,
alignment = CenterLeft,
values = VALUES.iter().collect::<Vec<&&str>>(),
expectation = EXPECTED_CENTER_LEFT,
}
test_case! {
align_center_right_vec_of_str_indirect_references
where
pad = AlignCenterRight,
alignment = CenterRight,
values = VALUES.iter().collect::<Vec<&&str>>(),
expectation = EXPECTED_CENTER_RIGHT,
}
test_case! {
align_left_vec_of_owned_strings
where
pad = AlignLeft,
alignment = Left,
values = VALUES.iter().map(ToString::to_string).collect::<Vec<String>>(),
expectation = EXPECTED_LEFT,
}
test_case! {
align_right_vec_of_owned_strings
where
pad = AlignRight,
alignment = Right,
values = VALUES.iter().map(ToString::to_string).collect::<Vec<String>>(),
expectation = EXPECTED_RIGHT,
}
test_case! {
align_center_left_vec_of_owned_strings
where
pad = AlignCenterLeft,
alignment = CenterLeft,
values = VALUES.iter().map(ToString::to_string).collect::<Vec<String>>(),
expectation = EXPECTED_CENTER_LEFT,
}
test_case! {
align_center_right_vec_of_owned_strings
where
pad = AlignCenterRight,
alignment = CenterRight,
values = VALUES.iter().map(ToString::to_string).collect::<Vec<String>>(),
expectation = EXPECTED_CENTER_RIGHT,
}
test_case! {
align_left_vec_of_str_slices
where
pad = AlignLeft,
alignment = Left,
values = VALUES.iter().copied().collect::<Vec<&str>>(),
expectation = EXPECTED_LEFT,
}
test_case! {
align_right_vec_of_str_slices
where
pad = AlignRight,
alignment = Right,
values = VALUES.iter().copied().collect::<Vec<&str>>(),
expectation = EXPECTED_RIGHT,
}
test_case! {
align_center_left_vec_of_str_slices
where
pad = AlignCenterLeft,
alignment = CenterLeft,
values = VALUES.iter().copied().collect::<Vec<&str>>(),
expectation = EXPECTED_CENTER_LEFT,
}
test_case! {
align_center_right_vec_of_str_slices
where
pad = AlignCenterRight,
alignment = CenterRight,
values = VALUES.iter().copied().collect::<Vec<&str>>(),
expectation = EXPECTED_CENTER_RIGHT,
}
| 24.446097 | 96 | 0.519313 |
fe3df462abcb036eb2b1304740aa03cbce0c5c51 | 599 | #![feature(test)]
extern crate route_recognizer;
extern crate test;
use route_recognizer::Router;
#[bench]
fn benchmark(b: &mut test::Bencher) {
let mut router = Router::new();
router.add("/posts/:post_id/comments/:id", "comment".to_string());
router.add("/posts/:post_id/comments", "comments".to_string());
router.add("/posts/:post_id", "post".to_string());
router.add("/posts", "posts".to_string());
router.add("/comments", "comments2".to_string());
router.add("/comments/:id", "comment2".to_string());
b.iter(|| router.recognize("/posts/100/comments/200"));
}
| 29.95 | 70 | 0.659432 |
1a34fe59e0a76b31244dbebf4bd696e3ebf3c319 | 7,526 | //! Build program to generate a program which runs all the testsuites.
//!
//! By generating a separate `#[test]` test for each file, we allow cargo test
//! to automatically run the files in parallel.
//!
//! Idea adapted from: https://github.com/CraneStation/wasmtime/blob/master/build.rs
//! Thanks @sunfishcode
fn main() {
#[cfg(feature = "wasm_tests")]
wasm_tests::build_and_generate_tests();
}
#[cfg(feature = "wasm_tests")]
mod wasm_tests {
use std::env;
use std::fs::{read_dir, DirEntry, File};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
pub(crate) fn build_and_generate_tests() {
// Validate if any of test sources are present and if they changed
// This should always work since there is no submodule to init anymore
let bin_tests = std::fs::read_dir("wasi-misc-tests/src/bin").unwrap();
for test in bin_tests {
if let Ok(test_file) = test {
let test_file_path = test_file
.path()
.into_os_string()
.into_string()
.expect("test file path");
println!("cargo:rerun-if-changed={}", test_file_path);
}
}
// Build tests to OUT_DIR (target/*/build/wasi-common-*/out/wasm32-wasi/release/*.wasm)
let out_dir = PathBuf::from(
env::var("OUT_DIR").expect("The OUT_DIR environment variable must be set"),
);
let mut out = File::create(out_dir.join("wasi_misc_tests.rs"))
.expect("error generating test source file");
build_tests("wasi-misc-tests", &out_dir).expect("building tests");
test_directory(&mut out, "wasi-misc-tests", &out_dir).expect("generating tests");
}
fn build_tests(testsuite: &str, out_dir: &Path) -> io::Result<()> {
let mut cmd = Command::new("cargo");
cmd.args(&[
"build",
"--release",
"--target=wasm32-wasi",
"--target-dir",
out_dir.to_str().unwrap(),
])
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.current_dir(testsuite);
let output = cmd.output()?;
let status = output.status;
if !status.success() {
panic!(
"Building tests failed: exit code: {}",
status.code().unwrap()
);
}
Ok(())
}
fn test_directory(out: &mut File, testsuite: &str, out_dir: &Path) -> io::Result<()> {
let mut dir_entries: Vec<_> = read_dir(out_dir.join("wasm32-wasi/release"))
.expect("reading testsuite directory")
.map(|r| r.expect("reading testsuite directory entry"))
.filter(|dir_entry| {
let p = dir_entry.path();
if let Some(ext) = p.extension() {
// Only look at wast files.
if ext == "wasm" {
// Ignore files starting with `.`, which could be editor temporary files
if let Some(stem) = p.file_stem() {
if let Some(stemstr) = stem.to_str() {
if !stemstr.starts_with('.') {
return true;
}
}
}
}
}
false
})
.collect();
dir_entries.sort_by_key(|dir| dir.path());
writeln!(
out,
"mod {} {{",
Path::new(testsuite)
.file_stem()
.expect("testsuite filename should have a stem")
.to_str()
.expect("testsuite filename should be representable as a string")
.replace("-", "_")
)?;
writeln!(out, " use super::{{runtime, utils, setup_log}};")?;
for dir_entry in dir_entries {
write_testsuite_tests(out, dir_entry, testsuite)?;
}
writeln!(out, "}}")?;
Ok(())
}
fn write_testsuite_tests(
out: &mut File,
dir_entry: DirEntry,
testsuite: &str,
) -> io::Result<()> {
let path = dir_entry.path();
let stemstr = path
.file_stem()
.expect("file_stem")
.to_str()
.expect("to_str");
writeln!(out, " #[test]")?;
if ignore(testsuite, stemstr) {
writeln!(out, " #[ignore]")?;
}
writeln!(
out,
" fn {}() -> Result<(), String> {{",
avoid_keywords(&stemstr.replace("-", "_"))
)?;
writeln!(out, " setup_log();")?;
write!(out, " let path = std::path::Path::new(\"")?;
// Write out the string with escape_debug to prevent special characters such
// as backslash from being reinterpreted.
for c in path.display().to_string().chars() {
write!(out, "{}", c.escape_debug())?;
}
writeln!(out, "\");")?;
writeln!(out, " let data = utils::read_wasm(path)?;")?;
writeln!(
out,
" let bin_name = utils::extract_exec_name_from_path(path)?;"
)?;
let workspace = if no_preopens(testsuite, stemstr) {
"None"
} else {
writeln!(
out,
" let workspace = utils::prepare_workspace(&bin_name)?;"
)?;
"Some(workspace.path())"
};
writeln!(
out,
" runtime::instantiate(&data, &bin_name, {})",
workspace
)?;
writeln!(out, " }}")?;
writeln!(out)?;
Ok(())
}
/// Rename tests which have the same name as Rust keywords.
fn avoid_keywords(name: &str) -> &str {
match name {
"if" => "if_",
"loop" => "loop_",
"type" => "type_",
"const" => "const_",
"return" => "return_",
other => other,
}
}
cfg_if::cfg_if! {
if #[cfg(not(windows))] {
/// Ignore tests that aren't supported yet.
fn ignore(_testsuite: &str, _name: &str) -> bool {
false
}
} else {
/// Ignore tests that aren't supported yet.
fn ignore(testsuite: &str, name: &str) -> bool {
if testsuite == "wasi-misc-tests" {
match name {
"readlink_no_buffer" => true,
"dangling_symlink" => true,
"symlink_loop" => true,
"truncation_rights" => true,
"path_rename_trailing_slashes" => true,
"fd_readdir" => true,
"poll_oneoff" => true,
_ => false,
}
} else {
unreachable!()
}
}
}
}
/// Mark tests which do not require preopens
fn no_preopens(testsuite: &str, name: &str) -> bool {
if testsuite == "wasi-misc-tests" {
match name {
"big_random_buf" => true,
"clock_time_get" => true,
"sched_yield" => true,
_ => false,
}
} else {
unreachable!()
}
}
}
| 34.209091 | 96 | 0.46625 |
186e29c22176e31433a89ff3b2744a1282df919e | 3,974 | use crate::{functions::*, ndarray_util::as_2d, *};
use ndarray::s;
pub struct SelectNet<
S: Layer<Input = Computed, Output = Computed>,
L: Layer<Input = Computed, Output = Computed>,
> {
pub output_size: usize,
pub select_layer: S,
pub layers: Vec<L>,
}
impl<S: Layer<Input = Computed, Output = Computed>, L: Layer<Input = Computed, Output = Computed>>
SelectNet<S, L>
{
pub fn new(
input: usize,
output: usize,
n: usize,
select_layer_builder: impl Fn(usize, usize) -> S,
layer_builder: impl Fn(usize, usize, usize) -> L,
) -> Self {
Self {
output_size: output,
select_layer: select_layer_builder(input, n),
layers: (0..n).map(|i| layer_builder(i, input, output)).collect(),
}
}
pub fn _call(&self, x: Computed, train: bool) -> (Computed, Computed) {
let select = self.select_layer.call(x.clone(), train);
let x = as_2d(&x);
let softmax = nn::activations::softmax(&select);
let mut ys = vec![];
for i in 0..x.shape()[0] {
let mut select = (&*softmax)
.slice(s![i, ..].to_owned())
.into_iter()
.enumerate()
.collect::<Vec<_>>();
select.sort_by(|(_, a), (_, b)| b.partial_cmp(a).unwrap());
select.truncate(5);
let mut lys = Vec::new();
for (j, _) in &select {
let layer = &self.layers[*j];
let ly = layer.call(Computed::new(x.slice(s![i..=i, ..]).into_ndarray()), train);
lys.push(ly * softmax.slice(s![i, *j]));
}
let lys = multi_add(&lys);
ys.push(lys);
}
let y = concat(&ys, 1);
// reshape to original shape
let y = y.reshape(
x.shape()
.iter()
.take(x.ndim() - 1)
.chain([self.output_size].iter())
.copied()
.collect::<Vec<_>>(),
);
(y, softmax)
}
}
impl<S: Layer<Input = Computed, Output = Computed>, L: Layer<Input = Computed, Output = Computed>> Layer
for SelectNet<S, L>
{
type Input = Computed;
type Output = Computed;
fn call(&self, input: Self::Input, train: bool) -> Self::Output {
self._call(input, train).0
}
fn all_params(&self) -> Vec<Param> {
self.select_layer
.all_params()
.into_iter()
.chain(self.layers.iter().flat_map(|l| l.all_params()))
.collect()
}
}
#[test]
fn test() {
use initializers::Initializer;
use ndarray::prelude::*;
use ndarray_rand::rand_distr::Uniform;
use nn::Linear;
let init = initializers::InitializerWithOptimizer::new(
Uniform::new(-0.01, 0.01),
optimizers::Adam::new(),
);
let select_net = SelectNet::new(
2,
3,
10,
|i, o| {
Linear::new(
i,
o,
init.scope("select_net_select_w"),
Some(init.scope("select_net_select_b")),
)
},
|n, i, o| {
Linear::new(
i,
o,
init.scope(format!("select_net_layer_w_{}", n)),
Some(init.scope(format!("select_net_layer_b_{}", n))),
)
},
);
let x = backprop(array![[0.1, 0.2], [0.0, 0.0], [0.0, 100.0]].into_ndarray());
let y = select_net._call(x.clone(), true);
dbg!(&*y.0);
// dbg!(&*y[1]);
let t = array![[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
.into_ndarray()
.into();
let loss = losses::naive_mean_squared_error(y.0.clone(), t);
dbg!(loss[[]]);
// export_dot::export_dot(&[loss.clone()], &format!("select_net.dot")).unwrap();
optimize(&loss);
let y2 = select_net._call(x.clone(), true);
assert_ne!(&*y.0, &*y2.0);
}
| 28.589928 | 104 | 0.491696 |
e6a44c57f1b6581a8cc810ae559160ef20401b4f | 4,120 | // 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 support the env! extension. Eventually this
* should all get sucked into either the compiler syntax extension plugin
* interface.
*/
use ast;
use codemap::Span;
use ext::base::*;
use ext::base;
use ext::build::AstBuilder;
use parse::token;
use std::os;
pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
-> Box<base::MacResult+'cx> {
let var = match get_single_str_from_tts(cx, sp, tts, "option_env!") {
None => return DummyResult::expr(sp),
Some(v) => v
};
let e = match os::getenv(var.as_slice()) {
None => {
cx.expr_path(cx.path_all(sp,
true,
vec!(cx.ident_of("std"),
cx.ident_of("option"),
cx.ident_of("Option"),
cx.ident_of("None")),
Vec::new(),
vec!(cx.ty_rptr(sp,
cx.ty_ident(sp,
cx.ident_of("str")),
Some(cx.lifetime(sp,
cx.ident_of(
"'static").name)),
ast::MutImmutable))))
}
Some(s) => {
cx.expr_call_global(sp,
vec!(cx.ident_of("std"),
cx.ident_of("option"),
cx.ident_of("Option"),
cx.ident_of("Some")),
vec!(cx.expr_str(sp,
token::intern_and_get_ident(
s.as_slice()))))
}
};
MacExpr::new(e)
}
pub fn expand_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
-> Box<base::MacResult+'cx> {
let mut exprs = match get_exprs_from_tts(cx, sp, tts) {
Some(ref exprs) if exprs.len() == 0 => {
cx.span_err(sp, "env! takes 1 or 2 arguments");
return DummyResult::expr(sp);
}
None => return DummyResult::expr(sp),
Some(exprs) => exprs.into_iter()
};
let var = match expr_to_string(cx,
exprs.next().unwrap(),
"expected string literal") {
None => return DummyResult::expr(sp),
Some((v, _style)) => v
};
let msg = match exprs.next() {
None => {
token::intern_and_get_ident(format!("environment variable `{}` \
not defined",
var).as_slice())
}
Some(second) => {
match expr_to_string(cx, second, "expected string literal") {
None => return DummyResult::expr(sp),
Some((s, _style)) => s
}
}
};
match exprs.next() {
None => {}
Some(_) => {
cx.span_err(sp, "env! takes 1 or 2 arguments");
return DummyResult::expr(sp);
}
}
let e = match os::getenv(var.get()) {
None => {
cx.span_err(sp, msg.get());
cx.expr_uint(sp, 0)
}
Some(s) => cx.expr_str(sp, token::intern_and_get_ident(s.as_slice()))
};
MacExpr::new(e)
}
| 36.785714 | 85 | 0.442718 |
d66b2a5cf84a651495d55be6ba7baef8ba758a77 | 14,335 | use rexpect::errors::Error;
use rexpect::spawn_stream;
use serialport::prelude::*;
use serialport::SerialPortSettings;
use std::env;
use std::fs::OpenOptions;
use std::process::{Command, Stdio};
use std::time::Duration;
use std::{thread, time};
fn earlgrey_cw310_flash(
app_name: &str,
) -> Result<rexpect::session::StreamSession<std::boxed::Box<dyn serialport::SerialPort>>, Error> {
let s = SerialPortSettings {
baud_rate: 115200,
data_bits: DataBits::Eight,
flow_control: FlowControl::None,
parity: Parity::None,
stop_bits: StopBits::One,
timeout: Duration::from_millis(1000),
};
// Open the first serialport available.
let port_name = &serialport::available_ports().expect("No serial port")[1].port_name;
println!("Connecting to OpenTitan port: {:?}", port_name);
let port = serialport::open_with_settings(port_name, &s).expect("Failed to open serial port");
// Clone the port
let port_clone = port.try_clone().expect("Failed to clone");
// Create the Rexpect instance
let mut p = spawn_stream(port, port_clone, Some(2000));
// Flash the Tock kernel and app
let mut build = Command::new("make")
.arg("-C")
.arg("../../boards/opentitan/earlgrey-cw310")
.arg(format!(
"OPENTITAN_TREE={}",
env::var("OPENTITAN_TREE").unwrap()
))
.arg(format!("APP={}", app_name))
.arg("flash-app")
.stdout(Stdio::null())
.spawn()
.expect("failed to spawn build");
assert!(build.wait().unwrap().success());
// Make sure the image is flashed
p.exp_string("Processing frame #13, expecting #13")?;
p.exp_string("Processing frame #67, expecting #67")?;
p.exp_string("Boot ROM initialisation has completed, jump into flash")?;
Ok(p)
}
fn earlgrey_cw310_c_hello() -> Result<(), Error> {
let app = format!(
"{}/{}",
env::var("LIBTOCK_C_TREE").unwrap(),
"examples/c_hello/build/rv32imc/rv32imc.0x20030080.0x10005000.tbf"
);
let mut p = earlgrey_cw310_flash(&app).unwrap();
p.exp_string("Hello World!")?;
Ok(())
}
fn earlgrey_cw310_blink() -> Result<(), Error> {
let app = format!(
"{}/{}",
env::var("LIBTOCK_C_TREE").unwrap(),
"examples/blink/build/rv32imc/rv32imc.0x20030080.0x10005000.tbf"
);
let _p = earlgrey_cw310_flash(&app).unwrap();
println!("Make sure the LEDs are blinking");
let timeout = time::Duration::from_secs(10);
thread::sleep(timeout);
Ok(())
}
fn earlgrey_cw310_c_hello_and_printf_long() -> Result<(), Error> {
let app = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open("app")
.unwrap();
let mut build = Command::new("cat")
.arg(format!(
"{}/{}",
env::var("LIBTOCK_C_TREE").unwrap(),
"examples/c_hello/build/rv32imc/rv32imc.0x20030080.0x10005000.tbf"
))
.stdout(app)
.spawn()
.expect("failed to spawn build");
assert!(build.wait().unwrap().success());
let app = OpenOptions::new()
.append(true)
.create(false)
.open("app")
.unwrap();
let mut build = Command::new("cat")
.arg(format!(
"{}/{}",
env::var("LIBTOCK_C_TREE").unwrap(),
"examples/tests/printf_long/build/rv32imc/rv32imc.0x20030880.0x10008000.tbf"
))
.stdout(app)
.spawn()
.expect("failed to spawn build");
assert!(build.wait().unwrap().success());
let mut p = earlgrey_cw310_flash("../../../tools/board-runner/app").unwrap();
p.exp_string("Hello World!")?;
p.exp_string("Hi welcome to Tock. This test makes sure that a greater than 64 byte message can be printed.")?;
p.exp_string("And a short message.")?;
Ok(())
}
fn earlgrey_cw310_recv_short_and_recv_long() -> Result<(), Error> {
let app = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open("app")
.unwrap();
let mut build = Command::new("cat")
.arg(format!(
"{}/{}",
env::var("LIBTOCK_C_TREE").unwrap(),
"examples/tests/console_recv_short/build/rv32imc/rv32imc.0x20030080.0x10005000.tbf"
))
.stdout(app)
.spawn()
.expect("failed to spawn build");
assert!(build.wait().unwrap().success());
let app = OpenOptions::new()
.append(true)
.create(false)
.open("app")
.unwrap();
let mut build = Command::new("cat")
.arg(format!(
"{}/{}",
env::var("LIBTOCK_C_TREE").unwrap(),
"examples/tests/console_recv_long/build/rv32imc/rv32imc.0x20034080.0x10008000.tbf"
))
.stdout(app)
.spawn()
.expect("failed to spawn build");
assert!(build.wait().unwrap().success());
let mut p = earlgrey_cw310_flash("../../../tools/board-runner/app").unwrap();
p.exp_string("Error doing UART receive: -2")?;
Ok(())
}
fn earlgrey_cw310_blink_and_c_hello_and_buttons() -> Result<(), Error> {
let app = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open("app")
.unwrap();
let mut build = Command::new("cat")
.arg(format!(
"{}/{}",
env::var("LIBTOCK_C_TREE").unwrap(),
"examples/blink/build/rv32imc/rv32imc.0x20030080.0x10005000.tbf"
))
.stdout(app)
.spawn()
.expect("failed to spawn build");
assert!(build.wait().unwrap().success());
let app = OpenOptions::new()
.append(true)
.create(false)
.open("app")
.unwrap();
let mut build = Command::new("cat")
.arg(format!(
"{}/{}",
env::var("LIBTOCK_C_TREE").unwrap(),
"examples/c_hello/build/rv32imc/rv32imc.0x20030880.0x10008000.tbf"
))
.stdout(app)
.spawn()
.expect("failed to spawn build");
assert!(build.wait().unwrap().success());
let app = OpenOptions::new()
.append(true)
.create(false)
.open("app")
.unwrap();
let mut build = Command::new("cat")
.arg(format!(
"{}/{}",
env::var("LIBTOCK_C_TREE").unwrap(),
"examples/buttons/build/rv32imc/rv32imc.0x20034080.0x10008000.tbf"
))
.stdout(app)
.spawn()
.expect("failed to spawn build");
assert!(build.wait().unwrap().success());
let mut p = earlgrey_cw310_flash("../../../tools/board-runner/app").unwrap();
p.exp_string("Hello World!")?;
println!("Make sure the LEDs are flashing");
let timeout = time::Duration::from_secs(10);
thread::sleep(timeout);
Ok(())
}
fn earlgrey_cw310_console_recv_short() -> Result<(), Error> {
let app = format!(
"{}/{}",
env::var("LIBTOCK_C_TREE").unwrap(),
"examples/tests/console_recv_short/build/rv32imc/rv32imc.0x20030080.0x10005000.tbf"
);
let mut p = earlgrey_cw310_flash(&app).unwrap();
p.send_line("Short recv")?;
// Check the message
p.exp_string("console_recv_short: Short recv")?;
Ok(())
}
fn earlgrey_cw310_console_timeout() -> Result<(), Error> {
let app = format!(
"{}/{}",
env::var("LIBTOCK_C_TREE").unwrap(),
"examples/tests/console_timeout/build/rv32imc/rv32imc.0x20030080.0x10005000.tbf"
);
let mut p = earlgrey_cw310_flash(&app).unwrap();
// Wait 5 seconds
let timeout = time::Duration::from_secs(5);
thread::sleep(timeout);
// Send a 60 charecter message
p.send_line("This is a test message that we are sending. Look at us go...")?;
// Check the message
p.exp_string("Userspace call to read console returned: This is a test message that we are sending. Look at us go...")?;
Ok(())
}
#[allow(dead_code)]
fn earlgrey_cw310_malloc_test1() -> Result<(), Error> {
let app = format!(
"{}/{}",
env::var("LIBTOCK_C_TREE").unwrap(),
"examples/tests/malloc_test01/build/rv32imc/rv32imc.0x20030080.0x10005000.tbf"
);
let mut p = earlgrey_cw310_flash(&app).unwrap();
p.exp_string("malloc01: success")?;
Ok(())
}
#[allow(dead_code)]
fn earlgrey_cw310_stack_size_test1() -> Result<(), Error> {
let app = format!(
"{}/{}",
env::var("LIBTOCK_C_TREE").unwrap(),
"examples/tests/stack_size_test01/build/rv32imc/rv32imc.0x20030080.0x10005000.tbf"
);
let mut p = earlgrey_cw310_flash(&app).unwrap();
p.exp_string("Stack Test App")?;
p.exp_string("Current stack pointer: 0x100")?;
Ok(())
}
#[allow(dead_code)]
fn earlgrey_cw310_stack_size_test2() -> Result<(), Error> {
let app = format!(
"{}/{}",
env::var("LIBTOCK_C_TREE").unwrap(),
"examples/tests/stack_size_test02/build/rv32imc/rv32imc.0x20030080.0x10005000.tbf"
);
let mut p = earlgrey_cw310_flash(&app).unwrap();
p.exp_string("Stack Test App")?;
p.exp_string("Current stack pointer: 0x100")?;
Ok(())
}
fn earlgrey_cw310_mpu_stack_growth() -> Result<(), Error> {
let app = format!(
"{}/{}",
env::var("LIBTOCK_C_TREE").unwrap(),
"examples/tests/mpu_stack_growth/build/rv32imc/rv32imc.0x20030080.0x10005000.tbf"
);
let mut p = earlgrey_cw310_flash(&app).unwrap();
p.exp_string("This test should recursively add stack frames until exceeding")?;
p.exp_string("panicked at 'Process mpu_stack_growth had a fault'")?;
p.exp_string("Store/AMO access fault")?;
Ok(())
}
#[allow(dead_code)]
fn earlgrey_cw310_mpu_walk_region() -> Result<(), Error> {
let app = format!(
"{}/{}",
env::var("LIBTOCK_C_TREE").unwrap(),
"examples/tests/mpu_walk_region/build/rv32imc/rv32imc.0x20030080.0x10005000.tbf"
);
let mut p = earlgrey_cw310_flash(&app).unwrap();
p.exp_string("MPU Walk Regions")?;
p.exp_string("Walking flash")?;
p.exp_string("Will overrun")?;
p.exp_string("0x2003ba00")?;
p.exp_string("panicked at 'Process mpu_walk_region had a fault'")?;
Ok(())
}
fn earlgrey_cw310_multi_alarm_test() -> Result<(), Error> {
let app = format!(
"{}/{}",
env::var("LIBTOCK_C_TREE").unwrap(),
"examples/tests/multi_alarm_test/build/rv32imc/rv32imc.0x20030080.0x10005000.tbf"
);
let _p = earlgrey_cw310_flash(&app).unwrap();
println!("Make sure the LEDs are blinking");
let timeout = time::Duration::from_secs(10);
thread::sleep(timeout);
Ok(())
}
fn earlgrey_cw310_sha_hmac_test() -> Result<(), Error> {
let app = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open("app")
.unwrap();
let mut build = Command::new("cat")
.arg(format!(
"{}/{}",
env::var("LIBTOCK_C_TREE").unwrap(),
"examples/tests/hmac/build/rv32imc/rv32imc.0x20030080.0x10005000.tbf"
))
.stdout(app)
.spawn()
.expect("failed to spawn build");
assert!(build.wait().unwrap().success());
let app = OpenOptions::new()
.append(true)
.create(false)
.open("app")
.unwrap();
let mut build = Command::new("cat")
.arg(format!(
"{}/{}",
env::var("LIBTOCK_C_TREE").unwrap(),
"examples/tests/sha/build/rv32imc/rv32imc.0x20034080.0x10008000.tbf"
))
.stdout(app)
.spawn()
.expect("failed to spawn build");
assert!(build.wait().unwrap().success());
let mut p = earlgrey_cw310_flash("../../../tools/board-runner/app").unwrap();
p.exp_string("HMAC Example Test")?;
p.exp_string("SHA Example Test")?;
p.exp_string("Running HMAC...")?;
p.exp_string("0: 0xeb")?;
p.exp_string("10: 0xde")?;
p.exp_string("Running SHA...")?;
p.exp_string("0: 0x68")?;
p.exp_string("10: 0x8f")?;
p.exp_string("31: 0x15")?;
let timeout = time::Duration::from_secs(10);
thread::sleep(timeout);
Ok(())
}
pub fn all_earlgrey_cw310_tests() {
println!("Tock board-runner starting...");
println!();
println!("Running earlgrey_cw310 tests...");
earlgrey_cw310_c_hello()
.unwrap_or_else(|e| panic!("earlgrey_cw310_c_hello job failed with {}", e));
earlgrey_cw310_blink().unwrap_or_else(|e| panic!("earlgrey_cw310_blink job failed with {}", e));
earlgrey_cw310_c_hello_and_printf_long().unwrap_or_else(|e| {
panic!(
"earlgrey_cw310_c_hello_and_printf_long job failed with {}",
e
)
});
earlgrey_cw310_recv_short_and_recv_long().unwrap_or_else(|e| {
panic!(
"earlgrey_cw310_recv_short_and_recv_long job failed with {}",
e
)
});
earlgrey_cw310_blink_and_c_hello_and_buttons().unwrap_or_else(|e| {
panic!(
"earlgrey_cw310_blink_and_c_hello_and_buttons job failed with {}",
e
)
});
earlgrey_cw310_console_recv_short()
.unwrap_or_else(|e| panic!("earlgrey_cw310_console_recv_short job failed with {}", e));
earlgrey_cw310_console_timeout()
.unwrap_or_else(|e| panic!("earlgrey_cw310_console_timeout job failed with {}", e));
earlgrey_cw310_malloc_test1()
.unwrap_or_else(|e| panic!("earlgrey_cw310_malloc_test1 job failed with {}", e));
earlgrey_cw310_stack_size_test1()
.unwrap_or_else(|e| panic!("earlgrey_cw310_stack_size_test1 job failed with {}", e));
earlgrey_cw310_stack_size_test2()
.unwrap_or_else(|e| panic!("earlgrey_cw310_stack_size_test2 job failed with {}", e));
earlgrey_cw310_mpu_stack_growth()
.unwrap_or_else(|e| panic!("earlgrey_cw310_mpu_stack_growth job failed with {}", e));
// earlgrey_cw310_mpu_walk_region()
// .unwrap_or_else(|e| panic!("earlgrey_cw310_mpu_walk_region job failed with {}", e));
earlgrey_cw310_multi_alarm_test()
.unwrap_or_else(|e| panic!("earlgrey_cw310_multi_alarm_test job failed with {}", e));
earlgrey_cw310_sha_hmac_test()
.unwrap_or_else(|e| panic!("earlgrey_cw310_sha_hmac_test job failed with {}", e));
println!("earlgrey_cw310 SUCCESS.");
}
| 29.864583 | 123 | 0.600279 |
ebdcff495a4cacd19a19fcf47b80a06dd30ae6fb | 529 | //! IOx Query Server Implementation.
#![deny(rustdoc::broken_intra_doc_links, rust_2018_idioms)]
#![warn(
missing_copy_implementations,
missing_docs,
clippy::explicit_iter_loop,
clippy::future_not_send,
clippy::use_self,
clippy::clone_on_ref_ptr
)]
#![allow(dead_code)]
pub use client_util::connection;
mod cache;
mod cache_system;
mod chunk;
pub mod database;
/// Flight client to the ingester to request in-memory data.
pub mod flight;
pub mod handler;
pub mod namespace;
mod poison;
pub mod server;
| 20.346154 | 60 | 0.746692 |
6a9ca910570a4f77d439db5312b12d5fd2b7526d | 1,008 | //! Link-time-optimization
/// Dummy type for pointers to the LTO object
#[allow(non_camel_case_types)]
pub type llvm_lto_t = *mut ::libc::c_void;
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum llvm_lto_status_t {
LLVM_LTO_UNKNOWN = 0,
LLVM_LTO_OPT_SUCCESS = 1,
LLVM_LTO_READ_SUCCESS = 2,
LLVM_LTO_READ_FAILURE = 3,
LLVM_LTO_WRITE_FAILURE = 4,
LLVM_LTO_NO_TARGET = 5,
LLVM_LTO_NO_WORK = 6,
LLVM_LTO_MODULE_MERGE_FAILURE = 7,
LLVM_LTO_ASM_FAILURE = 8,
LLVM_LTO_NULL_OBJECT = 9,
}
extern "C" {
pub fn llvm_create_optimizer() -> llvm_lto_t;
pub fn llvm_destroy_optimizer(lto: llvm_lto_t);
pub fn llvm_read_object_file(lto: llvm_lto_t,
input_filename: *const ::libc::c_char)
-> llvm_lto_status_t;
pub fn llvm_optimize_modules(lto: llvm_lto_t,
output_filename: *const ::libc::c_char)
-> llvm_lto_status_t;
}
| 31.5 | 72 | 0.628968 |
223554e3e9ad93571cb31c4ccf3d4ff315e95626 | 25,237 | use crate::{
crypto::{AuthorityPen, AuthorityVerifier, KeyBox},
data_io::{reduce_header_to_num, AlephData, DataProvider, DataStore, FinalizationHandler},
default_aleph_config,
finalization::{AlephFinalizer, BlockFinalizer},
first_block_of_session,
justification::{
AlephJustification, JustificationHandler, JustificationHandlerConfig,
JustificationNotification, JustificationRequestDelay, SessionInfo, SessionInfoProvider,
Verifier,
},
last_block_of_session,
network::{
split, AlephNetworkData, ConnectionIO, ConnectionManager, ConnectionManagerConfig,
RequestBlocks, RmcNetworkData, Service as NetworkService, SessionManager, SessionNetwork,
Split, IO as NetworkIO,
},
session_id_from_block_num, AuthorityId, Metrics, MillisecsPerBlock, NodeIndex, SessionId,
SessionMap, SessionPeriod, UnitCreationDelay,
};
use sp_keystore::CryptoStore;
use aleph_bft::{DelayConfig, SpawnHandle};
use aleph_primitives::{AlephSessionApi, KEY_TYPE};
use futures_timer::Delay;
use futures::channel::mpsc;
use log::{debug, error, info, trace, warn};
use codec::Encode;
use parking_lot::Mutex;
use sc_client_api::{Backend, HeaderBackend};
use sc_network::ExHashT;
use sp_api::{BlockId, NumberFor};
use sp_consensus::SelectChain;
use sp_runtime::{
traits::{Block, Header},
SaturatedConversion,
};
use std::{
cmp::min,
collections::{HashMap, HashSet},
default::Default,
marker::PhantomData,
sync::Arc,
time::{Duration, Instant},
};
mod task;
use task::{Handle, Task};
mod aggregator;
mod authority;
mod data_store;
mod member;
mod refresher;
use authority::{
SubtaskCommon as AuthoritySubtaskCommon, Subtasks as AuthoritySubtasks, Task as AuthorityTask,
};
type SplitData<B> = Split<AlephNetworkData<B>, RmcNetworkData<B>>;
pub struct AlephParams<B: Block, H: ExHashT, C, SC> {
pub config: crate::AlephConfig<B, H, C, SC>,
}
struct JustificationRequestDelayImpl {
last_request_time: Instant,
last_finalization_time: Instant,
delay: Duration,
}
impl JustificationRequestDelayImpl {
fn new(session_period: &SessionPeriod, millisecs_per_block: &MillisecsPerBlock) -> Self {
Self {
last_request_time: Instant::now(),
last_finalization_time: Instant::now(),
delay: Duration::from_millis(min(
millisecs_per_block.0 * 2,
millisecs_per_block.0 * session_period.0 as u64 / 10,
)),
}
}
}
impl JustificationRequestDelay for JustificationRequestDelayImpl {
fn can_request_now(&self) -> bool {
let now = Instant::now();
now - self.last_finalization_time > self.delay
&& now - self.last_request_time > 2 * self.delay
}
fn on_block_finalized(&mut self) {
self.last_finalization_time = Instant::now();
}
fn on_request_sent(&mut self) {
self.last_request_time = Instant::now();
}
}
impl<B: Block> Verifier<B> for AuthorityVerifier {
fn verify(&self, justification: &AlephJustification, hash: B::Hash) -> bool {
if !self.is_complete(&hash.encode()[..], &justification.signature) {
warn!(target: "afa", "Bad justification for block hash #{:?} {:?}", hash, justification);
return false;
}
true
}
}
fn get_session_info_provider<B: Block>(
session_authorities: Arc<Mutex<HashMap<SessionId, Vec<AuthorityId>>>>,
session_period: SessionPeriod,
) -> impl SessionInfoProvider<B, AuthorityVerifier> {
move |block_num| {
let current_session = session_id_from_block_num::<B>(block_num, session_period);
let last_block_height = last_block_of_session::<B>(current_session, session_period);
let verifier = session_authorities
.lock()
.get(¤t_session)
.map(|sa: &Vec<AuthorityId>| AuthorityVerifier::new(sa.to_vec()));
SessionInfo {
current_session,
last_block_height,
verifier,
}
}
}
pub async fn run_consensus_party<B, H, C, BE, SC>(aleph_params: AlephParams<B, H, C, SC>)
where
B: Block,
H: ExHashT,
C: crate::ClientForAleph<B, BE> + Send + Sync + 'static,
C::Api: aleph_primitives::AlephSessionApi<B>,
BE: Backend<B> + 'static,
SC: SelectChain<B> + 'static,
{
let AlephParams {
config:
crate::AlephConfig {
network,
client,
select_chain,
spawn_handle,
keystore,
justification_rx,
metrics,
session_period,
millisecs_per_block,
unit_creation_delay,
..
},
} = aleph_params;
let session_authorities = Arc::new(Mutex::new(HashMap::new()));
let block_requester = network.clone();
let handler = JustificationHandler::new(
get_session_info_provider(session_authorities.clone(), session_period),
block_requester.clone(),
client.clone(),
AlephFinalizer::new(client.clone()),
JustificationHandlerConfig {
justification_request_delay: JustificationRequestDelayImpl::new(
&session_period,
&millisecs_per_block,
),
metrics: metrics.clone(),
verifier_timeout: Duration::from_millis(500),
notification_timeout: Duration::from_millis(1000),
},
);
let authority_justification_tx =
run_justification_handler(handler, &spawn_handle.clone().into(), justification_rx);
// Prepare and start the network
let (commands_for_network, commands_from_io) = mpsc::unbounded();
let (messages_for_network, messages_from_user) = mpsc::unbounded();
let (commands_for_service, commands_from_user) = mpsc::unbounded();
let (messages_for_service, commands_from_manager) = mpsc::unbounded();
let (messages_for_user, messages_from_network) = mpsc::unbounded();
let connection_io = ConnectionIO::new(
commands_for_network,
messages_for_network,
commands_from_user,
commands_from_manager,
messages_from_network,
);
let connection_manager = ConnectionManager::new(
network.clone(),
ConnectionManagerConfig::with_session_period(&session_period, &millisecs_per_block),
);
let session_manager = SessionManager::new(commands_for_service, messages_for_service);
let network = NetworkService::new(
network.clone(),
spawn_handle.clone(),
NetworkIO::new(messages_from_user, messages_for_user, commands_from_io),
);
let network_manager_task = async move {
connection_io
.run(connection_manager)
.await
.expect("Failed to run new network manager")
};
spawn_handle.spawn("aleph/network_manager", None, network_manager_task);
let network_task = async move { network.run().await };
spawn_handle.spawn("aleph/network", None, network_task);
debug!(target: "afa", "Consensus network has started.");
let party = ConsensusParty {
session_manager,
client,
keystore,
select_chain,
block_requester,
metrics,
authority_justification_tx,
session_authorities,
session_period,
spawn_handle: spawn_handle.into(),
phantom: PhantomData,
unit_creation_delay,
};
debug!(target: "afa", "Consensus party has started.");
party.run().await;
error!(target: "afa", "Consensus party has finished unexpectedly.");
}
async fn get_node_index(
authorities: &[AuthorityId],
keystore: Arc<dyn CryptoStore>,
) -> Option<NodeIndex> {
let our_consensus_keys: HashSet<_> =
keystore.keys(KEY_TYPE).await.unwrap().into_iter().collect();
trace!(target: "afa", "Found {:?} consensus keys in our local keystore {:?}", our_consensus_keys.len(), our_consensus_keys);
authorities
.iter()
.position(|pkey| our_consensus_keys.contains(&pkey.into()))
.map(|id| id.into())
}
fn run_justification_handler<B, V, RB, C, D, SI, F>(
handler: JustificationHandler<B, V, RB, C, D, SI, F>,
spawn_handle: &crate::SpawnHandle,
import_justification_rx: mpsc::UnboundedReceiver<JustificationNotification<B>>,
) -> mpsc::UnboundedSender<JustificationNotification<B>>
where
C: HeaderBackend<B> + Send + Sync + 'static,
B: Block,
RB: RequestBlocks<B> + 'static,
V: Verifier<B> + Send + 'static,
D: JustificationRequestDelay + Send + 'static,
SI: SessionInfoProvider<B, V> + Send + 'static,
F: BlockFinalizer<B> + Send + 'static,
{
let (authority_justification_tx, authority_justification_rx) = mpsc::unbounded();
debug!(target: "afa", "JustificationHandler started");
spawn_handle.spawn("aleph/justification_handler", async move {
handler
.run(authority_justification_rx, import_justification_rx)
.await;
});
authority_justification_tx
}
struct ConsensusParty<B, C, BE, SC, RB>
where
B: Block,
C: crate::ClientForAleph<B, BE> + Send + Sync + 'static,
C::Api: aleph_primitives::AlephSessionApi<B>,
BE: Backend<B> + 'static,
SC: SelectChain<B> + 'static,
RB: RequestBlocks<B> + 'static,
{
session_manager: SessionManager<SplitData<B>>,
session_authorities: Arc<Mutex<SessionMap>>,
session_period: SessionPeriod,
spawn_handle: crate::SpawnHandle,
client: Arc<C>,
select_chain: SC,
keystore: Arc<dyn CryptoStore>,
block_requester: RB,
phantom: PhantomData<BE>,
metrics: Option<Metrics<<B::Header as Header>::Hash>>,
authority_justification_tx: mpsc::UnboundedSender<JustificationNotification<B>>,
unit_creation_delay: UnitCreationDelay,
}
const SESSION_STATUS_CHECK_PERIOD: Duration = Duration::from_millis(1000);
const NEXT_SESSION_NETWORK_START_ATTEMPT_PERIOD: Duration = Duration::from_secs(30);
fn get_authorities_for_session<B, C>(
runtime_api: sp_api::ApiRef<C::Api>,
session_id: SessionId,
first_block: NumberFor<B>,
) -> Vec<AuthorityId>
where
B: Block,
C: sp_api::ProvideRuntimeApi<B>,
C::Api: aleph_primitives::AlephSessionApi<B>,
{
if session_id == SessionId(0) {
runtime_api
.authorities(&BlockId::Number(<NumberFor<B>>::saturated_from(0u32)))
.expect("Authorities for the session 0 must be available from the beginning")
} else {
runtime_api
.next_session_authorities(&BlockId::Number(first_block))
.unwrap_or_else(|_| {
panic!(
"We didn't get the authorities for the session {:?}",
session_id
)
})
.expect(
"Authorities for next session must be available at first block of current session",
)
}
}
impl<B, C, BE, SC, RB> ConsensusParty<B, C, BE, SC, RB>
where
B: Block,
C: crate::ClientForAleph<B, BE> + Send + Sync + 'static,
C::Api: aleph_primitives::AlephSessionApi<B>,
BE: Backend<B> + 'static,
SC: SelectChain<B> + 'static,
RB: RequestBlocks<B> + 'static,
{
async fn spawn_authority_subtasks(
&self,
node_id: NodeIndex,
multikeychain: KeyBox,
data_network: SessionNetwork<SplitData<B>>,
session_id: SessionId,
authorities: Vec<AuthorityId>,
exit_rx: futures::channel::oneshot::Receiver<()>,
) -> AuthoritySubtasks {
debug!(target: "afa", "Authority task {:?}", session_id);
let last_block = last_block_of_session::<B>(session_id, self.session_period);
let (ordered_units_for_aggregator, ordered_units_from_aleph) = mpsc::unbounded();
let consensus_config = create_aleph_config(
authorities.len(),
node_id,
session_id,
self.unit_creation_delay,
);
let best_header = self
.select_chain
.best_chain()
.await
.expect("No best chain.");
let reduced_header = reduce_header_to_num(self.client.clone(), best_header, last_block);
let proposed_block = Arc::new(Mutex::new(AlephData::new(
reduced_header.hash(),
*reduced_header.number(),
)));
let data_provider = DataProvider::<B> {
proposed_block: proposed_block.clone(),
metrics: self.metrics.clone(),
};
let finalization_handler = FinalizationHandler::<B> {
ordered_units_tx: ordered_units_for_aggregator,
};
let subtask_common = AuthoritySubtaskCommon {
spawn_handle: self.spawn_handle.clone(),
session_id: session_id.0,
};
let aggregator_io = aggregator::IO {
ordered_units_from_aleph,
justifications_for_chain: self.authority_justification_tx.clone(),
};
let (unfiltered_aleph_network, rmc_network) = split(data_network);
let (data_store, aleph_network) = DataStore::new(
self.client.clone(),
self.block_requester.clone(),
Default::default(),
unfiltered_aleph_network,
);
AuthoritySubtasks::new(
exit_rx,
member::task(
subtask_common.clone(),
multikeychain.clone(),
consensus_config,
aleph_network.into(),
data_provider,
finalization_handler,
),
aggregator::task(
subtask_common.clone(),
self.client.clone(),
aggregator_io,
last_block,
self.metrics.clone(),
multikeychain.clone(),
rmc_network,
),
refresher::task(
subtask_common.clone(),
self.select_chain.clone(),
self.client.clone(),
proposed_block,
last_block,
),
data_store::task(subtask_common, data_store),
)
}
async fn spawn_authority_task(
&self,
session_id: SessionId,
node_id: NodeIndex,
authorities: Vec<AuthorityId>,
) -> AuthorityTask {
let authority_verifier = AuthorityVerifier::new(authorities.clone());
let authority_pen =
AuthorityPen::new(authorities[node_id.0].clone(), self.keystore.clone())
.await
.expect("The keys should sign successfully");
let keybox = KeyBox::new(node_id, authority_verifier.clone(), authority_pen.clone());
let data_network = self
.session_manager
.start_validator_session(session_id, authority_verifier, node_id, authority_pen)
.await
.expect("Failed to start validator session!");
let (exit, exit_rx) = futures::channel::oneshot::channel();
let authority_subtasks = self
.spawn_authority_subtasks(
node_id,
keybox,
data_network,
session_id,
authorities,
exit_rx,
)
.await;
AuthorityTask::new(
self.spawn_handle
.spawn_essential("aleph/session_authority", async move {
if authority_subtasks.failed().await {
warn!(target: "aleph-party", "Authority subtasks failed.");
}
}),
node_id,
exit,
)
}
/// Returns authorities for a given session or None if the first block of this session is
/// higher than the highest finalized block
fn updated_authorities_for_session(
&mut self,
session_id: SessionId,
) -> Option<Vec<AuthorityId>> {
let last_finalized_number = self.client.info().finalized_number;
let previous_session = match session_id {
SessionId(0) => SessionId(0),
SessionId(sid) => SessionId(sid - 1),
};
let first_block = first_block_of_session::<B>(previous_session, self.session_period);
if last_finalized_number < first_block {
return None;
}
Some(
self.session_authorities
.lock()
.entry(session_id)
.or_insert_with(|| {
get_authorities_for_session::<_, C>(
self.client.runtime_api(),
session_id,
first_block,
)
})
.clone(),
)
}
async fn run_session(&mut self, session_id: SessionId) {
let authorities = self
.updated_authorities_for_session(session_id)
.expect("We should know authorities for the session we are starting");
let last_block = last_block_of_session::<B>(session_id, self.session_period);
// Early skip attempt -- this will trigger during catching up (initial sync).
if self.client.info().best_number >= last_block {
// We need to give the JustificationHandler some time to pick up the keybox for the new session,
// validate justifications and finalize blocks. We wait 2000ms in total, checking every 200ms
// if the last block has been finalized.
for attempt in 0..10 {
// We don't wait before the first attempt.
if attempt != 0 {
Delay::new(Duration::from_millis(200)).await;
}
let last_finalized_number = self.client.info().finalized_number;
if last_finalized_number >= last_block {
debug!(target: "afa", "Skipping session {:?} early because block {:?} is already finalized", session_id, last_finalized_number);
return;
}
}
}
trace!(target: "afa", "Authorities for session {:?}: {:?}", session_id, authorities);
let mut maybe_authority_task = if let Some(node_id) =
get_node_index(&authorities, self.keystore.clone()).await
{
debug!(target: "afa", "Running session {:?} as authority id {:?}", session_id, node_id);
Some(
self.spawn_authority_task(session_id, node_id, authorities.clone())
.await,
)
} else {
debug!(target: "afa", "Running session {:?} as non-authority", session_id);
None
};
let mut check_session_status = Delay::new(SESSION_STATUS_CHECK_PERIOD);
let mut start_next_session_network =
Some(Delay::new(NEXT_SESSION_NETWORK_START_ATTEMPT_PERIOD));
loop {
tokio::select! {
_ = &mut check_session_status => {
let last_finalized_number = self.client.info().finalized_number;
if last_finalized_number >= last_block {
debug!(target: "aleph-party", "Terminating session {:?}", session_id);
break;
}
check_session_status = Delay::new(SESSION_STATUS_CHECK_PERIOD);
},
Some(_) = async {
match &mut start_next_session_network {
Some(start_next_session_network) => {
start_next_session_network.await;
Some(())
},
None => None,
}
} => {
let next_session_id = SessionId(session_id.0 + 1);
if let Some(next_session_authorities) =
self.updated_authorities_for_session(next_session_id)
{
let authority_verifier = AuthorityVerifier::new(next_session_authorities.clone());
match get_node_index(&authorities, self.keystore.clone()).await {
Some(node_id) => {
let authority_pen = AuthorityPen::new(
next_session_authorities[node_id.0].clone(),
self.keystore.clone(),
)
.await
.expect("The keys should sign successfully");
if let Err(e) = self
.session_manager
.early_start_validator_session(
next_session_id,
authority_verifier,
node_id,
authority_pen,
)
{
warn!(target: "aleph-party", "Failed to early start validator session{:?}:{:?}", next_session_id, e);
}
}
None => {
if let Err(e) = self
.session_manager
.start_nonvalidator_session(next_session_id, authority_verifier)
{
warn!(target: "aleph-party", "Failed to early start nonvalidator session{:?}:{:?}", next_session_id, e);
}
}
}
start_next_session_network = None;
} else {
start_next_session_network = Some(Delay::new(NEXT_SESSION_NETWORK_START_ATTEMPT_PERIOD));
}
},
Some(_) = async {
match maybe_authority_task.as_mut() {
Some(task) => Some(task.stopped().await),
None => None,
} } => {
warn!(target: "aleph-party", "Authority task ended prematurely, giving up for this session.");
maybe_authority_task = None;
},
}
}
if let Some(task) = maybe_authority_task {
debug!(target: "aleph-party", "Stopping the authority task.");
task.stop().await;
}
if let Err(e) = self.session_manager.stop_session(session_id) {
warn!(target: "aleph-party", "Session Manager failed to stop in session {:?}: {:?}", session_id, e)
}
}
fn prune_session_data(&self, prune_below: SessionId) {
// In this method we make sure that the amount of data we keep in RAM in finality-aleph
// does not grow with the size of the blockchain.
debug!(target: "afa", "Pruning session data below {:?}.", prune_below);
self.session_authorities
.lock()
.retain(|&s, _| s >= prune_below);
}
async fn run(mut self) {
let last_finalized_number = self.client.info().finalized_number;
let starting_session =
session_id_from_block_num::<B>(last_finalized_number, self.session_period);
for curr_id in starting_session.0.. {
info!(target: "afa", "Running session {:?}.", curr_id);
self.run_session(SessionId(curr_id)).await;
if curr_id >= 10 && curr_id % 10 == 0 {
self.prune_session_data(SessionId(curr_id - 10));
}
}
}
}
pub(crate) fn create_aleph_config(
n_members: usize,
node_id: NodeIndex,
session_id: SessionId,
unit_creation_delay: UnitCreationDelay,
) -> aleph_bft::Config {
let mut consensus_config = default_aleph_config(n_members.into(), node_id, session_id.0 as u64);
consensus_config.max_round = 7000;
let unit_creation_delay = Arc::new(move |t| {
if t == 0 {
Duration::from_millis(2000)
} else {
exponential_slowdown(t, unit_creation_delay.0 as f64, 5000, 1.005)
}
});
let unit_broadcast_delay = Arc::new(|t| exponential_slowdown(t, 4000., 0, 2.));
let delay_config = DelayConfig {
tick_interval: Duration::from_millis(100),
requests_interval: Duration::from_millis(3000),
unit_broadcast_delay,
unit_creation_delay,
};
consensus_config.delay_config = delay_config;
consensus_config
}
pub fn exponential_slowdown(
t: usize,
base_delay: f64,
start_exp_delay: usize,
exp_base: f64,
) -> Duration {
// This gives:
// base_delay, for t <= start_exp_delay,
// base_delay * exp_base^(t - start_exp_delay), for t > start_exp_delay.
let delay = if t < start_exp_delay {
base_delay
} else {
let power = t - start_exp_delay;
base_delay * exp_base.powf(power as f64)
};
let delay = delay.round() as u64;
// the above will make it u64::MAX if it exceeds u64
Duration::from_millis(delay)
}
// TODO: :(
#[cfg(test)]
mod tests {}
| 36.681686 | 148 | 0.582399 |
e546f7f5083b883a914317f6b1454d789d07c49c | 4,804 | // Copyright 2019 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::alloc::{vec, vec::Vec};
use core::any::{type_name, TypeId};
use core::ptr::NonNull;
use core::{fmt, mem};
use crate::archetype::TypeInfo;
use crate::Component;
/// A dynamically typed collection of components
pub trait DynamicBundle {
#[doc(hidden)]
fn with_ids<T>(&self, f: impl FnOnce(&[TypeId]) -> T) -> T;
#[doc(hidden)]
fn type_info(&self) -> Vec<TypeInfo>;
/// Allow a callback to move all components out of the bundle
///
/// Must invoke `f` only with a valid pointer, its type, and the pointee's size. A `false`
/// return value indicates that the value was not moved and should be dropped.
#[doc(hidden)]
unsafe fn put(self, f: impl FnMut(*mut u8, TypeId, usize) -> bool);
}
/// A statically typed collection of components
pub trait Bundle: DynamicBundle {
#[doc(hidden)]
fn with_static_ids<T>(f: impl FnOnce(&[TypeId]) -> T) -> T;
/// Construct `Self` by moving components out of pointers fetched by `f`
///
/// # Safety
///
/// `f` must produce pointers to the expected fields. The implementation must not read from any
/// pointers if any call to `f` returns `None`.
#[doc(hidden)]
unsafe fn get(
f: impl FnMut(TypeId, usize) -> Option<NonNull<u8>>,
) -> Result<Self, MissingComponent>
where
Self: Sized;
}
/// Error indicating that an entity did not have a required component
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct MissingComponent(&'static str);
impl MissingComponent {
/// Construct an error representing a missing `T`
pub fn new<T: Component>() -> Self {
Self(type_name::<T>())
}
}
impl fmt::Display for MissingComponent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "missing {} component", self.0)
}
}
#[cfg(feature = "std")]
impl std::error::Error for MissingComponent {}
macro_rules! tuple_impl {
($($name: ident),*) => {
impl<$($name: Component),*> DynamicBundle for ($($name,)*) {
fn with_ids<T>(&self, f: impl FnOnce(&[TypeId]) -> T) -> T {
Self::with_static_ids(f)
}
fn type_info(&self) -> Vec<TypeInfo> {
let mut xs = vec![$(TypeInfo::of::<$name>()),*];
xs.sort_unstable();
xs
}
#[allow(unused_variables, unused_mut)]
unsafe fn put(self, mut f: impl FnMut(*mut u8, TypeId, usize) -> bool) {
#[allow(non_snake_case)]
let ($(mut $name,)*) = self;
$(
if f(
(&mut $name as *mut $name).cast::<u8>(),
TypeId::of::<$name>(),
mem::size_of::<$name>()
) {
mem::forget($name)
}
)*
}
}
impl<$($name: Component),*> Bundle for ($($name,)*) {
fn with_static_ids<T>(f: impl FnOnce(&[TypeId]) -> T) -> T {
const N: usize = count!($($name),*);
let mut xs: [(usize, TypeId); N] = [$((mem::align_of::<$name>(), TypeId::of::<$name>())),*];
xs.sort_unstable_by(|x, y| x.0.cmp(&y.0).reverse().then(x.1.cmp(&y.1)));
let mut ids = [TypeId::of::<()>(); N];
for (slot, &(_, id)) in ids.iter_mut().zip(xs.iter()) {
*slot = id;
}
f(&ids)
}
#[allow(unused_variables, unused_mut)]
unsafe fn get(mut f: impl FnMut(TypeId, usize) -> Option<NonNull<u8>>) -> Result<Self, MissingComponent> {
#[allow(non_snake_case)]
let ($(mut $name,)*) = ($(
f(TypeId::of::<$name>(), mem::size_of::<$name>()).ok_or_else(MissingComponent::new::<$name>)?
.as_ptr()
.cast::<$name>(),)*
);
Ok(($($name.read(),)*))
}
}
}
}
macro_rules! count {
() => { 0 };
($x: ident $(, $rest: ident)*) => { 1 + count!($($rest),*) };
}
smaller_tuples_too!(tuple_impl, O, N, M, L, K, J, I, H, G, F, E, D, C, B, A);
| 35.323529 | 118 | 0.532681 |
89f980165a01d9fce456940e271b655471c3b645 | 7,836 | // SPDX-FileCopyrightText: 2021 Jason Francis <[email protected]>
// SPDX-License-Identifier: MIT
use proc_macro2::TokenStream;
use proc_macro_error::abort;
use quote::quote;
pub fn impl_variant_type(input: syn::DeriveInput) -> TokenStream {
let crate_path = super::crate_path();
let mut repr_attr = None;
let mut index_attr = None;
for attr in &input.attrs {
let is_index = attr.path.is_ident("glib_serde_variant_index");
let is_repr = attr.path.is_ident("glib_serde_repr");
if is_index || is_repr {
if repr_attr.is_some() || index_attr.is_some() {
abort!(
attr,
"Only one of #[glib_serde_variant_index] or #[glib_serde_repr] may be specified"
);
}
if is_index {
index_attr.replace(attr);
} else if is_repr {
repr_attr.replace(attr);
}
}
}
let name = &input.ident;
let (static_type, node) = match &input.data {
syn::Data::Struct(s) => {
if let Some(attr) = repr_attr {
abort!(attr, "#[glib_serde_repr] attribute not allowed on struct");
}
if let Some(attr) = index_attr {
abort!(
attr,
"#[glib_serde_variant_index] attribute not allowed on struct"
);
}
impl_for_fields(&crate_path, name, &s.fields)
}
syn::Data::Enum(e) => {
let (tag, tag_str) = repr_attr
.map(|_| {
for attr in &input.attrs {
if attr.path.is_ident("repr") {
abort!(attr, "#[glib_serde_repr] cannot be used with #[repr]");
}
}
(quote! { INT32 }, "i")
})
.or_else(|| index_attr.map(|_| (quote! { UINT32 }, "u")))
.unwrap_or_else(|| (quote! { STRING }, "s"));
let tag = quote! { #crate_path::glib::VariantTy::#tag };
let has_data = e
.variants
.iter()
.any(|v| !matches!(v.fields, syn::Fields::Unit));
if has_data {
let static_type_str = format!("({}v)", tag_str);
let children = e.variants.iter().map(|variant| {
let (_, node) = impl_for_fields(&crate_path, name, &variant.fields);
node
});
(
quote! {
::std::borrow::Cow::Borrowed(
unsafe {
#crate_path::glib::VariantTy::from_str_unchecked(#static_type_str)
}
)
},
impl_lazy(
&crate_path,
quote! { #crate_path::VariantTypeNode },
quote! {
#crate_path::VariantTypeNode::new(
<#name as #crate_path::glib::StaticVariantType>::static_variant_type(),
[ #(#children),* ],
)
},
),
)
} else {
(
quote! { ::std::borrow::Cow::Borrowed(#tag) },
impl_lazy(
&crate_path,
quote! { #crate_path::VariantTypeNode },
quote! {
#crate_path::VariantTypeNode::new(
::std::borrow::Cow::Borrowed(#tag),
[]
)
},
),
)
}
}
syn::Data::Union(u) => {
abort!(
u.union_token,
"#[derive(glib_serde::VariantType)] is not available for unions."
);
}
};
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
quote! {
impl #impl_generics #crate_path::glib::StaticVariantType for #name #ty_generics #where_clause {
fn static_variant_type() -> ::std::borrow::Cow<'static, #crate_path::glib::VariantTy> {
#static_type
}
}
impl #impl_generics #crate_path::VariantType for #name #ty_generics #where_clause {
fn variant_type() -> ::std::borrow::Cow<'static, #crate_path::VariantTypeNode<'static>> {
#node
}
}
}
}
fn impl_for_fields(
crate_path: &TokenStream,
name: &syn::Ident,
fields: &syn::Fields,
) -> (TokenStream, TokenStream) {
match fields {
syn::Fields::Named(_) | syn::Fields::Unnamed(_) => {
let types = fields.iter().map(|f| &f.ty);
if fields.len() == 1 {
let ty = &fields.iter().next().unwrap().ty;
(
quote! {
<#ty as glib::StaticVariantType>::static_variant_type()
},
quote! {
<#ty as #crate_path::VariantType>::variant_type()
},
)
} else {
let types2 = types.clone();
(
impl_lazy(
crate_path,
quote! { #crate_path::glib::VariantType },
quote! {
{
let mut builder = #crate_path::glib::GStringBuilder::new("(");
#(
{
let typ = <#types as glib::StaticVariantType>::static_variant_type();
builder.append(typ.as_str());
}
)*
builder.append_c(')');
#crate_path::glib::VariantType::from_string(builder.into_string()).unwrap()
}
},
),
impl_lazy(
crate_path,
quote! { #crate_path::VariantTypeNode },
quote! {
#crate_path::VariantTypeNode::new(
<#name as #crate_path::glib::StaticVariantType>::static_variant_type(),
[
#(
<#types2 as #crate_path::VariantType>::variant_type()
),*
]
)
},
),
)
}
}
syn::Fields::Unit => (
quote! { ::std::borrow::Cow::Borrowed(#crate_path::glib::VariantTy::UNIT) },
impl_lazy(
crate_path,
quote! { #crate_path::VariantTypeNode },
quote! {
#crate_path::VariantTypeNode::new(
::std::borrow::Cow::Borrowed(#crate_path::glib::VariantTy::UNIT),
[]
)
},
),
),
}
}
fn impl_lazy(crate_path: &TokenStream, ty: TokenStream, value: TokenStream) -> TokenStream {
quote! {
{
static TYP: #crate_path::glib::once_cell::sync::Lazy<#ty>
= #crate_path::glib::once_cell::sync::Lazy::new(|| #value);
::std::borrow::Cow::Borrowed(&*TYP)
}
}
}
| 38.038835 | 109 | 0.401863 |
1ce093b4afd66514a4757bdbc90d369170f56ef7 | 22,019 | // Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use ffi;
use font::{FontExtents, FontFace, FontOptions, Glyph, ScaledFont, TextCluster, TextExtents};
#[cfg(feature = "use_glib")]
use glib::translate::*;
use libc::c_int;
use matrices::Matrix;
use paths::Path;
use std::ffi::CString;
use std::fmt;
use std::ops;
use std::slice;
use Rectangle;
use {
Antialias, Content, FillRule, FontSlant, FontWeight, LineCap, LineJoin, Operator, Status,
TextClusterFlags,
};
use ffi::{cairo_rectangle_list_t, cairo_t};
use patterns::Pattern;
use surface::Surface;
pub struct RectangleList {
ptr: *mut cairo_rectangle_list_t,
}
impl ops::Deref for RectangleList {
type Target = [Rectangle];
fn deref(&self) -> &[Rectangle] {
unsafe {
let ptr = (*self.ptr).rectangles as *mut Rectangle;
let len = (*self.ptr).num_rectangles;
if ptr.is_null() || len == 0 {
&[]
} else {
slice::from_raw_parts(ptr, len as usize)
}
}
}
}
impl Drop for RectangleList {
fn drop(&mut self) {
unsafe {
ffi::cairo_rectangle_list_destroy(self.ptr);
}
}
}
impl fmt::Debug for RectangleList {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use std::ops::Deref;
f.debug_tuple("RectangleList").field(&self.deref()).finish()
}
}
impl fmt::Display for RectangleList {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "RectangleList")
}
}
#[derive(Debug)]
pub struct Context(*mut cairo_t, bool);
#[cfg(feature = "use_glib")]
impl<'a> ToGlibPtr<'a, *mut ffi::cairo_t> for &'a Context {
type Storage = &'a Context;
#[inline]
fn to_glib_none(&self) -> Stash<'a, *mut ffi::cairo_t, &'a Context> {
Stash(self.0, *self)
}
#[inline]
fn to_glib_full(&self) -> *mut ffi::cairo_t {
unsafe { ffi::cairo_reference(self.0) }
}
}
#[cfg(feature = "use_glib")]
impl FromGlibPtrNone<*mut ffi::cairo_t> for Context {
#[inline]
unsafe fn from_glib_none(ptr: *mut ffi::cairo_t) -> Context {
Self::from_raw_none(ptr)
}
}
#[cfg(feature = "use_glib")]
impl FromGlibPtrBorrow<*mut ffi::cairo_t> for Context {
#[inline]
unsafe fn from_glib_borrow(ptr: *mut ffi::cairo_t) -> Context {
Self::from_raw_borrow(ptr)
}
}
#[cfg(feature = "use_glib")]
impl FromGlibPtrFull<*mut ffi::cairo_t> for Context {
#[inline]
unsafe fn from_glib_full(ptr: *mut ffi::cairo_t) -> Context {
Self::from_raw_full(ptr)
}
}
#[cfg(feature = "use_glib")]
gvalue_impl!(
Context,
cairo_t,
ffi::gobject::cairo_gobject_context_get_type
);
impl Clone for Context {
fn clone(&self) -> Context {
unsafe { Self::from_raw_none(self.to_raw_none()) }
}
}
impl Drop for Context {
fn drop(&mut self) {
if !self.1 {
unsafe {
ffi::cairo_destroy(self.0);
}
}
}
}
impl Context {
#[inline]
pub unsafe fn from_raw_none(ptr: *mut ffi::cairo_t) -> Context {
assert!(!ptr.is_null());
ffi::cairo_reference(ptr);
Context(ptr, false)
}
#[inline]
pub unsafe fn from_raw_borrow(ptr: *mut ffi::cairo_t) -> Context {
assert!(!ptr.is_null());
Context(ptr, true)
}
#[inline]
pub unsafe fn from_raw_full(ptr: *mut ffi::cairo_t) -> Context {
assert!(!ptr.is_null());
Context(ptr, false)
}
pub fn to_raw_none(&self) -> *mut ffi::cairo_t {
self.0
}
pub fn ensure_status(&self) {
self.status().ensure_valid();
}
pub fn new(target: &Surface) -> Context {
unsafe { Self::from_raw_full(ffi::cairo_create(target.to_raw_none())) }
}
pub fn status(&self) -> Status {
unsafe { Status::from(ffi::cairo_status(self.0)) }
}
pub fn save(&self) {
unsafe { ffi::cairo_save(self.0) }
self.ensure_status()
}
pub fn restore(&self) {
unsafe { ffi::cairo_restore(self.0) }
self.ensure_status()
}
pub fn get_target(&self) -> Surface {
unsafe { Surface::from_raw_none(ffi::cairo_get_target(self.0)) }
}
pub fn push_group(&self) {
unsafe { ffi::cairo_push_group(self.0) }
}
pub fn push_group_with_content(&self, content: Content) {
unsafe { ffi::cairo_push_group_with_content(self.0, content.into()) }
}
pub fn pop_group(&self) -> Pattern {
unsafe { Pattern::from_raw_full(ffi::cairo_pop_group(self.0)) }
}
pub fn pop_group_to_source(&self) {
unsafe { ffi::cairo_pop_group_to_source(self.0) }
}
pub fn get_group_target(&self) -> Surface {
unsafe { Surface::from_raw_none(ffi::cairo_get_group_target(self.0)) }
}
pub fn set_source_rgb(&self, red: f64, green: f64, blue: f64) {
unsafe { ffi::cairo_set_source_rgb(self.0, red, green, blue) }
}
pub fn set_source_rgba(&self, red: f64, green: f64, blue: f64, alpha: f64) {
unsafe { ffi::cairo_set_source_rgba(self.0, red, green, blue, alpha) }
}
pub fn set_source(&self, source: &Pattern) {
unsafe {
ffi::cairo_set_source(self.0, source.to_raw_none());
}
self.ensure_status();
}
pub fn get_source(&self) -> Pattern {
unsafe { Pattern::from_raw_none(ffi::cairo_get_source(self.0)) }
}
pub fn set_source_surface(&self, surface: &Surface, x: f64, y: f64) {
unsafe {
ffi::cairo_set_source_surface(self.0, surface.to_raw_none(), x, y);
}
}
pub fn set_antialias(&self, antialias: Antialias) {
unsafe { ffi::cairo_set_antialias(self.0, antialias.into()) }
self.ensure_status()
}
pub fn get_antialias(&self) -> Antialias {
unsafe { Antialias::from(ffi::cairo_get_antialias(self.0)) }
}
pub fn set_dash(&self, dashes: &[f64], offset: f64) {
unsafe { ffi::cairo_set_dash(self.0, dashes.as_ptr(), dashes.len() as i32, offset) }
self.ensure_status(); //Possible invalid dashes value
}
pub fn get_dash_count(&self) -> i32 {
unsafe { ffi::cairo_get_dash_count(self.0) }
}
pub fn get_dash(&self) -> (Vec<f64>, f64) {
let dash_count = self.get_dash_count() as usize;
let mut dashes: Vec<f64> = Vec::with_capacity(dash_count);
let mut offset: f64 = 0.0;
unsafe {
ffi::cairo_get_dash(self.0, dashes.as_mut_ptr(), &mut offset);
dashes.set_len(dash_count);
(dashes, offset)
}
}
pub fn get_dash_dashes(&self) -> Vec<f64> {
let (dashes, _) = self.get_dash();
dashes
}
pub fn get_dash_offset(&self) -> f64 {
let (_, offset) = self.get_dash();
offset
}
pub fn set_fill_rule(&self, fill_rule: FillRule) {
unsafe {
ffi::cairo_set_fill_rule(self.0, fill_rule.into());
}
self.ensure_status();
}
pub fn get_fill_rule(&self) -> FillRule {
unsafe { FillRule::from(ffi::cairo_get_fill_rule(self.0)) }
}
pub fn set_line_cap(&self, arg: LineCap) {
unsafe { ffi::cairo_set_line_cap(self.0, arg.into()) }
self.ensure_status();
}
pub fn get_line_cap(&self) -> LineCap {
unsafe { LineCap::from(ffi::cairo_get_line_cap(self.0)) }
}
pub fn set_line_join(&self, arg: LineJoin) {
unsafe { ffi::cairo_set_line_join(self.0, arg.into()) }
self.ensure_status();
}
pub fn get_line_join(&self) -> LineJoin {
unsafe { LineJoin::from(ffi::cairo_get_line_join(self.0)) }
}
pub fn set_line_width(&self, arg: f64) {
unsafe { ffi::cairo_set_line_width(self.0, arg) }
self.ensure_status();
}
pub fn get_line_width(&self) -> f64 {
unsafe { ffi::cairo_get_line_width(self.0) }
}
pub fn set_miter_limit(&self, arg: f64) {
unsafe { ffi::cairo_set_miter_limit(self.0, arg) }
self.ensure_status();
}
pub fn get_miter_limit(&self) -> f64 {
unsafe { ffi::cairo_get_miter_limit(self.0) }
}
pub fn set_operator(&self, op: Operator) {
unsafe {
ffi::cairo_set_operator(self.0, op.into());
}
}
pub fn get_operator(&self) -> Operator {
unsafe { Operator::from(ffi::cairo_get_operator(self.0)) }
}
pub fn set_tolerance(&self, arg: f64) {
unsafe { ffi::cairo_set_tolerance(self.0, arg) }
self.ensure_status();
}
pub fn get_tolerance(&self) -> f64 {
unsafe { ffi::cairo_get_tolerance(self.0) }
}
pub fn clip(&self) {
unsafe { ffi::cairo_clip(self.0) }
}
pub fn clip_preserve(&self) {
unsafe { ffi::cairo_clip_preserve(self.0) }
}
pub fn clip_extents(&self) -> (f64, f64, f64, f64) {
let mut x1: f64 = 0.0;
let mut y1: f64 = 0.0;
let mut x2: f64 = 0.0;
let mut y2: f64 = 0.0;
unsafe {
ffi::cairo_clip_extents(self.0, &mut x1, &mut y1, &mut x2, &mut y2);
}
(x1, y1, x2, y2)
}
pub fn in_clip(&self, x: f64, y: f64) -> bool {
unsafe { ffi::cairo_in_clip(self.0, x, y).as_bool() }
}
pub fn reset_clip(&self) {
unsafe { ffi::cairo_reset_clip(self.0) }
self.ensure_status()
}
pub fn copy_clip_rectangle_list(&self) -> RectangleList {
unsafe {
let rectangle_list = ffi::cairo_copy_clip_rectangle_list(self.0);
Status::from((*rectangle_list).status).ensure_valid();
RectangleList {
ptr: rectangle_list,
}
}
}
pub fn fill(&self) {
unsafe { ffi::cairo_fill(self.0) }
}
pub fn fill_preserve(&self) {
unsafe { ffi::cairo_fill_preserve(self.0) }
}
pub fn fill_extents(&self) -> (f64, f64, f64, f64) {
let mut x1: f64 = 0.0;
let mut y1: f64 = 0.0;
let mut x2: f64 = 0.0;
let mut y2: f64 = 0.0;
unsafe {
ffi::cairo_fill_extents(self.0, &mut x1, &mut y1, &mut x2, &mut y2);
}
(x1, y1, x2, y2)
}
pub fn in_fill(&self, x: f64, y: f64) -> bool {
unsafe { ffi::cairo_in_fill(self.0, x, y).as_bool() }
}
pub fn mask(&self, pattern: &Pattern) {
unsafe { ffi::cairo_mask(self.0, pattern.to_raw_none()) }
}
pub fn mask_surface(&self, surface: &Surface, x: f64, y: f64) {
unsafe {
ffi::cairo_mask_surface(self.0, surface.to_raw_none(), x, y);
}
}
pub fn paint(&self) {
unsafe { ffi::cairo_paint(self.0) }
}
pub fn paint_with_alpha(&self, alpha: f64) {
unsafe { ffi::cairo_paint_with_alpha(self.0, alpha) }
}
pub fn stroke(&self) {
unsafe { ffi::cairo_stroke(self.0) }
}
pub fn stroke_preserve(&self) {
unsafe { ffi::cairo_stroke_preserve(self.0) }
}
pub fn stroke_extents(&self) -> (f64, f64, f64, f64) {
let mut x1: f64 = 0.0;
let mut y1: f64 = 0.0;
let mut x2: f64 = 0.0;
let mut y2: f64 = 0.0;
unsafe {
ffi::cairo_stroke_extents(self.0, &mut x1, &mut y1, &mut x2, &mut y2);
}
(x1, y1, x2, y2)
}
pub fn in_stroke(&self, x: f64, y: f64) -> bool {
unsafe { ffi::cairo_in_stroke(self.0, x, y).as_bool() }
}
pub fn copy_page(&self) {
unsafe { ffi::cairo_copy_page(self.0) }
}
pub fn show_page(&self) {
unsafe { ffi::cairo_show_page(self.0) }
}
pub fn get_reference_count(&self) -> u32 {
unsafe { ffi::cairo_get_reference_count(self.0) }
}
// transformations stuff
pub fn translate(&self, tx: f64, ty: f64) {
unsafe { ffi::cairo_translate(self.0, tx, ty) }
}
pub fn scale(&self, sx: f64, sy: f64) {
unsafe { ffi::cairo_scale(self.0, sx, sy) }
}
pub fn rotate(&self, angle: f64) {
unsafe { ffi::cairo_rotate(self.0, angle) }
}
pub fn transform(&self, matrix: Matrix) {
unsafe {
ffi::cairo_transform(self.0, matrix.ptr());
}
}
pub fn set_matrix(&self, matrix: Matrix) {
unsafe {
ffi::cairo_set_matrix(self.0, matrix.ptr());
}
}
pub fn get_matrix(&self) -> Matrix {
let mut matrix = Matrix::null();
unsafe {
ffi::cairo_get_matrix(self.0, matrix.mut_ptr());
}
matrix
}
pub fn identity_matrix(&self) {
unsafe { ffi::cairo_identity_matrix(self.0) }
}
pub fn user_to_device(&self, mut x: f64, mut y: f64) -> (f64, f64) {
unsafe {
ffi::cairo_user_to_device(self.0, &mut x, &mut y);
(x, y)
}
}
pub fn user_to_device_distance(&self, mut dx: f64, mut dy: f64) -> (f64, f64) {
unsafe {
ffi::cairo_user_to_device_distance(self.0, &mut dx, &mut dy);
(dx, dy)
}
}
pub fn device_to_user(&self, mut x: f64, mut y: f64) -> (f64, f64) {
unsafe {
ffi::cairo_device_to_user(self.0, &mut x, &mut y);
(x, y)
}
}
pub fn device_to_user_distance(&self, mut dx: f64, mut dy: f64) -> (f64, f64) {
unsafe {
ffi::cairo_device_to_user_distance(self.0, &mut dx, &mut dy);
(dx, dy)
}
}
// font stuff
pub fn select_font_face(&self, family: &str, slant: FontSlant, weight: FontWeight) {
unsafe {
let family = CString::new(family).unwrap();
ffi::cairo_select_font_face(self.0, family.as_ptr(), slant.into(), weight.into())
}
}
pub fn set_font_size(&self, size: f64) {
unsafe { ffi::cairo_set_font_size(self.0, size) }
}
// FIXME probably needs a heap allocation
pub fn set_font_matrix(&self, matrix: Matrix) {
unsafe { ffi::cairo_set_font_matrix(self.0, matrix.ptr()) }
}
pub fn get_font_matrix(&self) -> Matrix {
let mut matrix = Matrix::null();
unsafe {
ffi::cairo_get_font_matrix(self.0, matrix.mut_ptr());
}
matrix
}
pub fn set_font_options(&self, options: &FontOptions) {
unsafe { ffi::cairo_set_font_options(self.0, options.to_raw_none()) }
}
pub fn get_font_options(&self) -> FontOptions {
let out = FontOptions::new();
unsafe {
ffi::cairo_get_font_options(self.0, out.to_raw_none());
}
out
}
pub fn set_font_face(&self, font_face: &FontFace) {
unsafe { ffi::cairo_set_font_face(self.0, font_face.to_raw_none()) }
}
pub fn get_font_face(&self) -> FontFace {
unsafe { FontFace::from_raw_none(ffi::cairo_get_font_face(self.0)) }
}
pub fn set_scaled_font(&self, scaled_font: &ScaledFont) {
unsafe { ffi::cairo_set_scaled_font(self.0, scaled_font.to_raw_none()) }
}
pub fn get_scaled_font(&self) -> ScaledFont {
unsafe { ScaledFont::from_raw_none(ffi::cairo_get_scaled_font(self.0)) }
}
pub fn show_text(&self, text: &str) {
unsafe {
let text = CString::new(text).unwrap();
ffi::cairo_show_text(self.0, text.as_ptr())
}
}
pub fn show_glyphs(&self, glyphs: &[Glyph]) {
unsafe { ffi::cairo_show_glyphs(self.0, glyphs.as_ptr(), glyphs.len() as c_int) }
}
pub fn show_text_glyphs(
&self,
text: &str,
glyphs: &[Glyph],
clusters: &[TextCluster],
cluster_flags: TextClusterFlags,
) {
unsafe {
let text = CString::new(text).unwrap();
ffi::cairo_show_text_glyphs(
self.0,
text.as_ptr(),
-1 as c_int, //NULL terminated
glyphs.as_ptr(),
glyphs.len() as c_int,
clusters.as_ptr(),
clusters.len() as c_int,
cluster_flags.into(),
)
}
}
pub fn font_extents(&self) -> FontExtents {
let mut extents = FontExtents {
ascent: 0.0,
descent: 0.0,
height: 0.0,
max_x_advance: 0.0,
max_y_advance: 0.0,
};
unsafe {
ffi::cairo_font_extents(self.0, &mut extents);
}
extents
}
pub fn text_extents(&self, text: &str) -> TextExtents {
let mut extents = TextExtents {
x_bearing: 0.0,
y_bearing: 0.0,
width: 0.0,
height: 0.0,
x_advance: 0.0,
y_advance: 0.0,
};
unsafe {
let text = CString::new(text).unwrap();
ffi::cairo_text_extents(self.0, text.as_ptr(), &mut extents);
}
extents
}
pub fn glyph_extents(&self, glyphs: &[Glyph]) -> TextExtents {
let mut extents = TextExtents {
x_bearing: 0.0,
y_bearing: 0.0,
width: 0.0,
height: 0.0,
x_advance: 0.0,
y_advance: 0.0,
};
unsafe {
ffi::cairo_glyph_extents(self.0, glyphs.as_ptr(), glyphs.len() as c_int, &mut extents);
}
extents
}
// paths stuff
pub fn copy_path(&self) -> Path {
unsafe { Path::from_raw_full(ffi::cairo_copy_path(self.0)) }
}
pub fn copy_path_flat(&self) -> Path {
unsafe { Path::from_raw_full(ffi::cairo_copy_path_flat(self.0)) }
}
pub fn append_path(&self, path: &Path) {
unsafe { ffi::cairo_append_path(self.0, path.as_ptr()) }
}
pub fn has_current_point(&self) -> bool {
unsafe { ffi::cairo_has_current_point(self.0).as_bool() }
}
pub fn get_current_point(&self) -> (f64, f64) {
unsafe {
let mut x = 0.0;
let mut y = 0.0;
ffi::cairo_get_current_point(self.0, &mut x, &mut y);
(x, y)
}
}
pub fn new_path(&self) {
unsafe { ffi::cairo_new_path(self.0) }
}
pub fn new_sub_path(&self) {
unsafe { ffi::cairo_new_sub_path(self.0) }
}
pub fn close_path(&self) {
unsafe { ffi::cairo_close_path(self.0) }
}
pub fn arc(&self, xc: f64, yc: f64, radius: f64, angle1: f64, angle2: f64) {
unsafe { ffi::cairo_arc(self.0, xc, yc, radius, angle1, angle2) }
}
pub fn arc_negative(&self, xc: f64, yc: f64, radius: f64, angle1: f64, angle2: f64) {
unsafe { ffi::cairo_arc_negative(self.0, xc, yc, radius, angle1, angle2) }
}
pub fn curve_to(&self, x1: f64, y1: f64, x2: f64, y2: f64, x3: f64, y3: f64) {
unsafe { ffi::cairo_curve_to(self.0, x1, y1, x2, y2, x3, y3) }
}
pub fn line_to(&self, x: f64, y: f64) {
unsafe { ffi::cairo_line_to(self.0, x, y) }
}
pub fn move_to(&self, x: f64, y: f64) {
unsafe { ffi::cairo_move_to(self.0, x, y) }
}
pub fn rectangle(&self, x: f64, y: f64, width: f64, height: f64) {
unsafe { ffi::cairo_rectangle(self.0, x, y, width, height) }
}
pub fn text_path(&self, str_: &str) {
unsafe {
let str_ = CString::new(str_).unwrap();
ffi::cairo_text_path(self.0, str_.as_ptr())
}
}
pub fn glyph_path(&self, glyphs: &[Glyph]) {
unsafe { ffi::cairo_glyph_path(self.0, glyphs.as_ptr(), glyphs.len() as i32) }
}
pub fn rel_curve_to(&self, dx1: f64, dy1: f64, dx2: f64, dy2: f64, dx3: f64, dy3: f64) {
unsafe { ffi::cairo_rel_curve_to(self.0, dx1, dy1, dx2, dy2, dx3, dy3) }
}
pub fn rel_line_to(&self, dx: f64, dy: f64) {
unsafe { ffi::cairo_rel_line_to(self.0, dx, dy) }
}
pub fn rel_move_to(&self, dx: f64, dy: f64) {
unsafe { ffi::cairo_rel_move_to(self.0, dx, dy) }
}
pub fn path_extents(&self) -> (f64, f64, f64, f64) {
let mut x1: f64 = 0.0;
let mut y1: f64 = 0.0;
let mut x2: f64 = 0.0;
let mut y2: f64 = 0.0;
unsafe {
ffi::cairo_path_extents(self.0, &mut x1, &mut y1, &mut x2, &mut y2);
}
(x1, y1, x2, y2)
}
#[cfg(any(feature = "v1_16", feature = "dox"))]
pub fn tag_begin(&self, tag_name: &str, attributes: &str) {
unsafe {
let tag_name = CString::new(tag_name).unwrap();
let attributes = CString::new(attributes).unwrap();
ffi::cairo_tag_begin(self.0, tag_name.as_ptr(), attributes.as_ptr())
}
}
#[cfg(any(feature = "v1_16", feature = "dox"))]
pub fn tag_end(&self, tag_name: &str) {
unsafe {
let tag_name = CString::new(tag_name).unwrap();
ffi::cairo_tag_end(self.0, tag_name.as_ptr())
}
}
}
impl fmt::Display for Context {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Context")
}
}
#[cfg(test)]
mod tests {
use super::*;
use enums::Format;
use image_surface::ImageSurface;
use patterns::LinearGradient;
fn create_ctx() -> Context {
let surface = ImageSurface::create(Format::ARgb32, 10, 10).unwrap();
Context::new(&surface)
}
#[test]
fn drop_non_reference_pattern_from_ctx() {
let ctx = create_ctx();
ctx.get_source();
}
#[test]
fn drop_non_reference_pattern() {
let ctx = create_ctx();
let pattern = LinearGradient::new(1.0f64, 2.0f64, 3.0f64, 4.0f64);
ctx.set_source(&pattern);
}
#[test]
fn clip_rectange() {
let ctx = create_ctx();
let rect = ctx.copy_clip_rectangle_list();
assert_eq!(
format!("{:?}", rect),
"RectangleList([Rectangle { x: 0.0, y: 0.0, width: 10.0, height: 10.0 }])"
);
assert_eq!(rect.to_string(), "RectangleList");
}
}
| 27.050369 | 99 | 0.559335 |
8fb2f2147579ad99cb7c5e56e2ea455adb57e0bf | 2,436 | use qca_common::mbscanners::channel::{
MBBaud, MBChannel, MBChannelAddress, MBChannelRTUAddress, MBChannelTCPAddress, MBDataBits, MBFlowControl, MBParity,
MBStopBits,
};
use qca_common::mbscanners::device::MBDevice;
use qca_common::mbscanners::scanline::{MBScanline, MBScanlineCode};
use qca_common::mbscanners::MBConfig;
use qca_common::{IJsonSerializable, IYamlSerializable};
fn main() {
let mut mb_config = MBConfig { channels: Vec::new() };
mb_config.channels.push(MBChannel {
timeout_ms: 500,
interframe_delay_ms: 10,
address: MBChannelAddress::TCP(MBChannelTCPAddress {
socket_address: "127.0.0.1:502".parse().unwrap(),
}),
devices: vec![
MBDevice {
slave_address: 0,
scanlines: vec![
MBScanline {
function_code: MBScanlineCode::FC03,
interval_ms: 1000,
length: 5,
start_address: 100,
},
MBScanline {
function_code: MBScanlineCode::FC01,
interval_ms: 1000,
length: 1,
start_address: 1,
},
],
},
MBDevice {
slave_address: 1,
scanlines: vec![MBScanline {
function_code: MBScanlineCode::FC03,
interval_ms: 200,
length: 1,
start_address: 1,
}],
},
],
});
mb_config.channels.push(MBChannel {
timeout_ms: 500,
interframe_delay_ms: 10,
address: MBChannelAddress::RTU(MBChannelRTUAddress {
port_address: "/dev/ttyUSB0".into(),
baud: MBBaud::B115200,
data_bits: MBDataBits::Eight,
parity: MBParity::None,
stop_bits: MBStopBits::Two,
flow_control: MBFlowControl::None,
}),
devices: vec![MBDevice {
slave_address: 1,
scanlines: vec![MBScanline {
function_code: MBScanlineCode::FC03,
interval_ms: 1000,
length: 3,
start_address: 434,
}],
}],
});
println!("{}", mb_config.to_json_pretty());
println!("{}", mb_config.to_yaml());
}
| 34.309859 | 119 | 0.503695 |
89dbdf01968d86f3e66db4c623ce0846c619df08 | 1,331 | // structs2.rs
// Address all the TODOs to make the tests pass!
//
#[derive(Debug)]
struct Order {
name: String,
year: u32,
made_by_phone: bool,
made_by_mobile: bool,
made_by_email: bool,
item_number: u32,
count: u32,
}
fn create_order_template() -> Order {
Order {
name: String::from("Bob"),
year: 2019,
made_by_phone: false,
made_by_mobile: false,
made_by_email: true,
item_number: 123,
count: 0,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn your_order() {
let order_template = create_order_template();
// TODO: Create your own order using the update syntax and template above!
let your_order = Order{
name: String::from("Hacker in Rust"),
count:1,
..order_template
};
assert_eq!(your_order.name, "Hacker in Rust");
assert_eq!(your_order.year, order_template.year);
assert_eq!(your_order.made_by_phone, order_template.made_by_phone);
assert_eq!(your_order.made_by_mobile, order_template.made_by_mobile);
assert_eq!(your_order.made_by_email, order_template.made_by_email);
assert_eq!(your_order.item_number, order_template.item_number);
assert_eq!(your_order.count, 1);
}
}
| 25.596154 | 82 | 0.619835 |
71e17b854e529d24a3befb06368f28e28cab474a | 9,299 | // Part of ethercat-rs. Copyright 2018-2019 by the authors.
// This work is dual-licensed under Apache 2.0 and MIT terms.
//! Modbus server allowing access to the PLC "memory" variables.
use std::collections::BTreeMap;
use std::io::{Result, Read, Write, ErrorKind};
use std::net::{TcpListener, TcpStream};
use std::thread;
use log::*;
use byteorder::{ByteOrder, BE};
use crossbeam_channel::{unbounded, Sender, Receiver};
#[derive(Debug)]
pub(crate) struct Request {
pub hid: usize,
pub tid: u16,
pub fc: u8,
pub addr: usize,
pub count: usize,
pub write: Option<Vec<u16>>,
}
#[derive(Debug)]
pub(crate) enum Response {
Ok(Request, Vec<u16>),
Error(Request, u8),
}
enum HandlerEvent {
Request(Request),
New((usize, Sender<Response>)),
Finished(usize),
}
struct Handler {
hid: usize,
client: TcpStream,
requests: Sender<HandlerEvent>,
}
pub struct Server {
to_plc: Sender<Request>,
from_plc: Receiver<Response>,
}
impl Handler {
pub fn new(client: TcpStream, hid: usize, requests: Sender<HandlerEvent>,
replies: Receiver<Response>) -> Self
{
let send_client = client.try_clone().expect("could not clone socket");
thread::spawn(move || Handler::sender(send_client, replies));
Handler { client, hid, requests }
}
fn sender(mut client: TcpStream, replies: Receiver<Response>) {
let mut buf = [0u8; 256];
mlzlog::set_thread_prefix(format!("{} sender: ", client.peer_addr().unwrap()));
for response in replies {
debug!("sending response: {:?}", response);
let count = match response {
Response::Ok(req, values) => {
BE::write_u16(&mut buf, req.tid);
buf[7] = req.fc;
match req.fc {
3 | 4 => {
let nbytes = 2 * values.len();
buf[8] = nbytes as u8;
BE::write_u16_into(&values, &mut buf[9..9+nbytes]);
9 + nbytes
}
6 => {
BE::write_u16(&mut buf[8..], req.addr as u16);
BE::write_u16(&mut buf[10..], values[0]);
12
}
16 => {
BE::write_u16(&mut buf[8..], req.addr as u16);
BE::write_u16(&mut buf[10..], values.len() as u16);
12
}
x => panic!("impossible function code {}", x)
}
}
Response::Error(req, ec) => {
BE::write_u16(&mut buf, req.tid);
buf[7] = req.fc | 0x80;
buf[8] = ec;
9
}
};
BE::write_u16(&mut buf[4..], (count - 6) as u16);
if let Err(err) = client.write_all(&buf[..count]) {
warn!("write error: {}", err);
break;
}
}
}
fn handle(mut self) {
let mut headbuf = [0u8; 8];
let mut bodybuf = [0u8; 250]; // max frame size is 255
let mut errbuf = [0, 0, 0, 0, 0, 9, 0, 0, 0];
mlzlog::set_thread_prefix(format!("{}: ", self.client.peer_addr().unwrap()));
info!("connection accepted");
'outer: loop {
if let Err(err) = self.client.read_exact(&mut headbuf) {
if err.kind() != ErrorKind::UnexpectedEof {
warn!("error reading request head: {}", err);
}
break;
}
if &headbuf[2..4] != &[0, 0] {
warn!("protocol ID mismatch: {:?}", headbuf);
break;
}
let tid = BE::read_u16(&headbuf);
let data_len = BE::read_u16(&headbuf[4..6]) as usize;
if let Err(err) = self.client.read_exact(&mut bodybuf[..data_len - 2]) {
warn!("error reading request body: {}", err);
break;
}
if headbuf[6] != 0 {
warn!("invalid slave {}", headbuf[6]);
continue;
}
let fc = headbuf[7];
let req = match fc {
3 | 4 => {
if data_len != 6 {
warn!("invalid data length for fc {}", fc);
continue;
}
let addr = BE::read_u16(&bodybuf[..2]) as usize;
let count = BE::read_u16(&bodybuf[2..4]) as usize;
Request { hid: self.hid, tid, fc, addr, count, write: None }
}
6 => {
if data_len != 6 {
warn!("invalid data length for fc {}", fc);
continue;
}
let addr = BE::read_u16(&bodybuf[..2]) as usize;
let value = BE::read_u16(&bodybuf[2..4]);
Request { hid: self.hid, tid, fc, addr, count: 1, write: Some(vec![value]) }
}
16 => {
if data_len < 7 {
warn!("insufficient data length for fc {}", fc);
continue;
}
let addr = BE::read_u16(&bodybuf[..2]) as usize;
let bytecount = bodybuf[4] as usize;
if data_len != 7 + bytecount {
warn!("invalid data length for fc {}", fc);
continue;
}
let mut values = vec![0; bytecount / 2];
BE::read_u16_into(&bodybuf[5..5+bytecount], &mut values);
Request { hid: self.hid, tid, fc, addr, count: values.len(), write: Some(values) }
}
_ => {
warn!("unknown function code {}", fc);
BE::write_u16(&mut errbuf, tid);
errbuf[7] = fc | 0x80;
errbuf[8] = 1;
if let Err(err) = self.client.write_all(&errbuf) {
warn!("error writing error response: {}", err);
break;
}
continue;
}
};
debug!("got request: {:?}", req);
if let Err(e) = self.requests.send(HandlerEvent::Request(req)) {
warn!("couldn't send request to server: {}", e);
}
}
info!("connection closed");
if let Err(e) = self.requests.send(HandlerEvent::Finished(self.hid)) {
warn!("couldn't send finish event to server: {}", e);
}
}
}
impl Server {
pub(crate) fn new() -> (Self, Receiver<Request>, Sender<Response>) {
let (w_to_plc, r_to_plc) = unbounded();
let (w_from_plc, r_from_plc) = unbounded();
(Server { to_plc: w_to_plc, from_plc: r_from_plc }, r_to_plc, w_from_plc)
}
/// Listen for connections on the TCP socket and spawn handlers for it.
fn tcp_listener(tcp_sock: TcpListener, handler_sender: Sender<HandlerEvent>) {
mlzlog::set_thread_prefix("Modbus: ");
info!("listening on {}", tcp_sock.local_addr().unwrap());
let mut handler_id = 0;
while let Ok((stream, _)) = tcp_sock.accept() {
let (w_rep, r_rep) = unbounded();
let w_req = handler_sender.clone();
handler_id += 1;
if let Err(e) = w_req.send(HandlerEvent::New((handler_id, w_rep))) {
warn!("couldn't send new handler event: {}", e);
} else {
thread::spawn(move || Handler::new(stream, handler_id,
w_req, r_rep).handle());
}
}
}
fn dispatcher(self, r_clients: Receiver<HandlerEvent>) {
mlzlog::set_thread_prefix("Dispatcher: ");
let mut handlers = BTreeMap::new();
for event in r_clients {
match event {
HandlerEvent::New((id, chan)) => {
handlers.insert(id, chan);
}
HandlerEvent::Finished(id) => {
handlers.remove(&id);
}
HandlerEvent::Request(req) => {
let hid = req.hid;
if let Err(e) = self.to_plc.send(req) {
warn!("couldn't send request to PLC: {}", e);
} else {
let resp = self.from_plc.recv().unwrap();
if let Err(e) = handlers[&hid].send(resp) {
warn!("couldn't send reply to handler: {}", e);
}
}
}
}
}
}
pub fn start(self, addr: &str) -> Result<()> {
let (w_clients, r_clients) = unbounded();
let tcp_sock = TcpListener::bind(addr)?;
thread::spawn(move || Server::tcp_listener(tcp_sock, w_clients));
thread::spawn(move || Server::dispatcher(self, r_clients));
Ok(())
}
}
| 36.466667 | 102 | 0.450263 |
ed5cccf9df00675dc4aed5dc40f08f1c2efef731 | 9,914 | use std::{
collections::{BTreeMap, HashMap, HashSet},
ops::{Add, Mul, Sub},
};
pub fn solve() -> (usize, isize) {
let scanners = parse(std::fs::read_to_string("res/day19.txt").unwrap());
(part1(&scanners), part2(&scanners))
}
fn part1(scanners: &[Vec<Vector>]) -> usize {
let mut beacons: HashSet<Vector> = HashSet::from_iter(scanners[0].iter().cloned());
for (scanner, (matrix, vector)) in match_scanners(scanners) {
beacons.extend(
scanners[scanner]
.iter()
.map(|beacon| *beacon * matrix + vector),
);
}
beacons.len()
}
fn part2(scanners: &[Vec<Vector>]) -> isize {
let transformations = match_scanners(scanners);
let mut max = 0;
for (_, (_, left)) in transformations.iter() {
for (_, (_, right)) in transformations.iter() {
let d = (left.0 - right.0).abs() + (left.1 - right.1).abs() + (left.2 - right.2).abs();
max = std::cmp::max(max, d);
}
}
max
}
/// Checks two sets of beacons for overlaps
fn compare(left_beacons: &[Vector], right_beacons: &[Vector]) -> Option<(Matrix, Vector)> {
for rotation in Matrix::rotations() {
let mut shifts: HashMap<Vector, usize> = HashMap::new();
for left_beacon in left_beacons {
for right_beacon in right_beacons {
let transformed = *right_beacon * rotation;
*shifts.entry(*left_beacon - transformed).or_default() += 1;
}
}
if let Some((shift, _)) = shifts.into_iter().find(|(_, cnt)| *cnt >= 12) {
return Some((rotation, shift));
}
}
None
}
/// Attempts to match scanners in pairs based on their scanned beacons. Returns a rotation and shift
/// for each one, in relation to scanner 0
fn match_scanners(scanners: &[Vec<Vector>]) -> HashMap<usize, (Matrix, Vector)> {
let mut matches: BTreeMap<usize, HashSet<(usize, Matrix, Vector)>> = BTreeMap::new();
for (scanner, beacons) in scanners.iter().enumerate() {
for (ref_scanner, ref_beacons) in scanners.iter().enumerate() {
if scanner == ref_scanner {
continue;
}
if let Some((rotation, shift)) = compare(ref_beacons, beacons) {
assert!(matches
.entry(scanner)
.or_default()
.insert((ref_scanner, rotation, shift)));
}
}
}
(1..scanners.len())
.map(|s| {
(
s,
transformation(s, 0, HashSet::default(), &matches)
.unwrap_or_else(|| panic!("No match found for scanner {}", s)),
)
})
.collect()
// let transformations = HashMap::new();
// for scanner in 1..scanners.len() {
// let (matrix, vector) = transformation(scanner, 0, HashSet::new(), &matches)
// .unwrap_or_else(|| panic!("No match found for scanner {}", scanner));
// beacons.extend(
// scanners[scanner]
// .iter()
// .map(|beacon| *beacon * matrix + vector),
// );
// }
// matches
}
/// Derives a transformation (Rotation + Shift) based on the given associations between 2 scanners
fn transformation(
curr: usize,
target: usize,
history: HashSet<usize>,
matches: &BTreeMap<usize, HashSet<(usize, Matrix, Vector)>>,
) -> Option<(Matrix, Vector)> {
for (to, matrix, vector) in matches.get(&curr)?.iter() {
if *to == target {
return Some((*matrix, *vector));
} else if history.contains(to) {
continue;
} else {
let mut history = history.clone();
history.insert(curr);
if let Some((submatrix, subvector)) = transformation(*to, target, history, matches) {
return Some((submatrix * *matrix, *vector * submatrix + subvector));
}
}
}
None
}
fn parse(from: String) -> Vec<Vec<Vector>> {
let mut scanners = vec![];
let mut scanner = vec![];
for line in from.split('\n') {
if line.trim().is_empty() {
scanners.push(scanner);
scanner = vec![];
} else {
scanner.push(Vector::parse(line).unwrap());
}
}
scanners.push(scanner);
scanners
}
type Dimension = isize;
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
struct Vector(Dimension, Dimension, Dimension);
impl Vector {
pub fn parse(from: &str) -> Option<Self> {
let mut split = from.split(',');
let x = split.next()?.parse().ok()?;
let y = split.next()?.parse().ok()?;
let z = split.next()?.parse().ok()?;
Some(Self(x, y, z))
}
}
impl Add for Vector {
type Output = Vector;
fn add(self, other: Self) -> Self::Output {
Vector(self.0 + other.0, self.1 + other.1, self.2 + other.2)
}
}
impl Sub for Vector {
type Output = Self;
fn sub(self, other: Self) -> Self::Output {
Vector(self.0 - other.0, self.1 - other.1, self.2 - other.2)
}
}
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
struct Matrix(Vector, Vector, Vector);
impl Matrix {
pub const fn rotations() -> [Self; 24] {
[
Matrix(Vector(1, 0, 0), Vector(0, 1, 0), Vector(0, 0, 1)),
Matrix(Vector(1, 0, 0), Vector(0, 0, -1), Vector(0, 1, 0)),
Matrix(Vector(1, 0, 0), Vector(0, -1, 0), Vector(0, 0, -1)),
Matrix(Vector(1, 0, 0), Vector(0, 0, 1), Vector(0, -1, 0)),
/////////////////
Matrix(Vector(0, 1, 0), Vector(-1, 0, 0), Vector(0, 0, 1)),
Matrix(Vector(0, 0, -1), Vector(-1, 0, 0), Vector(0, 1, 0)),
Matrix(Vector(0, -1, 0), Vector(-1, 0, 0), Vector(0, 0, -1)),
Matrix(Vector(0, 0, 1), Vector(-1, 0, 0), Vector(0, -1, 0)),
////////////////
Matrix(Vector(-1, 0, 0), Vector(0, -1, 0), Vector(0, 0, 1)),
Matrix(Vector(-1, 0, 0), Vector(0, 0, 1), Vector(0, 1, 0)),
Matrix(Vector(-1, 0, 0), Vector(0, 1, 0), Vector(0, 0, -1)),
Matrix(Vector(-1, 0, 0), Vector(0, 0, -1), Vector(0, -1, 0)),
///////////////
Matrix(Vector(0, -1, 0), Vector(1, 0, 0), Vector(0, 0, 1)),
Matrix(Vector(0, 0, 1), Vector(1, 0, 0), Vector(0, 1, 0)),
Matrix(Vector(0, 1, 0), Vector(1, 0, 0), Vector(0, 0, -1)),
Matrix(Vector(0, 0, -1), Vector(1, 0, 0), Vector(0, -1, 0)),
//////////////
Matrix(Vector(0, 0, -1), Vector(0, 1, 0), Vector(1, 0, 0)),
Matrix(Vector(0, -1, 0), Vector(0, 0, -1), Vector(1, 0, 0)),
Matrix(Vector(0, 0, 1), Vector(0, -1, 0), Vector(1, 0, 0)),
Matrix(Vector(0, 1, 0), Vector(0, 0, 1), Vector(1, 0, 0)),
//////////////
Matrix(Vector(0, 0, 1), Vector(0, 1, 0), Vector(-1, 0, 0)),
Matrix(Vector(0, 1, 0), Vector(0, 0, -1), Vector(-1, 0, 0)),
Matrix(Vector(0, 0, -1), Vector(0, -1, 0), Vector(-1, 0, 0)),
Matrix(Vector(0, -1, 0), Vector(0, 0, 1), Vector(-1, 0, 0)),
]
}
}
impl Mul for Matrix {
type Output = Self;
fn mul(self, other: Self) -> Self::Output {
let line0 = Vector(
self.0 .0 * other.0 .0 + self.0 .1 * other.1 .0 + self.0 .2 * other.2 .0,
self.0 .0 * other.0 .1 + self.0 .1 * other.1 .1 + self.0 .2 * other.2 .1,
self.0 .0 * other.0 .2 + self.0 .1 * other.1 .2 + self.0 .2 * other.2 .2,
);
let line1 = Vector(
self.1 .0 * other.0 .0 + self.1 .1 * other.1 .0 + self.1 .2 * other.2 .0,
self.1 .0 * other.0 .1 + self.1 .1 * other.1 .1 + self.1 .2 * other.2 .1,
self.1 .0 * other.0 .2 + self.1 .1 * other.1 .2 + self.1 .2 * other.2 .2,
);
let line2 = Vector(
self.2 .0 * other.0 .0 + self.2 .1 * other.1 .0 + self.2 .2 * other.2 .0,
self.2 .0 * other.0 .1 + self.2 .1 * other.1 .1 + self.2 .2 * other.2 .1,
self.2 .0 * other.0 .2 + self.2 .1 * other.1 .2 + self.2 .2 * other.2 .2,
);
Self(line0, line1, line2)
}
}
impl Mul<Matrix> for Vector {
type Output = Self;
fn mul(self, matrix: Matrix) -> Self::Output {
let x = self.0 * matrix.0 .0 + self.1 * matrix.0 .1 + self.2 * matrix.0 .2;
let y = self.0 * matrix.1 .0 + self.1 * matrix.1 .1 + self.2 * matrix.1 .2;
let z = self.0 * matrix.2 .0 + self.1 * matrix.2 .1 + self.2 * matrix.2 .2;
Vector(x, y, z)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn multiplication() {
let a = Matrix(Vector(4, -8, 9), Vector(-1, 1, 3), Vector(3, 2, -1));
let b = Matrix(Vector(3, -9, 2), Vector(2, -4, 1), Vector(1, 1, -7));
let c = Matrix(Vector(5, 5, -63), Vector(2, 8, -22), Vector(12, -36, 15));
assert_eq!(a * b, c);
}
#[test]
fn examples() {
let scanners = parse(std::fs::read_to_string("res/day19-example.txt").unwrap());
let (r1, s1) =
compare(&scanners[0], &scanners[1]).expect("Scanners 0 and 1 should overlap");
assert_eq!(s1, Vector(68, -1246, -43));
let (_, s3) = compare(&scanners[1], &scanners[3]).expect("Scanners 1 and 3 should overlap");
let p3 = s3 * r1 + s1;
assert_eq!(p3, Vector(-92, -2380, -20));
let (r4, s4) =
compare(&scanners[1], &scanners[4]).expect("Scanners 1 and 4 should overlap");
let p4 = s4 * r1 + s1;
assert_eq!(p4, Vector(-20, -1133, 1061));
let (_, s2) = compare(&scanners[4], &scanners[2]).expect("Scanners 2 and 4 should overlap");
let p2 = s2 * r4 * r1 + p4;
assert_eq!(p2, Vector(1105, -1205, 1229));
assert_eq!(part1(&scanners), 79);
assert_eq!(part2(&scanners), 3621);
}
}
| 33.157191 | 100 | 0.507262 |
64cf00e54c85354829a9bfa14c85de1ac84d3c08 | 10,779 | use binary_derive::WasmBinary;
use ordered_float::OrderedFloat;
use crate::{BlockType, FunctionType, GlobalType, Idx, Label, Memarg, MemoryType, RawCustomSection, TableType, ValType, WasmBinary};
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Module {
pub sections: Vec<Section>,
}
/// Just a marker; does not save the size itself since that changes during transformations anyway.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct WithSize<T>(pub T);
/// Just a marker to indicate that parallel decoding/encoding is possible.
#[derive(Debug, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct Parallel<T>(pub T);
/* Sections */
#[derive(WasmBinary, Debug, Clone, Eq, PartialEq, Hash)]
pub enum Section {
#[tag = 0] Custom(CustomSection),
#[tag = 1] Type(WithSize<Vec<FunctionType>>),
#[tag = 2] Import(WithSize<Vec<Import>>),
#[tag = 3] Function(WithSize<Vec<Idx<FunctionType>>>),
#[tag = 4] Table(WithSize<Vec<TableType>>),
#[tag = 5] Memory(WithSize<Vec<MemoryType>>),
#[tag = 6] Global(WithSize<Vec<Global>>),
#[tag = 7] Export(WithSize<Vec<Export>>),
#[tag = 8] Start(WithSize<Idx<Function>>),
#[tag = 9] Element(WithSize<Vec<Element>>),
#[tag = 10] Code(WithSize<Parallel<Vec<WithSize<Code>>>>),
// Exchange with the following line to disable parallel decoding of code section (instructions).
// #[tag = 10] Code(WithSize<Vec<WithSize<Code>>>),
#[tag = 11] Data(WithSize<Vec<Data>>),
}
#[derive(WasmBinary, Debug, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct Global {
pub type_: GlobalType,
pub init: Expr,
}
#[derive(WasmBinary, Debug, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct Element {
// always 0x00 in WASM version 1
pub table_idx: Idx<Table>,
pub offset: Expr,
pub init: Vec<Idx<Function>>,
}
#[derive(WasmBinary, Debug, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct Data {
// always 0x00 in WASM version 1
pub memory_idx: Idx<Memory>,
pub offset: Expr,
pub init: Vec<u8>,
}
#[derive(WasmBinary, Debug, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct Import {
pub module: String,
pub name: String,
pub type_: ImportType,
}
#[derive(WasmBinary, Debug, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct Export {
pub name: String,
pub type_: ExportType,
}
#[derive(WasmBinary, Debug, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub enum ImportType {
#[tag = 0x0] Function(Idx<FunctionType>),
#[tag = 0x1] Table(TableType),
#[tag = 0x2] Memory(MemoryType),
#[tag = 0x3] Global(GlobalType),
}
#[derive(WasmBinary, Debug, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub enum ExportType {
#[tag = 0x0] Function(Idx<Function>),
#[tag = 0x1] Table(Idx<Table>),
#[tag = 0x2] Memory(Idx<Memory>),
#[tag = 0x3] Global(Idx<Global>),
}
// Markers for Idx<T>, since in low-level format Function, Table, and Memory have not one type,
// but are split over multiple sections.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct Function;
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct Table;
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct Memory;
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct Local;
/* Code */
#[derive(WasmBinary, Debug, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct Code {
pub locals: Vec<Locals>,
pub body: Expr,
}
#[derive(WasmBinary, Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct Locals {
pub count: u32,
pub type_: ValType,
}
#[derive(Debug, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct Expr(pub Vec<Instr>);
#[derive(WasmBinary, Debug, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub enum Instr {
#[tag = 0x00] Unreachable,
#[tag = 0x01] Nop,
// NOTE block nesting is handled by Expr::decode
#[tag = 0x02] Block(BlockType),
#[tag = 0x03] Loop(BlockType),
#[tag = 0x04] If(BlockType),
#[tag = 0x05] Else,
#[tag = 0x0b] End,
#[tag = 0x0c] Br(Label),
#[tag = 0x0d] BrIf(Label),
#[tag = 0x0e] BrTable { table: Vec<Label>, default: Label },
#[tag = 0x0f] Return,
#[tag = 0x10] Call(Idx<Function>),
#[tag = 0x11] CallIndirect(Idx<FunctionType>, /* unused, always 0x00 in WASM version 1 */ Idx<Table>),
#[tag = 0x1a] Drop,
#[tag = 0x1b] Select,
#[tag = 0x20] LocalGet(Idx<Local>),
#[tag = 0x21] LocalSet(Idx<Local>),
#[tag = 0x22] LocalTee(Idx<Local>),
#[tag = 0x23] GlobalGet(Idx<Global>),
#[tag = 0x24] GlobalSet(Idx<Global>),
#[tag = 0x28] I32Load(Memarg),
#[tag = 0x29] I64Load(Memarg),
#[tag = 0x2a] F32Load(Memarg),
#[tag = 0x2b] F64Load(Memarg),
#[tag = 0x2c] I32Load8S(Memarg),
#[tag = 0x2d] I32Load8U(Memarg),
#[tag = 0x2e] I32Load16S(Memarg),
#[tag = 0x2f] I32Load16U(Memarg),
#[tag = 0x30] I64Load8S(Memarg),
#[tag = 0x31] I64Load8U(Memarg),
#[tag = 0x32] I64Load16S(Memarg),
#[tag = 0x33] I64Load16U(Memarg),
#[tag = 0x34] I64Load32S(Memarg),
#[tag = 0x35] I64Load32U(Memarg),
#[tag = 0x36] I32Store(Memarg),
#[tag = 0x37] I64Store(Memarg),
#[tag = 0x38] F32Store(Memarg),
#[tag = 0x39] F64Store(Memarg),
#[tag = 0x3a] I32Store8(Memarg),
#[tag = 0x3b] I32Store16(Memarg),
#[tag = 0x3c] I64Store8(Memarg),
#[tag = 0x3d] I64Store16(Memarg),
#[tag = 0x3e] I64Store32(Memarg),
#[tag = 0x3f] MemorySize(/* unused, always 0x00 in WASM version 1 */ Idx<Memory>),
#[tag = 0x40] MemoryGrow(/* unused, always 0x00 in WASM version 1 */ Idx<Memory>),
#[tag = 0x41] I32Const(i32),
#[tag = 0x42] I64Const(i64),
// Wrap floats, such that they can be ordered and compared (unlike IEEE754 floats),
// to make it possible, e.g., to put instructions in HashSets etc.
#[tag = 0x43] F32Const(OrderedFloat<f32>),
#[tag = 0x44] F64Const(OrderedFloat<f64>),
#[tag = 0x45] I32Eqz,
#[tag = 0x46] I32Eq,
#[tag = 0x47] I32Ne,
#[tag = 0x48] I32LtS,
#[tag = 0x49] I32LtU,
#[tag = 0x4a] I32GtS,
#[tag = 0x4b] I32GtU,
#[tag = 0x4c] I32LeS,
#[tag = 0x4d] I32LeU,
#[tag = 0x4e] I32GeS,
#[tag = 0x4f] I32GeU,
#[tag = 0x50] I64Eqz,
#[tag = 0x51] I64Eq,
#[tag = 0x52] I64Ne,
#[tag = 0x53] I64LtS,
#[tag = 0x54] I64LtU,
#[tag = 0x55] I64GtS,
#[tag = 0x56] I64GtU,
#[tag = 0x57] I64LeS,
#[tag = 0x58] I64LeU,
#[tag = 0x59] I64GeS,
#[tag = 0x5a] I64GeU,
#[tag = 0x5b] F32Eq,
#[tag = 0x5c] F32Ne,
#[tag = 0x5d] F32Lt,
#[tag = 0x5e] F32Gt,
#[tag = 0x5f] F32Le,
#[tag = 0x60] F32Ge,
#[tag = 0x61] F64Eq,
#[tag = 0x62] F64Ne,
#[tag = 0x63] F64Lt,
#[tag = 0x64] F64Gt,
#[tag = 0x65] F64Le,
#[tag = 0x66] F64Ge,
#[tag = 0x67] I32Clz,
#[tag = 0x68] I32Ctz,
#[tag = 0x69] I32Popcnt,
#[tag = 0x6a] I32Add,
#[tag = 0x6b] I32Sub,
#[tag = 0x6c] I32Mul,
#[tag = 0x6d] I32DivS,
#[tag = 0x6e] I32DivU,
#[tag = 0x6f] I32RemS,
#[tag = 0x70] I32RemU,
#[tag = 0x71] I32And,
#[tag = 0x72] I32Or,
#[tag = 0x73] I32Xor,
#[tag = 0x74] I32Shl,
#[tag = 0x75] I32ShrS,
#[tag = 0x76] I32ShrU,
#[tag = 0x77] I32Rotl,
#[tag = 0x78] I32Rotr,
#[tag = 0x79] I64Clz,
#[tag = 0x7a] I64Ctz,
#[tag = 0x7b] I64Popcnt,
#[tag = 0x7c] I64Add,
#[tag = 0x7d] I64Sub,
#[tag = 0x7e] I64Mul,
#[tag = 0x7f] I64DivS,
#[tag = 0x80] I64DivU,
#[tag = 0x81] I64RemS,
#[tag = 0x82] I64RemU,
#[tag = 0x83] I64And,
#[tag = 0x84] I64Or,
#[tag = 0x85] I64Xor,
#[tag = 0x86] I64Shl,
#[tag = 0x87] I64ShrS,
#[tag = 0x88] I64ShrU,
#[tag = 0x89] I64Rotl,
#[tag = 0x8a] I64Rotr,
#[tag = 0x8b] F32Abs,
#[tag = 0x8c] F32Neg,
#[tag = 0x8d] F32Ceil,
#[tag = 0x8e] F32Floor,
#[tag = 0x8f] F32Trunc,
#[tag = 0x90] F32Nearest,
#[tag = 0x91] F32Sqrt,
#[tag = 0x92] F32Add,
#[tag = 0x93] F32Sub,
#[tag = 0x94] F32Mul,
#[tag = 0x95] F32Div,
#[tag = 0x96] F32Min,
#[tag = 0x97] F32Max,
#[tag = 0x98] F32Copysign,
#[tag = 0x99] F64Abs,
#[tag = 0x9a] F64Neg,
#[tag = 0x9b] F64Ceil,
#[tag = 0x9c] F64Floor,
#[tag = 0x9d] F64Trunc,
#[tag = 0x9e] F64Nearest,
#[tag = 0x9f] F64Sqrt,
#[tag = 0xa0] F64Add,
#[tag = 0xa1] F64Sub,
#[tag = 0xa2] F64Mul,
#[tag = 0xa3] F64Div,
#[tag = 0xa4] F64Min,
#[tag = 0xa5] F64Max,
#[tag = 0xa6] F64Copysign,
#[tag = 0xa7] I32WrapI64,
#[tag = 0xa8] I32TruncF32S,
#[tag = 0xa9] I32TruncF32U,
#[tag = 0xaa] I32TruncF64S,
#[tag = 0xab] I32TruncF64U,
#[tag = 0xac] I64ExtendI32S,
#[tag = 0xad] I64ExtendI32U,
#[tag = 0xae] I64TruncF32S,
#[tag = 0xaf] I64TruncF32U,
#[tag = 0xb0] I64TruncF64S,
#[tag = 0xb1] I64TruncF64U,
#[tag = 0xb2] F32ConvertI32S,
#[tag = 0xb3] F32ConvertI32U,
#[tag = 0xb4] F32ConvertI64S,
#[tag = 0xb5] F32ConvertI64U,
#[tag = 0xb6] F32DemoteF64,
#[tag = 0xb7] F64ConvertI32S,
#[tag = 0xb8] F64ConvertI32U,
#[tag = 0xb9] F64ConvertI64S,
#[tag = 0xba] F64ConvertI64U,
#[tag = 0xbb] F64PromoteF32,
#[tag = 0xbc] I32ReinterpretF32,
#[tag = 0xbd] I64ReinterpretF64,
#[tag = 0xbe] F32ReinterpretI32,
#[tag = 0xbf] F64ReinterpretI64,
}
/* Important/widely supported custom sections */
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum CustomSection {
/// If custom section name was "name".
Name(NameSection),
/// Fallback, if we cannot parse this type of custom section.
Raw(RawCustomSection),
}
// See https://webassembly.github.io/spec/core/appendix/custom.html#name-section
#[derive(Debug, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct NameSection {
// NOTE This does not inlucde the custom section name (in this case: "name"), since we know it
// from the type NameSection alone.
pub subsections: Vec<NameSubSection>
}
#[derive(WasmBinary, Debug, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub enum NameSubSection {
#[tag = 0x00] Module(WithSize<String>),
#[tag = 0x01] Function(WithSize<NameMap<Function>>),
#[tag = 0x02] Local(WithSize<IndirectNameMap<Function, Local>>),
}
pub type NameMap<T> = Vec<NameAssoc<T>>;
#[derive(WasmBinary, Debug, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct NameAssoc<T> {
pub idx: Idx<T>,
pub name: String,
}
pub type IndirectNameMap<T, U> = Vec<IndirectNameAssoc<T, U>>;
#[derive(WasmBinary, Debug, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct IndirectNameAssoc<T, U> {
pub idx: Idx<T>,
pub name_map: NameMap<U>,
}
| 30.709402 | 131 | 0.617404 |
64f2a28c7ac437bcd8ba83e88e58d9140c730fbd | 966 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust
// Zhihu: https://www.zhihu.com/people/netcan
use std::cmp::min;
impl Solution {
pub fn mincost_tickets(days: Vec<i32>, costs: Vec<i32>) -> i32 {
// dp[day]: 第day天所花费的最小票价
// dp[day] = min(dp[day-1]+costs[0], dp[day-7]+costs[1], dp[day-30]+costs[2])
let mut travel = [false; 366];
let mut dp = [0; 366];
let (first, last) = (*days.first().unwrap(), *days.last().unwrap());
for day in days { travel[day as usize] = true; }
for day in first..=last {
dp[day as usize] = if travel[day as usize] {
min(dp[(day - 1) as usize] + costs[0], min(
dp[(day - 7).max(0) as usize] + costs[1],
dp[(day - 30).max(0) as usize] + costs[2],
))
} else {
dp[(day - 1) as usize]
}
}
dp[last as usize]
}
}
| 34.5 | 85 | 0.478261 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.