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
|
---|---|---|---|---|---|
fe44da67c86aaf683e5edea6aa7ee83b227f1685 | 9,721 | // Copyright 2017 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
// Refer to https://dev.mysql.com/doc/refman/5.7/en/json-path-syntax.html
// From MySQL 5.7, JSON path expression grammar:
// pathExpression ::= scope (pathLeg)*
// scope ::= [ columnReference ] '$'
// columnReference ::= // omit...
// pathLeg ::= member | arrayLocation | '**'
// member ::= '.' (keyName | '*')
// arrayLocation ::= '[' (non-negative-integer | '*') ']'
// keyName ::= ECMAScript-identifier | ECMAScript-string-literal
//
// And some implementation limits in MySQL 5.7:
// 1) columnReference in scope must be empty now;
// 2) double asterisk(**) could not be last leg;
//
// Examples:
// select json_extract('{"a": "b", "c": [1, "2"]}', '$.a') -> "b"
// select json_extract('{"a": "b", "c": [1, "2"]}', '$.c') -> [1, "2"]
// select json_extract('{"a": "b", "c": [1, "2"]}', '$.a', '$.c') -> ["b", [1, "2"]]
// select json_extract('{"a": "b", "c": [1, "2"]}', '$.c[0]') -> 1
// select json_extract('{"a": "b", "c": [1, "2"]}', '$.c[2]') -> NULL
// select json_extract('{"a": "b", "c": [1, "2"]}', '$.c[*]') -> [1, "2"]
// select json_extract('{"a": "b", "c": [1, "2"]}', '$.*') -> ["b", [1, "2"]]
// FIXME: remove following later
#![allow(dead_code)]
use std::ops::Index;
use std::ascii::AsciiExt;
use regex::Regex;
use coprocessor::codec::Result;
use super::json_unquote::unquote_string;
pub const PATH_EXPR_ASTERISK: &'static str = "*";
// [a-zA-Z_][a-zA-Z0-9_]* matches any identifier;
// "[^"\\]*(\\.[^"\\]*)*" matches any string literal which can carry escaped quotes.
const PATH_EXPR_LEG_RE_STR: &'static str =
r#"(\.\s*([a-zA-Z_][a-zA-Z0-9_]*|\*|"[^"\\]*(\\.[^"\\]*)*")|(\[\s*([0-9]+|\*)\s*\])|\*\*)"#;
#[derive(Clone, Debug, PartialEq)]
pub enum PathLeg {
/// `Key` indicates the path leg with '.key'.
Key(String),
/// `Index` indicates the path leg with form '[number]'.
Index(i32),
/// `DoubleAsterisk` indicates the path leg with form '**'.
DoubleAsterisk,
}
// ArrayIndexAsterisk is for parsing '*' into a number.
// we need this number represent "all".
pub const PATH_EXPR_ARRAY_INDEX_ASTERISK: i32 = -1;
pub type PathExpressionFlag = u8;
pub const PATH_EXPRESSION_CONTAINS_ASTERISK: PathExpressionFlag = 0x01;
pub const PATH_EXPRESSION_CONTAINS_DOUBLE_ASTERISK: PathExpressionFlag = 0x02;
#[derive(Clone, Default, Debug, PartialEq)]
pub struct PathExpression {
pub legs: Vec<PathLeg>,
pub flags: PathExpressionFlag,
}
impl PathExpression {
pub fn contains_any_asterisk(&self) -> bool {
(self.flags &
(PATH_EXPRESSION_CONTAINS_ASTERISK | PATH_EXPRESSION_CONTAINS_DOUBLE_ASTERISK)) !=
0
}
}
/// Parses a JSON path expression. Returns a `PathExpression`
/// object which can be used in `JSON_EXTRACT`, `JSON_SET` and so on.
pub fn parse_json_path_expr(path_expr: &str) -> Result<PathExpression> {
// Find the position of first '$'. If any no-blank characters in
// path_expr[0: dollarIndex], return an error.
let dollar_index = match path_expr.find('$') {
Some(i) => i,
None => return Err(box_err!("Invalid JSON path: {}", path_expr)),
};
if path_expr
.index(0..dollar_index)
.char_indices()
.any(|(_, c)| !c.is_ascii_whitespace())
{
return Err(box_err!("Invalid JSON path: {}", path_expr));
}
let expr = path_expr.index(dollar_index + 1..).trim_left();
lazy_static! {
static ref RE: Regex = Regex::new(PATH_EXPR_LEG_RE_STR).unwrap();
}
let mut legs = vec![];
let mut flags = PathExpressionFlag::default();
let mut last_end = 0;
for (start, end) in RE.find_iter(expr) {
// Check all characters between two legs are blank.
if expr.index(last_end..start)
.char_indices()
.any(|(_, c)| !c.is_ascii_whitespace())
{
return Err(box_err!("Invalid JSON path: {}", path_expr));
}
last_end = end;
let next_char = expr.index(start..).chars().next().unwrap();
if next_char == '[' {
// The leg is an index of a JSON array.
let leg = expr[start + 1..end].trim();
let index_str = leg[0..leg.len() - 1].trim();
let index = if index_str == PATH_EXPR_ASTERISK {
flags |= PATH_EXPRESSION_CONTAINS_ASTERISK;
PATH_EXPR_ARRAY_INDEX_ASTERISK
} else {
box_try!(index_str.parse::<i32>())
};
legs.push(PathLeg::Index(index))
} else if next_char == '.' {
// The leg is a key of a JSON object.
let mut key = expr[start + 1..end].trim().to_owned();
if key == PATH_EXPR_ASTERISK {
flags |= PATH_EXPRESSION_CONTAINS_ASTERISK;
} else if key.chars().next().unwrap() == '"' {
// We need to unquote the origin string.
key = unquote_string(&key[1..key.len() - 1])?;
}
legs.push(PathLeg::Key(key))
} else {
// The leg is '**'.
flags |= PATH_EXPRESSION_CONTAINS_DOUBLE_ASTERISK;
legs.push(PathLeg::DoubleAsterisk);
}
}
// Check `!expr.is_empty()` here because "$" is a valid path to specify the current JSON.
if (last_end == 0) && (!expr.is_empty()) {
return Err(box_err!("Invalid JSON path: {}", path_expr));
}
if !legs.is_empty() {
if let PathLeg::DoubleAsterisk = *legs.last().unwrap() {
// The last leg of a path expression cannot be '**'.
return Err(box_err!("Invalid JSON path: {}", path_expr));
}
}
Ok(PathExpression {
legs: legs,
flags: flags,
})
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_path_expression_flag() {
let mut e = PathExpression {
legs: vec![],
flags: PathExpressionFlag::default(),
};
assert!(!e.contains_any_asterisk());
e.flags |= PATH_EXPRESSION_CONTAINS_ASTERISK;
assert!(e.contains_any_asterisk());
e.flags = PathExpressionFlag::default();
e.flags |= PATH_EXPRESSION_CONTAINS_DOUBLE_ASTERISK;
assert!(e.contains_any_asterisk());
}
#[test]
fn test_parse_json_path_expr() {
let mut test_cases = vec![
(
"$",
true,
Some(PathExpression {
legs: vec![],
flags: PathExpressionFlag::default(),
}),
),
(
"$.a",
true,
Some(PathExpression {
legs: vec![PathLeg::Key(String::from("a"))],
flags: PathExpressionFlag::default(),
}),
),
(
"$.\"hello world\"",
true,
Some(PathExpression {
legs: vec![PathLeg::Key(String::from("hello world"))],
flags: PathExpressionFlag::default(),
}),
),
(
"$[0]",
true,
Some(PathExpression {
legs: vec![PathLeg::Index(0)],
flags: PathExpressionFlag::default(),
}),
),
(
"$**.a",
true,
Some(PathExpression {
legs: vec![PathLeg::DoubleAsterisk, PathLeg::Key(String::from("a"))],
flags: PATH_EXPRESSION_CONTAINS_DOUBLE_ASTERISK,
}),
),
// invalid path expressions
(".a", false, None),
("xx$[1]", false, None),
("$.a xx .b", false, None),
("$[a]", false, None),
("$.\"\\u33\"", false, None),
("$**", false, None),
];
for (i, (path_expr, no_error, expected)) in test_cases.drain(..).enumerate() {
let r = parse_json_path_expr(path_expr);
if no_error {
assert!(r.is_ok(), "#{} expect parse ok but got err {:?}", i, r);
let got = r.unwrap();
let expected = expected.unwrap();
assert_eq!(
got,
expected,
"#{} expect {:?} but got {:?}",
i,
expected,
got
);
} else {
assert!(r.is_err(), "#{} expect error but got {:?}", i, r);
}
}
}
#[test]
fn test_parse_json_path_expr_contains_any_asterisk() {
let mut test_cases = vec![
("$.a[b]", false),
("$.a[*]", true),
("$.*[b]", true),
("$**.a[b]", true),
];
for (i, (path_expr, expected)) in test_cases.drain(..).enumerate() {
let r = parse_json_path_expr(path_expr);
assert!(r.is_ok(), "#{} expect parse ok but got err {:?}", i, r);
let e = r.unwrap();
let b = e.contains_any_asterisk();
assert_eq!(b, expected, "#{} expect {:?} but got {:?}", i, expected, b);
}
}
}
| 35.738971 | 96 | 0.517951 |
d660f9aa97ac2da50dbc3c980f26aec8aadf43fc | 121,873 | #![allow(clippy::integer_arithmetic)]
#[cfg(not(target_env = "msvc"))]
use jemallocator::Jemalloc;
use {
clap::{
crate_description, crate_name, value_t, value_t_or_exit, values_t, values_t_or_exit, App,
AppSettings, Arg, ArgMatches, SubCommand,
},
console::style,
log::*,
rand::{seq::SliceRandom, thread_rng, Rng},
solana_clap_utils::{
input_parsers::{keypair_of, keypairs_of, pubkey_of, value_of},
input_validators::{
is_keypair, is_keypair_or_ask_keyword, is_niceness_adjustment_valid, is_parsable,
is_pubkey, is_pubkey_or_keypair, is_slot, is_valid_percentage,
},
keypair::SKIP_SEED_PHRASE_VALIDATION_ARG,
},
solana_client::{
rpc_client::RpcClient, rpc_config::RpcLeaderScheduleConfig,
rpc_request::MAX_MULTIPLE_ACCOUNTS,
},
solana_core::{
ledger_cleanup_service::{DEFAULT_MAX_LEDGER_SHREDS, DEFAULT_MIN_MAX_LEDGER_SHREDS},
tpu::DEFAULT_TPU_COALESCE_MS,
validator::{
is_snapshot_config_invalid, Validator, ValidatorConfig, ValidatorStartProgress,
},
},
solana_download_utils::{download_snapshot, DownloadProgressRecord},
renec_genesis_utils::download_then_check_genesis_hash,
solana_gossip::{
cluster_info::{ClusterInfo, Node, VALIDATOR_PORT_RANGE},
contact_info::ContactInfo,
gossip_service::GossipService,
},
solana_ledger::blockstore_db::BlockstoreRecoveryMode,
solana_perf::recycler::enable_recycler_warming,
solana_poh::poh_service,
solana_rpc::{rpc::JsonRpcConfig, rpc_pubsub_service::PubSubConfig, send_transaction_service},
solana_runtime::{
accounts_db::{
AccountShrinkThreshold, DEFAULT_ACCOUNTS_SHRINK_OPTIMIZE_TOTAL_SPACE,
DEFAULT_ACCOUNTS_SHRINK_RATIO,
},
accounts_index::{
AccountIndex, AccountSecondaryIndexes, AccountSecondaryIndexesIncludeExclude,
},
bank_forks::{ArchiveFormat, SnapshotConfig, SnapshotVersion},
hardened_unpack::MAX_GENESIS_ARCHIVE_UNPACKED_SIZE,
snapshot_utils::{get_highest_snapshot_archive_path, DEFAULT_MAX_SNAPSHOTS_TO_RETAIN},
},
solana_sdk::{
clock::{Slot, DEFAULT_S_PER_SLOT},
commitment_config::CommitmentConfig,
hash::Hash,
pubkey::Pubkey,
signature::{Keypair, Signer},
},
solana_streamer::socket::SocketAddrSpace,
renec_validator::{
admin_rpc_service, dashboard::Dashboard, ledger_lockfile, lock_ledger,
new_spinner_progress_bar, println_name_value, redirect_stderr_to_file,
},
std::{
collections::{HashSet, VecDeque},
env,
fs::{self, File},
net::{IpAddr, SocketAddr, TcpListener, UdpSocket},
path::{Path, PathBuf},
process::exit,
str::FromStr,
sync::{
atomic::{AtomicBool, Ordering},
Arc, RwLock,
},
thread::sleep,
time::{Duration, Instant, SystemTime},
},
};
#[cfg(not(target_env = "msvc"))]
#[global_allocator]
static GLOBAL: Jemalloc = Jemalloc;
#[derive(Debug, PartialEq)]
enum Operation {
Initialize,
Run,
}
const EXCLUDE_KEY: &str = "account-index-exclude-key";
const INCLUDE_KEY: &str = "account-index-include-key";
// The default minimal snapshot download speed (bytes/second)
const DEFAULT_MIN_SNAPSHOT_DOWNLOAD_SPEED: u64 = 10485760;
// The maximum times of snapshot download abort and retry
const MAX_SNAPSHOT_DOWNLOAD_ABORT: u32 = 5;
fn monitor_validator(ledger_path: &Path) {
let dashboard = Dashboard::new(ledger_path, None, None).unwrap_or_else(|err| {
println!(
"Error: Unable to connect to validator at {}: {:?}",
ledger_path.display(),
err,
);
exit(1);
});
dashboard.run(Duration::from_secs(2));
}
fn wait_for_restart_window(
ledger_path: &Path,
identity: Option<Pubkey>,
min_idle_time_in_minutes: usize,
max_delinquency_percentage: u8,
) -> Result<(), Box<dyn std::error::Error>> {
let sleep_interval = Duration::from_secs(5);
let min_idle_slots = (min_idle_time_in_minutes as f64 * 60. / DEFAULT_S_PER_SLOT) as Slot;
let admin_client = admin_rpc_service::connect(ledger_path);
let rpc_addr = admin_rpc_service::runtime()
.block_on(async move { admin_client.await?.rpc_addr().await })
.map_err(|err| format!("Unable to get validator RPC address: {}", err))?;
let rpc_client = match rpc_addr {
None => return Err("RPC not available".into()),
Some(rpc_addr) => RpcClient::new_socket(rpc_addr),
};
let my_identity = rpc_client.get_identity()?;
let identity = identity.unwrap_or(my_identity);
let monitoring_another_validator = identity != my_identity;
println_name_value("Identity:", &identity.to_string());
println_name_value(
"Minimum Idle Time:",
&format!(
"{} slots (~{} minutes)",
min_idle_slots, min_idle_time_in_minutes
),
);
println!(
"Maximum permitted delinquency: {}%",
max_delinquency_percentage
);
let mut current_epoch = None;
let mut leader_schedule = VecDeque::new();
let mut restart_snapshot = None;
let mut upcoming_idle_windows = vec![]; // Vec<(starting slot, idle window length in slots)>
let progress_bar = new_spinner_progress_bar();
let monitor_start_time = SystemTime::now();
loop {
let snapshot_slot = rpc_client.get_snapshot_slot().ok();
let epoch_info = rpc_client.get_epoch_info_with_commitment(CommitmentConfig::processed())?;
let healthy = rpc_client.get_health().ok().is_some();
let delinquent_stake_percentage = {
let vote_accounts = rpc_client.get_vote_accounts()?;
let current_stake: u64 = vote_accounts
.current
.iter()
.map(|va| va.activated_stake)
.sum();
let delinquent_stake: u64 = vote_accounts
.delinquent
.iter()
.map(|va| va.activated_stake)
.sum();
let total_stake = current_stake + delinquent_stake;
delinquent_stake as f64 / total_stake as f64
};
if match current_epoch {
None => true,
Some(current_epoch) => current_epoch != epoch_info.epoch,
} {
progress_bar.set_message(&format!(
"Fetching leader schedule for epoch {}...",
epoch_info.epoch
));
let first_slot_in_epoch = epoch_info.absolute_slot - epoch_info.slot_index;
leader_schedule = rpc_client
.get_leader_schedule_with_config(
Some(first_slot_in_epoch),
RpcLeaderScheduleConfig {
identity: Some(identity.to_string()),
..RpcLeaderScheduleConfig::default()
},
)?
.ok_or_else(|| {
format!(
"Unable to get leader schedule from slot {}",
first_slot_in_epoch
)
})?
.get(&identity.to_string())
.cloned()
.unwrap_or_default()
.into_iter()
.map(|slot_index| first_slot_in_epoch.saturating_add(slot_index as u64))
.filter(|slot| *slot > epoch_info.absolute_slot)
.collect::<VecDeque<_>>();
upcoming_idle_windows.clear();
{
let mut leader_schedule = leader_schedule.clone();
let mut max_idle_window = 0;
let mut idle_window_start_slot = epoch_info.absolute_slot;
while let Some(next_leader_slot) = leader_schedule.pop_front() {
let idle_window = next_leader_slot - idle_window_start_slot;
max_idle_window = max_idle_window.max(idle_window);
if idle_window > min_idle_slots {
upcoming_idle_windows.push((idle_window_start_slot, idle_window));
}
idle_window_start_slot = next_leader_slot;
}
if !leader_schedule.is_empty() && upcoming_idle_windows.is_empty() {
return Err(format!(
"Validator has no idle window of at least {} slots. Largest idle window for epoch {} is {} slots",
min_idle_slots, epoch_info.epoch, max_idle_window
)
.into());
}
}
current_epoch = Some(epoch_info.epoch);
}
let status = {
if !healthy {
style("Node is unhealthy").red().to_string()
} else {
// Wait until a hole in the leader schedule before restarting the node
let in_leader_schedule_hole = if epoch_info.slot_index + min_idle_slots as u64
> epoch_info.slots_in_epoch
{
Err("Current epoch is almost complete".to_string())
} else {
while leader_schedule
.get(0)
.map(|slot| *slot < epoch_info.absolute_slot)
.unwrap_or(false)
{
leader_schedule.pop_front();
}
while upcoming_idle_windows
.get(0)
.map(|(slot, _)| *slot < epoch_info.absolute_slot)
.unwrap_or(false)
{
upcoming_idle_windows.pop();
}
match leader_schedule.get(0) {
None => {
Ok(()) // Validator has no leader slots
}
Some(next_leader_slot) => {
let idle_slots =
next_leader_slot.saturating_sub(epoch_info.absolute_slot);
if idle_slots >= min_idle_slots {
Ok(())
} else {
Err(match upcoming_idle_windows.get(0) {
Some((starting_slot, length_in_slots)) => {
format!(
"Next idle window in {} slots, for {} slots",
starting_slot.saturating_sub(epoch_info.absolute_slot),
length_in_slots
)
}
None => format!(
"Validator will be leader soon. Next leader slot is {}",
next_leader_slot
),
})
}
}
}
};
match in_leader_schedule_hole {
Ok(_) => {
if restart_snapshot == None {
restart_snapshot = snapshot_slot;
}
if restart_snapshot == snapshot_slot && !monitoring_another_validator {
"Waiting for a new snapshot".to_string()
} else if delinquent_stake_percentage
>= (max_delinquency_percentage as f64 / 100.)
{
style("Delinquency too high").red().to_string()
} else {
break; // Restart!
}
}
Err(why) => style(why).yellow().to_string(),
}
}
};
progress_bar.set_message(&format!(
"{} | Processed Slot: {} {} | {:.2}% delinquent stake | {}",
{
let elapsed =
chrono::Duration::from_std(monitor_start_time.elapsed().unwrap()).unwrap();
format!(
"{:02}:{:02}:{:02}",
elapsed.num_hours(),
elapsed.num_minutes() % 60,
elapsed.num_seconds() % 60
)
},
epoch_info.absolute_slot,
if monitoring_another_validator {
"".to_string()
} else {
format!(
"| Snapshot Slot: {}",
snapshot_slot
.map(|s| s.to_string())
.unwrap_or_else(|| "-".to_string())
)
},
delinquent_stake_percentage * 100.,
status
));
std::thread::sleep(sleep_interval);
}
drop(progress_bar);
println!("{}", style("Ready to restart").green());
Ok(())
}
fn hash_validator(hash: String) -> Result<(), String> {
Hash::from_str(&hash)
.map(|_| ())
.map_err(|e| format!("{:?}", e))
}
fn is_known_validator(id: &Pubkey, known_validators: &Option<HashSet<Pubkey>>) -> bool {
if let Some(known_validators) = known_validators {
known_validators.contains(id)
} else {
false
}
}
fn get_trusted_snapshot_hashes(
cluster_info: &ClusterInfo,
known_validators: &Option<HashSet<Pubkey>>,
) -> Option<HashSet<(Slot, Hash)>> {
if let Some(known_validators) = known_validators {
let mut trusted_snapshot_hashes = HashSet::new();
for known_validator in known_validators {
cluster_info.get_snapshot_hash_for_node(known_validator, |snapshot_hashes| {
for snapshot_hash in snapshot_hashes {
trusted_snapshot_hashes.insert(*snapshot_hash);
}
});
}
Some(trusted_snapshot_hashes)
} else {
None
}
}
fn start_gossip_node(
identity_keypair: &Arc<Keypair>,
cluster_entrypoints: &[ContactInfo],
ledger_path: &Path,
gossip_addr: &SocketAddr,
gossip_socket: UdpSocket,
expected_shred_version: Option<u16>,
gossip_validators: Option<HashSet<Pubkey>>,
should_check_duplicate_instance: bool,
socket_addr_space: SocketAddrSpace,
) -> (Arc<ClusterInfo>, Arc<AtomicBool>, GossipService) {
let mut cluster_info = ClusterInfo::new(
ClusterInfo::gossip_contact_info(
&identity_keypair.pubkey(),
*gossip_addr,
expected_shred_version.unwrap_or(0),
),
identity_keypair.clone(),
socket_addr_space,
);
cluster_info.set_entrypoints(cluster_entrypoints.to_vec());
cluster_info.restore_contact_info(ledger_path, 0);
let cluster_info = Arc::new(cluster_info);
let gossip_exit_flag = Arc::new(AtomicBool::new(false));
let gossip_service = GossipService::new(
&cluster_info,
None,
gossip_socket,
gossip_validators,
should_check_duplicate_instance,
&gossip_exit_flag,
);
(cluster_info, gossip_exit_flag, gossip_service)
}
fn get_rpc_node(
cluster_info: &ClusterInfo,
cluster_entrypoints: &[ContactInfo],
validator_config: &ValidatorConfig,
blacklisted_rpc_nodes: &mut HashSet<Pubkey>,
snapshot_not_required: bool,
only_known_rpc: bool,
snapshot_output_dir: &Path,
) -> Option<(ContactInfo, Option<(Slot, Hash)>)> {
let mut blacklist_timeout = Instant::now();
let mut newer_cluster_snapshot_timeout = None;
let mut retry_reason = None;
loop {
sleep(Duration::from_secs(1));
info!("\n{}", cluster_info.rpc_info_trace());
let shred_version = validator_config
.expected_shred_version
.unwrap_or_else(|| cluster_info.my_shred_version());
if shred_version == 0 {
let all_zero_shred_versions = cluster_entrypoints.iter().all(|cluster_entrypoint| {
cluster_info
.lookup_contact_info_by_gossip_addr(&cluster_entrypoint.gossip)
.map_or(false, |entrypoint| entrypoint.shred_version == 0)
});
if all_zero_shred_versions {
eprintln!(
"Entrypoint shred version is zero. Restart with --expected-shred-version"
);
exit(1);
}
info!("Waiting to adopt entrypoint shred version...");
continue;
}
info!(
"Searching for an RPC service with shred version {}{}...",
shred_version,
retry_reason
.as_ref()
.map(|s| format!(" (Retrying: {})", s))
.unwrap_or_default()
);
let rpc_peers = cluster_info
.all_rpc_peers()
.into_iter()
.filter(|contact_info| contact_info.shred_version == shred_version)
.collect::<Vec<_>>();
let rpc_peers_total = rpc_peers.len();
// Filter out blacklisted nodes
let rpc_peers: Vec<_> = rpc_peers
.into_iter()
.filter(|rpc_peer| !blacklisted_rpc_nodes.contains(&rpc_peer.id))
.collect();
let rpc_peers_blacklisted = rpc_peers_total - rpc_peers.len();
let rpc_peers_trusted = rpc_peers
.iter()
.filter(|rpc_peer| is_known_validator(&rpc_peer.id, &validator_config.known_validators))
.count();
info!(
"Total {} RPC nodes found. {} known, {} blacklisted ",
rpc_peers_total, rpc_peers_trusted, rpc_peers_blacklisted
);
if rpc_peers_blacklisted == rpc_peers_total {
retry_reason = if !blacklisted_rpc_nodes.is_empty()
&& blacklist_timeout.elapsed().as_secs() > 60
{
// If all nodes are blacklisted and no additional nodes are discovered after 60 seconds,
// remove the blacklist and try them all again
blacklisted_rpc_nodes.clear();
Some("Blacklist timeout expired".to_owned())
} else {
Some("Wait for known rpc peers".to_owned())
};
continue;
}
blacklist_timeout = Instant::now();
let mut highest_snapshot_hash: Option<(Slot, Hash)> =
get_highest_snapshot_archive_path(snapshot_output_dir)
.map(|(_path, (slot, hash, _compression))| (slot, hash));
let eligible_rpc_peers = if snapshot_not_required {
rpc_peers
} else {
let trusted_snapshot_hashes =
get_trusted_snapshot_hashes(cluster_info, &validator_config.known_validators);
let mut eligible_rpc_peers = vec![];
for rpc_peer in rpc_peers.iter() {
if only_known_rpc
&& !is_known_validator(&rpc_peer.id, &validator_config.known_validators)
{
continue;
}
cluster_info.get_snapshot_hash_for_node(&rpc_peer.id, |snapshot_hashes| {
for snapshot_hash in snapshot_hashes {
if let Some(ref trusted_snapshot_hashes) = trusted_snapshot_hashes {
if !trusted_snapshot_hashes.contains(snapshot_hash) {
// Ignore all untrusted snapshot hashes
continue;
}
}
if highest_snapshot_hash.is_none()
|| snapshot_hash.0 > highest_snapshot_hash.unwrap().0
{
// Found a higher snapshot, remove all nodes with a lower snapshot
eligible_rpc_peers.clear();
highest_snapshot_hash = Some(*snapshot_hash)
}
if Some(*snapshot_hash) == highest_snapshot_hash {
eligible_rpc_peers.push(rpc_peer.clone());
}
}
});
}
match highest_snapshot_hash {
None => {
assert!(eligible_rpc_peers.is_empty());
}
Some(highest_snapshot_hash) => {
if eligible_rpc_peers.is_empty() {
match newer_cluster_snapshot_timeout {
None => newer_cluster_snapshot_timeout = Some(Instant::now()),
Some(newer_cluster_snapshot_timeout) => {
if newer_cluster_snapshot_timeout.elapsed().as_secs() > 180 {
warn!("giving up newer snapshot from the cluster");
return None;
}
}
}
retry_reason = Some(format!(
"Wait for newer snapshot than local: {:?}",
highest_snapshot_hash
));
continue;
}
info!(
"Highest available snapshot slot is {}, available from {} node{}: {:?}",
highest_snapshot_hash.0,
eligible_rpc_peers.len(),
if eligible_rpc_peers.len() > 1 {
"s"
} else {
""
},
eligible_rpc_peers
.iter()
.map(|contact_info| contact_info.id)
.collect::<Vec<_>>()
);
}
}
eligible_rpc_peers
};
if !eligible_rpc_peers.is_empty() {
let contact_info =
&eligible_rpc_peers[thread_rng().gen_range(0, eligible_rpc_peers.len())];
return Some((contact_info.clone(), highest_snapshot_hash));
} else {
retry_reason = Some("No snapshots available".to_owned());
}
}
}
fn check_vote_account(
rpc_client: &RpcClient,
identity_pubkey: &Pubkey,
vote_account_address: &Pubkey,
authorized_voter_pubkeys: &[Pubkey],
) -> Result<(), String> {
let vote_account = rpc_client
.get_account_with_commitment(vote_account_address, CommitmentConfig::confirmed())
.map_err(|err| format!("failed to fetch vote account: {}", err.to_string()))?
.value
.ok_or_else(|| format!("vote account does not exist: {}", vote_account_address))?;
if vote_account.owner != solana_vote_program::id() {
return Err(format!(
"not a vote account (owned by {}): {}",
vote_account.owner, vote_account_address
));
}
let identity_account = rpc_client
.get_account_with_commitment(identity_pubkey, CommitmentConfig::confirmed())
.map_err(|err| format!("failed to fetch identity account: {}", err.to_string()))?
.value
.ok_or_else(|| format!("identity account does not exist: {}", identity_pubkey))?;
let vote_state = solana_vote_program::vote_state::VoteState::from(&vote_account);
if let Some(vote_state) = vote_state {
if vote_state.authorized_voters().is_empty() {
return Err("Vote account not yet initialized".to_string());
}
if vote_state.node_pubkey != *identity_pubkey {
return Err(format!(
"vote account's identity ({}) does not match the validator's identity {}).",
vote_state.node_pubkey, identity_pubkey
));
}
for (_, vote_account_authorized_voter_pubkey) in vote_state.authorized_voters().iter() {
if !authorized_voter_pubkeys.contains(vote_account_authorized_voter_pubkey) {
return Err(format!(
"authorized voter {} not available",
vote_account_authorized_voter_pubkey
));
}
}
} else {
return Err(format!(
"invalid vote account data for {}",
vote_account_address
));
}
// Maybe we can calculate minimum voting fee; rather than 1 lamport
if identity_account.lamports <= 1 {
return Err(format!(
"underfunded identity account ({}): only {} lamports available",
identity_pubkey, identity_account.lamports
));
}
Ok(())
}
// This function is duplicated in ledger-tool/src/main.rs...
fn hardforks_of(matches: &ArgMatches<'_>, name: &str) -> Option<Vec<Slot>> {
if matches.is_present(name) {
Some(values_t_or_exit!(matches, name, Slot))
} else {
None
}
}
fn validators_set(
identity_pubkey: &Pubkey,
matches: &ArgMatches<'_>,
matches_name: &str,
arg_name: &str,
) -> Option<HashSet<Pubkey>> {
if matches.is_present(matches_name) {
let validators_set: HashSet<_> = values_t_or_exit!(matches, matches_name, Pubkey)
.into_iter()
.collect();
if validators_set.contains(identity_pubkey) {
eprintln!(
"The validator's identity pubkey cannot be a {}: {}",
arg_name, identity_pubkey
);
exit(1);
}
Some(validators_set)
} else {
None
}
}
fn verify_reachable_ports(
node: &Node,
cluster_entrypoint: &ContactInfo,
validator_config: &ValidatorConfig,
socket_addr_space: &SocketAddrSpace,
) -> bool {
let mut udp_sockets = vec![&node.sockets.gossip, &node.sockets.repair];
if ContactInfo::is_valid_address(&node.info.serve_repair, socket_addr_space) {
udp_sockets.push(&node.sockets.serve_repair);
}
if ContactInfo::is_valid_address(&node.info.tpu, socket_addr_space) {
udp_sockets.extend(node.sockets.tpu.iter());
}
if ContactInfo::is_valid_address(&node.info.tpu_forwards, socket_addr_space) {
udp_sockets.extend(node.sockets.tpu_forwards.iter());
}
if ContactInfo::is_valid_address(&node.info.tpu_vote, socket_addr_space) {
udp_sockets.extend(node.sockets.tpu_vote.iter());
}
if ContactInfo::is_valid_address(&node.info.tvu, socket_addr_space) {
udp_sockets.extend(node.sockets.tvu.iter());
udp_sockets.extend(node.sockets.broadcast.iter());
udp_sockets.extend(node.sockets.retransmit_sockets.iter());
}
if ContactInfo::is_valid_address(&node.info.tvu_forwards, socket_addr_space) {
udp_sockets.extend(node.sockets.tvu_forwards.iter());
}
let mut tcp_listeners = vec![];
if let Some((rpc_addr, rpc_pubsub_addr)) = validator_config.rpc_addrs {
for (purpose, bind_addr, public_addr) in &[
("RPC", rpc_addr, &node.info.rpc),
("RPC pubsub", rpc_pubsub_addr, &node.info.rpc_pubsub),
] {
if ContactInfo::is_valid_address(public_addr, socket_addr_space) {
tcp_listeners.push((
bind_addr.port(),
TcpListener::bind(bind_addr).unwrap_or_else(|err| {
error!(
"Unable to bind to tcp {:?} for {}: {}",
bind_addr, purpose, err
);
exit(1);
}),
));
}
}
}
if let Some(ip_echo) = &node.sockets.ip_echo {
let ip_echo = ip_echo.try_clone().expect("unable to clone tcp_listener");
tcp_listeners.push((ip_echo.local_addr().unwrap().port(), ip_echo));
}
solana_net_utils::verify_reachable_ports(
&cluster_entrypoint.gossip,
tcp_listeners,
&udp_sockets,
)
}
struct RpcBootstrapConfig {
no_genesis_fetch: bool,
no_snapshot_fetch: bool,
only_known_rpc: bool,
max_genesis_archive_unpacked_size: u64,
check_vote_account: Option<String>,
}
impl Default for RpcBootstrapConfig {
fn default() -> Self {
Self {
no_genesis_fetch: true,
no_snapshot_fetch: true,
only_known_rpc: true,
max_genesis_archive_unpacked_size: MAX_GENESIS_ARCHIVE_UNPACKED_SIZE,
check_vote_account: None,
}
}
}
#[allow(clippy::too_many_arguments)]
fn rpc_bootstrap(
node: &Node,
identity_keypair: &Arc<Keypair>,
ledger_path: &Path,
snapshot_output_dir: &Path,
vote_account: &Pubkey,
authorized_voter_keypairs: Arc<RwLock<Vec<Arc<Keypair>>>>,
cluster_entrypoints: &[ContactInfo],
validator_config: &mut ValidatorConfig,
bootstrap_config: RpcBootstrapConfig,
no_port_check: bool,
use_progress_bar: bool,
maximum_local_snapshot_age: Slot,
should_check_duplicate_instance: bool,
start_progress: &Arc<RwLock<ValidatorStartProgress>>,
minimal_snapshot_download_speed: f32,
maximum_snapshot_download_abort: u64,
socket_addr_space: SocketAddrSpace,
) {
if !no_port_check {
let mut order: Vec<_> = (0..cluster_entrypoints.len()).collect();
order.shuffle(&mut thread_rng());
if order.into_iter().all(|i| {
!verify_reachable_ports(
node,
&cluster_entrypoints[i],
validator_config,
&socket_addr_space,
)
}) {
exit(1);
}
}
if bootstrap_config.no_genesis_fetch && bootstrap_config.no_snapshot_fetch {
return;
}
let mut blacklisted_rpc_nodes = HashSet::new();
let mut gossip = None;
let mut download_abort_count = 0;
loop {
if gossip.is_none() {
*start_progress.write().unwrap() = ValidatorStartProgress::SearchingForRpcService;
gossip = Some(start_gossip_node(
identity_keypair,
cluster_entrypoints,
ledger_path,
&node.info.gossip,
node.sockets.gossip.try_clone().unwrap(),
validator_config.expected_shred_version,
validator_config.gossip_validators.clone(),
should_check_duplicate_instance,
socket_addr_space,
));
}
let rpc_node_details = get_rpc_node(
&gossip.as_ref().unwrap().0,
cluster_entrypoints,
validator_config,
&mut blacklisted_rpc_nodes,
bootstrap_config.no_snapshot_fetch,
bootstrap_config.only_known_rpc,
snapshot_output_dir,
);
if rpc_node_details.is_none() {
return;
}
let (rpc_contact_info, snapshot_hash) = rpc_node_details.unwrap();
info!(
"Using RPC service from node {}: {:?}",
rpc_contact_info.id, rpc_contact_info.rpc
);
let rpc_client = RpcClient::new_socket(rpc_contact_info.rpc);
let result = match rpc_client.get_version() {
Ok(rpc_version) => {
info!("RPC node version: {}", rpc_version.solana_core);
Ok(())
}
Err(err) => Err(format!("Failed to get RPC node version: {}", err)),
}
.and_then(|_| {
let genesis_config = download_then_check_genesis_hash(
&rpc_contact_info.rpc,
ledger_path,
validator_config.expected_genesis_hash,
bootstrap_config.max_genesis_archive_unpacked_size,
bootstrap_config.no_genesis_fetch,
use_progress_bar,
);
if let Ok(genesis_config) = genesis_config {
let genesis_hash = genesis_config.hash();
if validator_config.expected_genesis_hash.is_none() {
info!("Expected genesis hash set to {}", genesis_hash);
validator_config.expected_genesis_hash = Some(genesis_hash);
}
}
if let Some(expected_genesis_hash) = validator_config.expected_genesis_hash {
// Sanity check that the RPC node is using the expected genesis hash before
// downloading a snapshot from it
let rpc_genesis_hash = rpc_client
.get_genesis_hash()
.map_err(|err| format!("Failed to get genesis hash: {}", err))?;
if expected_genesis_hash != rpc_genesis_hash {
return Err(format!(
"Genesis hash mismatch: expected {} but RPC node genesis hash is {}",
expected_genesis_hash, rpc_genesis_hash
));
}
}
if let Some(snapshot_hash) = snapshot_hash {
let mut use_local_snapshot = false;
if let Some(highest_local_snapshot_slot) =
get_highest_snapshot_archive_path(snapshot_output_dir)
.map(|(_path, (slot, _hash, _compression))| slot)
{
if highest_local_snapshot_slot
> snapshot_hash.0.saturating_sub(maximum_local_snapshot_age)
{
info!(
"Reusing local snapshot at slot {} instead \
of downloading a snapshot for slot {}",
highest_local_snapshot_slot, snapshot_hash.0
);
use_local_snapshot = true;
} else {
info!(
"Local snapshot from slot {} is too old. \
Downloading a newer snapshot for slot {}",
highest_local_snapshot_slot, snapshot_hash.0
);
}
}
if use_local_snapshot {
Ok(())
} else {
rpc_client
.get_slot_with_commitment(CommitmentConfig::finalized())
.map_err(|err| format!("Failed to get RPC node slot: {}", err))
.and_then(|slot| {
*start_progress.write().unwrap() =
ValidatorStartProgress::DownloadingSnapshot {
slot: snapshot_hash.0,
rpc_addr: rpc_contact_info.rpc,
};
info!("RPC node root slot: {}", slot);
let (cluster_info, gossip_exit_flag, gossip_service) =
gossip.take().unwrap();
cluster_info.save_contact_info();
gossip_exit_flag.store(true, Ordering::Relaxed);
let maximum_snapshots_to_retain = if let Some(snapshot_config) =
validator_config.snapshot_config.as_ref()
{
snapshot_config.maximum_snapshots_to_retain
} else {
DEFAULT_MAX_SNAPSHOTS_TO_RETAIN
};
let ret = download_snapshot(
&rpc_contact_info.rpc,
snapshot_output_dir,
snapshot_hash,
use_progress_bar,
maximum_snapshots_to_retain,
&mut Some(Box::new(|download_progress: &DownloadProgressRecord| {
debug!("Download progress: {:?}", download_progress);
if download_progress.last_throughput < minimal_snapshot_download_speed
&& download_progress.notification_count <= 1
&& download_progress.percentage_done <= 2_f32
&& download_progress.estimated_remaining_time > 60_f32
&& download_abort_count < maximum_snapshot_download_abort {
if let Some(ref known_validators) = validator_config.known_validators {
if known_validators.contains(&rpc_contact_info.id)
&& known_validators.len() == 1
&& bootstrap_config.only_known_rpc {
warn!("The snapshot download is too slow, throughput: {} < min speed {} bytes/sec, but will NOT abort \
and try a different node as it is the only known validator and the --only-known-rpc flag \
is set. \
Abort count: {}, Progress detail: {:?}",
download_progress.last_throughput, minimal_snapshot_download_speed,
download_abort_count, download_progress);
return true; // Do not abort download from the one-and-only known validator
}
}
warn!("The snapshot download is too slow, throughput: {} < min speed {} bytes/sec, will abort \
and try a different node. Abort count: {}, Progress detail: {:?}",
download_progress.last_throughput, minimal_snapshot_download_speed,
download_abort_count, download_progress);
download_abort_count += 1;
false
} else {
true
}
})),
);
gossip_service.join().unwrap();
ret
})
}
} else {
Ok(())
}
})
.map(|_| {
if let Some(url) = bootstrap_config.check_vote_account.as_ref() {
let rpc_client = RpcClient::new(url);
check_vote_account(
&rpc_client,
&identity_keypair.pubkey(),
vote_account,
&authorized_voter_keypairs
.read()
.unwrap()
.iter()
.map(|k| k.pubkey())
.collect::<Vec<_>>(),
)
.unwrap_or_else(|err| {
// Consider failures here to be more likely due to user error (eg,
// incorrect `renec-validator` command-line arguments) rather than the
// RPC node failing.
//
// Power users can always use the `--no-check-vote-account` option to
// bypass this check entirely
error!("{}", err);
exit(1);
});
}
});
if result.is_ok() {
break;
}
warn!("{}", result.unwrap_err());
if let Some(ref known_validators) = validator_config.known_validators {
if known_validators.contains(&rpc_contact_info.id) {
continue; // Never blacklist a trusted node
}
}
info!(
"Excluding {} as a future RPC candidate",
rpc_contact_info.id
);
blacklisted_rpc_nodes.insert(rpc_contact_info.id);
}
if let Some((cluster_info, gossip_exit_flag, gossip_service)) = gossip.take() {
cluster_info.save_contact_info();
gossip_exit_flag.store(true, Ordering::Relaxed);
gossip_service.join().unwrap();
}
}
fn get_cluster_shred_version(entrypoints: &[SocketAddr]) -> Option<u16> {
let entrypoints = {
let mut index: Vec<_> = (0..entrypoints.len()).collect();
index.shuffle(&mut rand::thread_rng());
index.into_iter().map(|i| &entrypoints[i])
};
for entrypoint in entrypoints {
match solana_net_utils::get_cluster_shred_version(entrypoint) {
Err(err) => eprintln!("get_cluster_shred_version failed: {}, {}", entrypoint, err),
Ok(0) => eprintln!("zero sherd-version from entrypoint: {}", entrypoint),
Ok(shred_version) => {
info!(
"obtained shred-version {} from {}",
shred_version, entrypoint
);
return Some(shred_version);
}
}
}
None
}
pub fn main() {
let default_dynamic_port_range =
&format!("{}-{}", VALIDATOR_PORT_RANGE.0, VALIDATOR_PORT_RANGE.1);
let default_genesis_archive_unpacked_size = &MAX_GENESIS_ARCHIVE_UNPACKED_SIZE.to_string();
let default_rpc_max_multiple_accounts = &MAX_MULTIPLE_ACCOUNTS.to_string();
let default_rpc_pubsub_max_active_subscriptions =
PubSubConfig::default().max_active_subscriptions.to_string();
let default_rpc_pubsub_queue_capacity_items =
PubSubConfig::default().queue_capacity_items.to_string();
let default_rpc_pubsub_queue_capacity_bytes =
PubSubConfig::default().queue_capacity_bytes.to_string();
let default_send_transaction_service_config = send_transaction_service::Config::default();
let default_rpc_send_transaction_retry_ms = default_send_transaction_service_config
.retry_rate_ms
.to_string();
let default_rpc_send_transaction_leader_forward_count = default_send_transaction_service_config
.leader_forward_count
.to_string();
let default_rpc_send_transaction_service_max_retries = default_send_transaction_service_config
.service_max_retries
.to_string();
let default_rpc_threads = num_cpus::get().to_string();
let default_max_snapshot_to_retain = &DEFAULT_MAX_SNAPSHOTS_TO_RETAIN.to_string();
let default_min_snapshot_download_speed = &DEFAULT_MIN_SNAPSHOT_DOWNLOAD_SPEED.to_string();
let default_max_snapshot_download_abort = &MAX_SNAPSHOT_DOWNLOAD_ABORT.to_string();
let default_accounts_shrink_optimize_total_space =
&DEFAULT_ACCOUNTS_SHRINK_OPTIMIZE_TOTAL_SPACE.to_string();
let default_accounts_shrink_ratio = &DEFAULT_ACCOUNTS_SHRINK_RATIO.to_string();
let matches = App::new(crate_name!()).about(crate_description!())
.version(solana_version::version!())
.setting(AppSettings::VersionlessSubcommands)
.setting(AppSettings::InferSubcommands)
.arg(
Arg::with_name(SKIP_SEED_PHRASE_VALIDATION_ARG.name)
.long(SKIP_SEED_PHRASE_VALIDATION_ARG.long)
.help(SKIP_SEED_PHRASE_VALIDATION_ARG.help),
)
.arg(
Arg::with_name("identity")
.short("i")
.long("identity")
.value_name("KEYPAIR")
.takes_value(true)
.validator(is_keypair_or_ask_keyword)
.help("Validator identity keypair"),
)
.arg(
Arg::with_name("authorized_voter_keypairs")
.long("authorized-voter")
.value_name("KEYPAIR")
.takes_value(true)
.validator(is_keypair_or_ask_keyword)
.requires("vote_account")
.multiple(true)
.help("Include an additional authorized voter keypair. \
May be specified multiple times. \
[default: the --identity keypair]"),
)
.arg(
Arg::with_name("vote_account")
.long("vote-account")
.value_name("ADDRESS")
.takes_value(true)
.validator(is_pubkey_or_keypair)
.requires("identity")
.help("Validator vote account public key. \
If unspecified voting will be disabled. \
The authorized voter for the account must either be the \
--identity keypair or with the --authorized-voter argument")
)
.arg(
Arg::with_name("init_complete_file")
.long("init-complete-file")
.value_name("FILE")
.takes_value(true)
.help("Create this file if it doesn't already exist \
once validator initialization is complete"),
)
.arg(
Arg::with_name("ledger_path")
.short("l")
.long("ledger")
.value_name("DIR")
.takes_value(true)
.required(true)
.default_value("ledger")
.help("Use DIR as ledger location"),
)
.arg(
Arg::with_name("entrypoint")
.short("n")
.long("entrypoint")
.value_name("HOST:PORT")
.takes_value(true)
.multiple(true)
.validator(solana_net_utils::is_host_port)
.help("Rendezvous with the cluster at this gossip entrypoint"),
)
.arg(
Arg::with_name("no_snapshot_fetch")
.long("no-snapshot-fetch")
.takes_value(false)
.help("Do not attempt to fetch a snapshot from the cluster, \
start from a local snapshot if present"),
)
.arg(
Arg::with_name("no_genesis_fetch")
.long("no-genesis-fetch")
.takes_value(false)
.help("Do not fetch genesis from the cluster"),
)
.arg(
Arg::with_name("no_voting")
.long("no-voting")
.takes_value(false)
.help("Launch validator without voting"),
)
.arg(
Arg::with_name("no_check_vote_account")
.long("no-check-vote-account")
.takes_value(false)
.conflicts_with("no_voting")
.requires("entrypoint")
.hidden(true)
.help("Skip the RPC vote account sanity check")
)
.arg(
Arg::with_name("check_vote_account")
.long("check-vote-account")
.takes_value(true)
.value_name("RPC_URL")
.requires("entrypoint")
.conflicts_with_all(&["no_check_vote_account", "no_voting"])
.help("Sanity check vote account state at startup. The JSON RPC endpoint at RPC_URL must expose `--full-rpc-api`")
)
.arg(
Arg::with_name("restricted_repair_only_mode")
.long("restricted-repair-only-mode")
.takes_value(false)
.help("Do not publish the Gossip, TPU, TVU or Repair Service ports causing \
the validator to operate in a limited capacity that reduces its \
exposure to the rest of the cluster. \
\
The --no-voting flag is implicit when this flag is enabled \
"),
)
.arg(
Arg::with_name("dev_halt_at_slot")
.long("dev-halt-at-slot")
.value_name("SLOT")
.validator(is_slot)
.takes_value(true)
.help("Halt the validator when it reaches the given slot"),
)
.arg(
Arg::with_name("rpc_port")
.long("rpc-port")
.value_name("PORT")
.takes_value(true)
.validator(renec_validator::port_validator)
.help("Enable JSON RPC on this port, and the next port for the RPC websocket"),
)
.arg(
Arg::with_name("minimal_rpc_api")
.long("--minimal-rpc-api")
.takes_value(false)
.hidden(true)
.help("Only expose the RPC methods required to serve snapshots to other nodes"),
)
.arg(
Arg::with_name("full_rpc_api")
.long("--full-rpc-api")
.conflicts_with("minimal_rpc_api")
.takes_value(false)
.help("Expose RPC methods for querying chain state and transaction history"),
)
.arg(
Arg::with_name("obsolete_v1_7_rpc_api")
.long("--enable-rpc-obsolete_v1_7")
.takes_value(false)
.help("Enable the obsolete RPC methods removed in v1.7"),
)
.arg(
Arg::with_name("private_rpc")
.long("--private-rpc")
.takes_value(false)
.help("Do not publish the RPC port for use by others")
)
.arg(
Arg::with_name("no_port_check")
.long("--no-port-check")
.takes_value(false)
.help("Do not perform TCP/UDP reachable port checks at start-up")
)
.arg(
Arg::with_name("enable_rpc_transaction_history")
.long("enable-rpc-transaction-history")
.takes_value(false)
.help("Enable historical transaction info over JSON RPC, \
including the 'getConfirmedBlock' API. \
This will cause an increase in disk usage and IOPS"),
)
.arg(
Arg::with_name("enable_rpc_bigtable_ledger_storage")
.long("enable-rpc-bigtable-ledger-storage")
.requires("enable_rpc_transaction_history")
.takes_value(false)
.help("Fetch historical transaction info from a BigTable instance \
as a fallback to local ledger data"),
)
.arg(
Arg::with_name("enable_bigtable_ledger_upload")
.long("enable-bigtable-ledger-upload")
.requires("enable_rpc_transaction_history")
.takes_value(false)
.help("Upload new confirmed blocks into a BigTable instance"),
)
.arg(
Arg::with_name("enable_cpi_and_log_storage")
.long("enable-cpi-and-log-storage")
.requires("enable_rpc_transaction_history")
.takes_value(false)
.help("Include CPI inner instructions and logs in the \
historical transaction info stored"),
)
.arg(
Arg::with_name("rpc_max_multiple_accounts")
.long("rpc-max-multiple-accounts")
.value_name("MAX ACCOUNTS")
.takes_value(true)
.default_value(default_rpc_max_multiple_accounts)
.help("Override the default maximum accounts accepted by \
the getMultipleAccounts JSON RPC method")
)
.arg(
Arg::with_name("health_check_slot_distance")
.long("health-check-slot-distance")
.value_name("SLOT_DISTANCE")
.takes_value(true)
.default_value("150")
.help("If --known-validators are specified, report this validator healthy \
if its latest account hash is no further behind than this number of \
slots from the latest known validator account hash. \
If no --known-validators are specified, the validator will always \
report itself to be healthy")
)
.arg(
Arg::with_name("rpc_faucet_addr")
.long("rpc-faucet-address")
.value_name("HOST:PORT")
.takes_value(true)
.validator(solana_net_utils::is_host_port)
.help("Enable the JSON RPC 'requestAirdrop' API with this faucet address."),
)
.arg(
Arg::with_name("account_paths")
.long("accounts")
.value_name("PATHS")
.takes_value(true)
.multiple(true)
.help("Comma separated persistent accounts location"),
)
.arg(
Arg::with_name("account_shrink_path")
.long("account-shrink-path")
.value_name("PATH")
.takes_value(true)
.multiple(true)
.help("Path to accounts shrink path which can hold a compacted account set."),
)
.arg(
Arg::with_name("snapshots")
.long("snapshots")
.value_name("DIR")
.takes_value(true)
.help("Use DIR as snapshot location [default: --ledger value]"),
)
.arg(
Arg::with_name("tower")
.long("tower")
.value_name("DIR")
.takes_value(true)
.help("Use DIR as tower location [default: --ledger value]"),
)
.arg(
Arg::with_name("gossip_port")
.long("gossip-port")
.value_name("PORT")
.takes_value(true)
.help("Gossip port number for the validator"),
)
.arg(
Arg::with_name("gossip_host")
.long("gossip-host")
.value_name("HOST")
.takes_value(true)
.validator(solana_net_utils::is_host)
.help("Gossip DNS name or IP address for the validator to advertise in gossip \
[default: ask --entrypoint, or 127.0.0.1 when --entrypoint is not provided]"),
)
.arg(
Arg::with_name("public_rpc_addr")
.long("public-rpc-address")
.value_name("HOST:PORT")
.takes_value(true)
.conflicts_with("private_rpc")
.validator(solana_net_utils::is_host_port)
.help("RPC address for the validator to advertise publicly in gossip. \
Useful for validators running behind a load balancer or proxy \
[default: use --rpc-bind-address / --rpc-port]"),
)
.arg(
Arg::with_name("dynamic_port_range")
.long("dynamic-port-range")
.value_name("MIN_PORT-MAX_PORT")
.takes_value(true)
.default_value(default_dynamic_port_range)
.validator(renec_validator::port_range_validator)
.help("Range to use for dynamically assigned ports"),
)
.arg(
Arg::with_name("maximum_local_snapshot_age")
.long("maximum-local-snapshot-age")
.value_name("NUMBER_OF_SLOTS")
.takes_value(true)
.default_value("500")
.help("Reuse a local snapshot if it's less than this many \
slots behind the highest snapshot available for \
download from other validators"),
)
.arg(
Arg::with_name("snapshot_interval_slots")
.long("snapshot-interval-slots")
.value_name("SNAPSHOT_INTERVAL_SLOTS")
.takes_value(true)
.default_value("100")
.help("Number of slots between generating snapshots, \
0 to disable snapshots"),
)
.arg(
Arg::with_name("maximum_snapshots_to_retain")
.long("maximum-snapshots-to-retain")
.value_name("MAXIMUM_SNAPSHOTS_TO_RETAIN")
.takes_value(true)
.default_value(default_max_snapshot_to_retain)
.help("The maximum number of snapshots to hold on to when purging older snapshots.")
)
.arg(
Arg::with_name("snapshot_packager_niceness_adj")
.long("snapshot-packager-niceness-adjustment")
.value_name("ADJUSTMENT")
.takes_value(true)
.validator(is_niceness_adjustment_valid)
.default_value("0")
.help("Add this value to niceness of snapshot packager thread. Negative value \
increases priority, positive value decreases priority.")
)
.arg(
Arg::with_name("minimal_snapshot_download_speed")
.long("minimal-snapshot-download-speed")
.value_name("MINIMAL_SNAPSHOT_DOWNLOAD_SPEED")
.takes_value(true)
.default_value(default_min_snapshot_download_speed)
.help("The minimal speed of snapshot downloads measured in bytes/second. \
If the initial download speed falls below this threshold, the system will \
retry the download against a different rpc node."),
)
.arg(
Arg::with_name("maximum_snapshot_download_abort")
.long("maximum-snapshot-download-abort")
.value_name("MAXIMUM_SNAPSHOT_DOWNLOAD_ABORT")
.takes_value(true)
.default_value(default_max_snapshot_download_abort)
.help("The maximum number of times to abort and retry when encountering a \
slow snapshot download."),
)
.arg(
Arg::with_name("contact_debug_interval")
.long("contact-debug-interval")
.value_name("CONTACT_DEBUG_INTERVAL")
.takes_value(true)
.default_value("10000")
.help("Milliseconds between printing contact debug from gossip."),
)
.arg(
Arg::with_name("no_poh_speed_test")
.long("no-poh-speed-test")
.help("Skip the check for PoH speed."),
)
.arg(
Arg::with_name("accounts_hash_interval_slots")
.long("accounts-hash-slots")
.value_name("ACCOUNTS_HASH_INTERVAL_SLOTS")
.takes_value(true)
.default_value("100")
.help("Number of slots between generating accounts hash."),
)
.arg(
Arg::with_name("no_os_network_stats_reporting")
.long("no-os-network-stats-reporting")
.help("Disable reporting of OS network statistics.")
)
.arg(
Arg::with_name("snapshot_version")
.long("snapshot-version")
.value_name("SNAPSHOT_VERSION")
.validator(is_parsable::<SnapshotVersion>)
.takes_value(true)
.default_value(SnapshotVersion::default().into())
.help("Output snapshot version"),
)
.arg(
Arg::with_name("limit_ledger_size")
.long("limit-ledger-size")
.value_name("SHRED_COUNT")
.takes_value(true)
.min_values(0)
.max_values(1)
/* .default_value() intentionally not used here! */
.help("Keep this amount of shreds in root slots."),
)
.arg(
Arg::with_name("skip_poh_verify")
.long("skip-poh-verify")
.takes_value(false)
.help("Skip ledger verification at validator bootup"),
)
.arg(
Arg::with_name("cuda")
.long("cuda")
.takes_value(false)
.help("Use CUDA"),
)
.arg(
clap::Arg::with_name("require_tower")
.long("require-tower")
.takes_value(false)
.help("Refuse to start if saved tower state is not found"),
)
.arg(
Arg::with_name("expected_genesis_hash")
.long("expected-genesis-hash")
.value_name("HASH")
.takes_value(true)
.validator(hash_validator)
.help("Require the genesis have this hash"),
)
.arg(
Arg::with_name("expected_bank_hash")
.long("expected-bank-hash")
.value_name("HASH")
.takes_value(true)
.validator(hash_validator)
.help("When wait-for-supermajority <x>, require the bank at <x> to have this hash"),
)
.arg(
Arg::with_name("expected_shred_version")
.long("expected-shred-version")
.value_name("VERSION")
.takes_value(true)
.validator(is_parsable::<u16>)
.help("Require the shred version be this value"),
)
.arg(
Arg::with_name("logfile")
.short("o")
.long("log")
.value_name("FILE")
.takes_value(true)
.help("Redirect logging to the specified file, '-' for standard error. \
Sending the SIGUSR1 signal to the validator process will cause it \
to re-open the log file"),
)
.arg(
Arg::with_name("wait_for_supermajority")
.long("wait-for-supermajority")
.requires("expected_bank_hash")
.value_name("SLOT")
.validator(is_slot)
.help("After processing the ledger and the next slot is SLOT, wait until a \
supermajority of stake is visible on gossip before starting PoH"),
)
.arg(
Arg::with_name("no_wait_for_vote_to_start_leader")
.hidden(true)
.long("no-wait-for-vote-to-start-leader")
.help("If the validator starts up with no ledger, it will wait to start block
production until it sees a vote land in a rooted slot. This prevents
double signing. Turn off to risk double signing a block."),
)
.arg(
Arg::with_name("hard_forks")
.long("hard-fork")
.value_name("SLOT")
.validator(is_slot)
.multiple(true)
.takes_value(true)
.help("Add a hard fork at this slot"),
)
.arg(
Arg::with_name("known_validators")
.alias("trusted-validator")
.long("known-validator")
.validator(is_pubkey)
.value_name("VALIDATOR IDENTITY")
.multiple(true)
.takes_value(true)
.help("A snapshot hash must be published in gossip by this validator to be accepted. \
May be specified multiple times. If unspecified any snapshot hash will be accepted"),
)
.arg(
Arg::with_name("debug_key")
.long("debug-key")
.validator(is_pubkey)
.value_name("ADDRESS")
.multiple(true)
.takes_value(true)
.help("Log when transactions are processed which reference a given key."),
)
.arg(
Arg::with_name("only_known_rpc")
.alias("no-untrusted-rpc")
.long("only-known-rpc")
.takes_value(false)
.help("Use the RPC service of known validators only")
)
.arg(
Arg::with_name("repair_validators")
.long("repair-validator")
.validator(is_pubkey)
.value_name("VALIDATOR IDENTITY")
.multiple(true)
.takes_value(true)
.help("A list of validators to request repairs from. If specified, repair will not \
request from validators outside this set [default: all validators]")
)
.arg(
Arg::with_name("gossip_validators")
.long("gossip-validator")
.validator(is_pubkey)
.value_name("VALIDATOR IDENTITY")
.multiple(true)
.takes_value(true)
.help("A list of validators to gossip with. If specified, gossip \
will not pull/pull from from validators outside this set. \
[default: all validators]")
)
.arg(
Arg::with_name("no_rocksdb_compaction")
.long("no-rocksdb-compaction")
.takes_value(false)
.help("Disable manual compaction of the ledger database (this is ignored).")
)
.arg(
Arg::with_name("rocksdb_compaction_interval")
.long("rocksdb-compaction-interval-slots")
.value_name("ROCKSDB_COMPACTION_INTERVAL_SLOTS")
.takes_value(true)
.help("Number of slots between compacting ledger"),
)
.arg(
Arg::with_name("tpu_coalesce_ms")
.long("tpu-coalesce-ms")
.value_name("MILLISECS")
.takes_value(true)
.validator(is_parsable::<u64>)
.help("Milliseconds to wait in the TPU receiver for packet coalescing."),
)
.arg(
Arg::with_name("rocksdb_max_compaction_jitter")
.long("rocksdb-max-compaction-jitter-slots")
.value_name("ROCKSDB_MAX_COMPACTION_JITTER_SLOTS")
.takes_value(true)
.help("Introduce jitter into the compaction to offset compaction operation"),
)
.arg(
Arg::with_name("bind_address")
.long("bind-address")
.value_name("HOST")
.takes_value(true)
.validator(solana_net_utils::is_host)
.default_value("0.0.0.0")
.help("IP address to bind the validator ports"),
)
.arg(
Arg::with_name("rpc_bind_address")
.long("rpc-bind-address")
.value_name("HOST")
.takes_value(true)
.validator(solana_net_utils::is_host)
.help("IP address to bind the RPC port [default: 127.0.0.1 if --private-rpc is present, otherwise use --bind-address]"),
)
.arg(
Arg::with_name("rpc_threads")
.long("rpc-threads")
.value_name("NUMBER")
.validator(is_parsable::<usize>)
.takes_value(true)
.default_value(&default_rpc_threads)
.help("Number of threads to use for servicing RPC requests"),
)
.arg(
Arg::with_name("rpc_niceness_adj")
.long("rpc-niceness-adjustment")
.value_name("ADJUSTMENT")
.takes_value(true)
.validator(is_niceness_adjustment_valid)
.default_value("0")
.help("Add this value to niceness of RPC threads. Negative value \
increases priority, positive value decreases priority.")
)
.arg(
Arg::with_name("rpc_bigtable_timeout")
.long("rpc-bigtable-timeout")
.value_name("SECONDS")
.validator(is_parsable::<u64>)
.takes_value(true)
.default_value("30")
.help("Number of seconds before timing out RPC requests backed by BigTable"),
)
.arg(
Arg::with_name("rpc_pubsub_worker_threads")
.long("rpc-pubsub-worker-threads")
.takes_value(true)
.value_name("NUMBER")
.validator(is_parsable::<usize>)
.default_value("4")
.help("PubSub worker threads"),
)
.arg(
Arg::with_name("rpc_pubsub_enable_vote_subscription")
.long("rpc-pubsub-enable-vote-subscription")
.takes_value(false)
.help("Enable the unstable RPC PubSub `voteSubscribe` subscription"),
)
.arg(
Arg::with_name("rpc_pubsub_max_connections")
.long("rpc-pubsub-max-connections")
.value_name("NUMBER")
.takes_value(true)
.validator(is_parsable::<usize>)
.hidden(true)
.help("The maximum number of connections that RPC PubSub will support. \
This is a hard limit and no new connections beyond this limit can \
be made until an old connection is dropped. (Obsolete)"),
)
.arg(
Arg::with_name("rpc_pubsub_max_fragment_size")
.long("rpc-pubsub-max-fragment-size")
.value_name("BYTES")
.takes_value(true)
.validator(is_parsable::<usize>)
.hidden(true)
.help("The maximum length in bytes of acceptable incoming frames. Messages longer \
than this will be rejected. (Obsolete)"),
)
.arg(
Arg::with_name("rpc_pubsub_max_in_buffer_capacity")
.long("rpc-pubsub-max-in-buffer-capacity")
.value_name("BYTES")
.takes_value(true)
.validator(is_parsable::<usize>)
.hidden(true)
.help("The maximum size in bytes to which the incoming websocket buffer can grow. \
(Obsolete)"),
)
.arg(
Arg::with_name("rpc_pubsub_max_out_buffer_capacity")
.long("rpc-pubsub-max-out-buffer-capacity")
.value_name("BYTES")
.takes_value(true)
.validator(is_parsable::<usize>)
.hidden(true)
.help("The maximum size in bytes to which the outgoing websocket buffer can grow. \
(Obsolete)"),
)
.arg(
Arg::with_name("rpc_pubsub_max_active_subscriptions")
.long("rpc-pubsub-max-active-subscriptions")
.takes_value(true)
.value_name("NUMBER")
.validator(is_parsable::<usize>)
.default_value(&default_rpc_pubsub_max_active_subscriptions)
.help("The maximum number of active subscriptions that RPC PubSub will accept \
across all connections."),
)
.arg(
Arg::with_name("rpc_pubsub_queue_capacity_items")
.long("rpc-pubsub-queue-capacity-items")
.takes_value(true)
.value_name("NUMBER")
.validator(is_parsable::<usize>)
.default_value(&default_rpc_pubsub_queue_capacity_items)
.help("The maximum number of notifications that RPC PubSub will store \
across all connections."),
)
.arg(
Arg::with_name("rpc_pubsub_queue_capacity_bytes")
.long("rpc-pubsub-queue-capacity-bytes")
.takes_value(true)
.value_name("BYTES")
.validator(is_parsable::<usize>)
.default_value(&default_rpc_pubsub_queue_capacity_bytes)
.help("The maximum total size of notifications that RPC PubSub will store \
across all connections."),
)
.arg(
Arg::with_name("rpc_pubsub_notification_threads")
.long("rpc-pubsub-notification-threads")
.takes_value(true)
.value_name("NUM_THREADS")
.validator(is_parsable::<usize>)
.help("The maximum number of threads that RPC PubSub will use \
for generating notifications."),
)
.arg(
Arg::with_name("rpc_send_transaction_retry_ms")
.long("rpc-send-retry-ms")
.value_name("MILLISECS")
.takes_value(true)
.validator(is_parsable::<u64>)
.default_value(&default_rpc_send_transaction_retry_ms)
.help("The rate at which transactions sent via rpc service are retried."),
)
.arg(
Arg::with_name("rpc_send_transaction_leader_forward_count")
.long("rpc-send-leader-count")
.value_name("NUMBER")
.takes_value(true)
.validator(is_parsable::<u64>)
.default_value(&default_rpc_send_transaction_leader_forward_count)
.help("The number of upcoming leaders to which to forward transactions sent via rpc service."),
)
.arg(
Arg::with_name("rpc_send_transaction_default_max_retries")
.long("rpc-send-default-max-retries")
.value_name("NUMBER")
.takes_value(true)
.validator(is_parsable::<usize>)
.help("The maximum number of transaction broadcast retries when unspecified by the request, otherwise retried until expiration."),
)
.arg(
Arg::with_name("rpc_send_transaction_service_max_retries")
.long("rpc-send-service-max-retries")
.value_name("NUMBER")
.takes_value(true)
.validator(is_parsable::<usize>)
.default_value(&default_rpc_send_transaction_service_max_retries)
.help("The maximum number of transaction broadcast retries, regardless of requested value."),
)
.arg(
Arg::with_name("rpc_scan_and_fix_roots")
.long("rpc-scan-and-fix-roots")
.takes_value(false)
.requires("enable_rpc_transaction_history")
.help("Verifies blockstore roots on boot and fixes any gaps"),
)
.arg(
Arg::with_name("accountsdb_plugin_config")
.long("accountsdb-plugin-config")
.value_name("FILE")
.takes_value(true)
.multiple(true)
.hidden(true)
.help("Specify the configuration file for the AccountsDb plugin."),
)
.arg(
Arg::with_name("halt_on_known_validators_accounts_hash_mismatch")
.alias("halt-on-trusted-validators-accounts-hash-mismatch")
.long("halt-on-known-validators-accounts-hash-mismatch")
.requires("known_validators")
.takes_value(false)
.help("Abort the validator if a bank hash mismatch is detected within known validator set"),
)
.arg(
Arg::with_name("frozen_accounts")
.long("frozen-account")
.validator(is_pubkey)
.value_name("PUBKEY")
.multiple(true)
.takes_value(true)
.help("Freeze the specified account. This will cause the validator to \
intentionally crash should any transaction modify the frozen account in any way \
other than increasing the account balance"),
)
.arg(
Arg::with_name("snapshot_archive_format")
.long("snapshot-archive-format")
.alias("snapshot-compression") // Legacy name used by Solana v1.5.x and older
.possible_values(&["bz2", "gzip", "zstd", "tar", "none"])
.default_value("zstd")
.value_name("ARCHIVE_TYPE")
.takes_value(true)
.help("Snapshot archive format to use."),
)
.arg(
Arg::with_name("max_genesis_archive_unpacked_size")
.long("max-genesis-archive-unpacked-size")
.value_name("NUMBER")
.takes_value(true)
.default_value(default_genesis_archive_unpacked_size)
.help(
"maximum total uncompressed file size of downloaded genesis archive",
),
)
.arg(
Arg::with_name("wal_recovery_mode")
.long("wal-recovery-mode")
.value_name("MODE")
.takes_value(true)
.possible_values(&[
"tolerate_corrupted_tail_records",
"absolute_consistency",
"point_in_time",
"skip_any_corrupted_record"])
.help(
"Mode to recovery the ledger db write ahead log."
),
)
.arg(
Arg::with_name("no_bpf_jit")
.long("no-bpf-jit")
.takes_value(false)
.help("Disable the just-in-time compiler and instead use the interpreter for BPF"),
)
.arg(
// legacy nop argument
Arg::with_name("bpf_jit")
.long("bpf-jit")
.hidden(true)
.takes_value(false)
.conflicts_with("no_bpf_jit")
)
.arg(
Arg::with_name("poh_pinned_cpu_core")
.hidden(true)
.long("experimental-poh-pinned-cpu-core")
.takes_value(true)
.value_name("CPU_CORE_INDEX")
.validator(|s| {
let core_index = usize::from_str(&s).map_err(|e| e.to_string())?;
let max_index = core_affinity::get_core_ids().map(|cids| cids.len() - 1).unwrap_or(0);
if core_index > max_index {
return Err(format!("core index must be in the range [0, {}]", max_index));
}
Ok(())
})
.help("EXPERIMENTAL: Specify which CPU core PoH is pinned to"),
)
.arg(
Arg::with_name("poh_hashes_per_batch")
.hidden(true)
.long("poh-hashes-per-batch")
.takes_value(true)
.value_name("NUM")
.help("Specify hashes per batch in PoH service"),
)
.arg(
Arg::with_name("account_indexes")
.long("account-index")
.takes_value(true)
.multiple(true)
.possible_values(&["program-id", "spl-token-owner", "spl-token-mint"])
.value_name("INDEX")
.help("Enable an accounts index, indexed by the selected account field"),
)
.arg(
Arg::with_name("account_index_exclude_key")
.long(EXCLUDE_KEY)
.takes_value(true)
.validator(is_pubkey)
.multiple(true)
.value_name("KEY")
.help("When account indexes are enabled, exclude this key from the index."),
)
.arg(
Arg::with_name("account_index_include_key")
.long(INCLUDE_KEY)
.takes_value(true)
.validator(is_pubkey)
.conflicts_with("account_index_exclude_key")
.multiple(true)
.value_name("KEY")
.help("When account indexes are enabled, only include specific keys in the index. This overrides --account-index-exclude-key."),
)
.arg(
Arg::with_name("no_accounts_db_caching")
.long("no-accounts-db-caching")
.help("Disables accounts caching"),
)
.arg(
Arg::with_name("accounts_db_skip_shrink")
.long("accounts-db-skip-shrink")
.help("Enables faster starting of validators by skipping shrink. \
This option is for use during testing."),
)
.arg(
Arg::with_name("accounts_db_test_hash_calculation")
.long("accounts-db-test-hash-calculation")
.help("Enables testing of hash calculation using stores in \
AccountsHashVerifier. This has a computational cost."),
)
.arg(
Arg::with_name("accounts_db_index_hashing")
.long("accounts-db-index-hashing")
.help("Enables the use of the index in hash calculation in \
AccountsHashVerifier/Accounts Background Service."),
)
.arg(
Arg::with_name("no_accounts_db_index_hashing")
.long("no-accounts-db-index-hashing")
.help("This is obsolete. See --accounts-db-index-hashing. \
Disables the use of the index in hash calculation in \
AccountsHashVerifier/Accounts Background Service."),
)
.arg(
// legacy nop argument
Arg::with_name("accounts_db_caching_enabled")
.long("accounts-db-caching-enabled")
.conflicts_with("no_accounts_db_caching")
.hidden(true)
)
.arg(
Arg::with_name("accounts_shrink_optimize_total_space")
.long("accounts-shrink-optimize-total-space")
.takes_value(true)
.value_name("BOOLEAN")
.default_value(default_accounts_shrink_optimize_total_space)
.help("When this is set to true, the system will shrink the most \
sparse accounts and when the overall shrink ratio is above \
the specified accounts-shrink-ratio, the shrink will stop and \
it will skip all other less sparse accounts."),
)
.arg(
Arg::with_name("accounts_shrink_ratio")
.long("accounts-shrink-ratio")
.takes_value(true)
.value_name("RATIO")
.default_value(default_accounts_shrink_ratio)
.help("Specifies the shrink ratio for the accounts to be shrunk. \
The shrink ratio is defined as the ratio of the bytes alive over the \
total bytes used. If the account's shrink ratio is less than this ratio \
it becomes a candidate for shrinking. The value must between 0. and 1.0 \
inclusive."),
)
.arg(
Arg::with_name("no_duplicate_instance_check")
.long("no-duplicate-instance-check")
.takes_value(false)
.help("Disables duplicate instance check")
.hidden(true),
)
.arg(
Arg::with_name("allow_private_addr")
.long("allow-private-addr")
.takes_value(false)
.help("Allow contacting private ip addresses")
.hidden(true),
)
.after_help("The default subcommand is run")
.subcommand(
SubCommand::with_name("exit")
.about("Send an exit request to the validator")
.arg(
Arg::with_name("force")
.short("f")
.long("force")
.takes_value(false)
.help("Request the validator exit immediately instead of waiting for a restart window")
)
.arg(
Arg::with_name("monitor")
.short("m")
.long("monitor")
.takes_value(false)
.help("Monitor the validator after sending the exit request")
)
.arg(
Arg::with_name("min_idle_time")
.takes_value(true)
.long("min-idle-time")
.validator(is_parsable::<usize>)
.value_name("MINUTES")
.default_value("10")
.help("Minimum time that the validator should not be leader before restarting")
)
.arg(
Arg::with_name("max_delinquent_stake")
.long("max-delinquent-stake")
.takes_value(true)
.validator(is_valid_percentage)
.default_value("5")
.value_name("PERCENT")
.help("The maximum delinquent stake % permitted for an exit")
)
)
.subcommand(
SubCommand::with_name("authorized-voter")
.about("Adjust the validator authorized voters")
.setting(AppSettings::SubcommandRequiredElseHelp)
.setting(AppSettings::InferSubcommands)
.subcommand(
SubCommand::with_name("add")
.about("Add an authorized voter")
.arg(
Arg::with_name("authorized_voter_keypair")
.index(1)
.value_name("KEYPAIR")
.takes_value(true)
.validator(is_keypair)
.help("Keypair of the authorized voter to add"),
)
.after_help("Note: the new authorized voter only applies to the \
currently running validator instance")
)
.subcommand(
SubCommand::with_name("remove-all")
.about("Remove all authorized voters")
.after_help("Note: the removal only applies to the \
currently running validator instance")
)
)
.subcommand(
SubCommand::with_name("contact-info")
.about("Display the validator's contact info")
.arg(
Arg::with_name("output")
.long("output")
.takes_value(true)
.value_name("MODE")
.possible_values(&["json", "json-compact"])
.help("Output display mode")
)
)
.subcommand(
SubCommand::with_name("init")
.about("Initialize the ledger directory then exit")
)
.subcommand(
SubCommand::with_name("monitor")
.about("Monitor the validator")
)
.subcommand(
SubCommand::with_name("run")
.about("Run the validator")
)
.subcommand(
SubCommand::with_name("set-log-filter")
.about("Adjust the validator log filter")
.arg(
Arg::with_name("filter")
.takes_value(true)
.index(1)
.help("New filter using the same format as the RUST_LOG environment variable")
)
.after_help("Note: the new filter only applies to the currently running validator instance")
)
.subcommand(
SubCommand::with_name("wait-for-restart-window")
.about("Monitor the validator for a good time to restart")
.arg(
Arg::with_name("min_idle_time")
.takes_value(true)
.index(1)
.validator(is_parsable::<usize>)
.value_name("MINUTES")
.default_value("10")
.help("Minimum time that the validator should not be leader before restarting")
)
.arg(
Arg::with_name("identity")
.long("identity")
.value_name("ADDRESS")
.takes_value(true)
.validator(is_pubkey_or_keypair)
.help("Validator identity to monitor [default: your validator]")
)
.arg(
Arg::with_name("max_delinquent_stake")
.long("max-delinquent-stake")
.takes_value(true)
.validator(is_valid_percentage)
.default_value("5")
.value_name("PERCENT")
.help("The maximum delinquent stake % permitted for a restart")
)
.after_help("Note: If this command exits with a non-zero status \
then this not a good time for a restart")
)
.get_matches();
let socket_addr_space = SocketAddrSpace::new(matches.is_present("allow_private_addr"));
let ledger_path = PathBuf::from(matches.value_of("ledger_path").unwrap());
let operation = match matches.subcommand() {
("", _) | ("run", _) => Operation::Run,
("authorized-voter", Some(authorized_voter_subcommand_matches)) => {
match authorized_voter_subcommand_matches.subcommand() {
("add", Some(subcommand_matches)) => {
let authorized_voter_keypair =
value_t_or_exit!(subcommand_matches, "authorized_voter_keypair", String);
let authorized_voter_keypair = fs::canonicalize(&authorized_voter_keypair)
.unwrap_or_else(|err| {
println!(
"Unable to access path: {}: {:?}",
authorized_voter_keypair, err
);
exit(1);
});
println!(
"Adding authorized voter: {}",
authorized_voter_keypair.display()
);
let admin_client = admin_rpc_service::connect(&ledger_path);
admin_rpc_service::runtime()
.block_on(async move {
admin_client
.await?
.add_authorized_voter(
authorized_voter_keypair.display().to_string(),
)
.await
})
.unwrap_or_else(|err| {
println!("addAuthorizedVoter request failed: {}", err);
exit(1);
});
return;
}
("remove-all", _) => {
let admin_client = admin_rpc_service::connect(&ledger_path);
admin_rpc_service::runtime()
.block_on(async move {
admin_client.await?.remove_all_authorized_voters().await
})
.unwrap_or_else(|err| {
println!("removeAllAuthorizedVoters request failed: {}", err);
exit(1);
});
println!("All authorized voters removed");
return;
}
_ => unreachable!(),
}
}
("contact-info", Some(subcommand_matches)) => {
let output_mode = subcommand_matches.value_of("output");
let admin_client = admin_rpc_service::connect(&ledger_path);
let contact_info = admin_rpc_service::runtime()
.block_on(async move { admin_client.await?.contact_info().await })
.unwrap_or_else(|err| {
eprintln!("Contact info query failed: {}", err);
exit(1);
});
if let Some(mode) = output_mode {
match mode {
"json" => println!("{}", serde_json::to_string_pretty(&contact_info).unwrap()),
"json-compact" => print!("{}", serde_json::to_string(&contact_info).unwrap()),
_ => unreachable!(),
}
} else {
print!("{}", contact_info);
}
return;
}
("init", _) => Operation::Initialize,
("exit", Some(subcommand_matches)) => {
let min_idle_time = value_t_or_exit!(subcommand_matches, "min_idle_time", usize);
let force = subcommand_matches.is_present("force");
let monitor = subcommand_matches.is_present("monitor");
let max_delinquent_stake =
value_t_or_exit!(subcommand_matches, "max_delinquent_stake", u8);
if !force {
wait_for_restart_window(&ledger_path, None, min_idle_time, max_delinquent_stake)
.unwrap_or_else(|err| {
println!("{}", err);
exit(1);
});
}
let admin_client = admin_rpc_service::connect(&ledger_path);
admin_rpc_service::runtime()
.block_on(async move { admin_client.await?.exit().await })
.unwrap_or_else(|err| {
println!("exit request failed: {}", err);
exit(1);
});
println!("Exit request sent");
if monitor {
monitor_validator(&ledger_path);
}
return;
}
("monitor", _) => {
monitor_validator(&ledger_path);
return;
}
("set-log-filter", Some(subcommand_matches)) => {
let filter = value_t_or_exit!(subcommand_matches, "filter", String);
let admin_client = admin_rpc_service::connect(&ledger_path);
admin_rpc_service::runtime()
.block_on(async move { admin_client.await?.set_log_filter(filter).await })
.unwrap_or_else(|err| {
println!("set log filter failed: {}", err);
exit(1);
});
return;
}
("wait-for-restart-window", Some(subcommand_matches)) => {
let min_idle_time = value_t_or_exit!(subcommand_matches, "min_idle_time", usize);
let identity = pubkey_of(subcommand_matches, "identity");
let max_delinquent_stake =
value_t_or_exit!(subcommand_matches, "max_delinquent_stake", u8);
wait_for_restart_window(&ledger_path, identity, min_idle_time, max_delinquent_stake)
.unwrap_or_else(|err| {
println!("{}", err);
exit(1);
});
return;
}
_ => unreachable!(),
};
let identity_keypair = Arc::new(keypair_of(&matches, "identity").unwrap_or_else(|| {
clap::Error::with_description(
"The --identity <KEYPAIR> argument is required",
clap::ErrorKind::ArgumentNotFound,
)
.exit();
}));
let logfile = {
let logfile = matches
.value_of("logfile")
.map(|s| s.into())
.unwrap_or_else(|| format!("renec-validator-{}.log", identity_keypair.pubkey()));
if logfile == "-" {
None
} else {
println!("log file: {}", logfile);
Some(logfile)
}
};
let use_progress_bar = logfile.is_none();
let _logger_thread = redirect_stderr_to_file(logfile);
info!("{} {}", crate_name!(), solana_version::version!());
info!("Starting validator with: {:#?}", std::env::args_os());
let cuda = matches.is_present("cuda");
if cuda {
solana_perf::perf_libs::init_cuda();
enable_recycler_warming();
}
solana_core::validator::report_target_features();
let authorized_voter_keypairs = keypairs_of(&matches, "authorized_voter_keypairs")
.map(|keypairs| keypairs.into_iter().map(Arc::new).collect())
.unwrap_or_else(|| vec![identity_keypair.clone()]);
let authorized_voter_keypairs = Arc::new(RwLock::new(authorized_voter_keypairs));
let init_complete_file = matches.value_of("init_complete_file");
if matches.is_present("no_check_vote_account") {
info!("vote account sanity checks are no longer performed by default. --no-check-vote-account is deprecated and can be removed from the command line");
}
let rpc_bootstrap_config = RpcBootstrapConfig {
no_genesis_fetch: matches.is_present("no_genesis_fetch"),
no_snapshot_fetch: matches.is_present("no_snapshot_fetch"),
check_vote_account: matches
.value_of("check_vote_account")
.map(|url| url.to_string()),
only_known_rpc: matches.is_present("only_known_rpc"),
max_genesis_archive_unpacked_size: value_t_or_exit!(
matches,
"max_genesis_archive_unpacked_size",
u64
),
};
let private_rpc = matches.is_present("private_rpc");
let no_port_check = matches.is_present("no_port_check");
let no_rocksdb_compaction = true;
let rocksdb_compaction_interval = value_t!(matches, "rocksdb_compaction_interval", u64).ok();
let rocksdb_max_compaction_jitter =
value_t!(matches, "rocksdb_max_compaction_jitter", u64).ok();
let tpu_coalesce_ms =
value_t!(matches, "tpu_coalesce_ms", u64).unwrap_or(DEFAULT_TPU_COALESCE_MS);
let wal_recovery_mode = matches
.value_of("wal_recovery_mode")
.map(BlockstoreRecoveryMode::from);
// Canonicalize ledger path to avoid issues with symlink creation
let _ = fs::create_dir_all(&ledger_path);
let ledger_path = fs::canonicalize(&ledger_path).unwrap_or_else(|err| {
eprintln!("Unable to access ledger path: {:?}", err);
exit(1);
});
let debug_keys: Option<Arc<HashSet<_>>> = if matches.is_present("debug_key") {
Some(Arc::new(
values_t_or_exit!(matches, "debug_key", Pubkey)
.into_iter()
.collect(),
))
} else {
None
};
let known_validators = validators_set(
&identity_keypair.pubkey(),
&matches,
"known_validators",
"--known-validator",
);
let repair_validators = validators_set(
&identity_keypair.pubkey(),
&matches,
"repair_validators",
"--repair-validator",
);
let gossip_validators = validators_set(
&identity_keypair.pubkey(),
&matches,
"gossip_validators",
"--gossip-validator",
);
let bind_address = solana_net_utils::parse_host(matches.value_of("bind_address").unwrap())
.expect("invalid bind_address");
let rpc_bind_address = if matches.is_present("rpc_bind_address") {
solana_net_utils::parse_host(matches.value_of("rpc_bind_address").unwrap())
.expect("invalid rpc_bind_address")
} else if private_rpc {
solana_net_utils::parse_host("127.0.0.1").unwrap()
} else {
bind_address
};
let contact_debug_interval = value_t_or_exit!(matches, "contact_debug_interval", u64);
let account_indexes = process_account_indexes(&matches);
let restricted_repair_only_mode = matches.is_present("restricted_repair_only_mode");
let accounts_shrink_optimize_total_space =
value_t_or_exit!(matches, "accounts_shrink_optimize_total_space", bool);
let shrink_ratio = value_t_or_exit!(matches, "accounts_shrink_ratio", f64);
if !(0.0..=1.0).contains(&shrink_ratio) {
eprintln!(
"The specified account-shrink-ratio is invalid, it must be between 0. and 1.0 inclusive: {}",
shrink_ratio
);
exit(1);
}
let accounts_shrink_ratio = if accounts_shrink_optimize_total_space {
AccountShrinkThreshold::TotalSpace { shrink_ratio }
} else {
AccountShrinkThreshold::IndividalStore { shrink_ratio }
};
let entrypoint_addrs = values_t!(matches, "entrypoint", String)
.unwrap_or_default()
.into_iter()
.map(|entrypoint| {
solana_net_utils::parse_host_port(&entrypoint).unwrap_or_else(|e| {
eprintln!("failed to parse entrypoint address: {}", e);
exit(1);
})
})
.collect::<HashSet<_>>()
.into_iter()
.collect::<Vec<_>>();
// TODO: Once entrypoints are updated to return shred-version, this should
// abort if it fails to obtain a shred-version, so that nodes always join
// gossip with a valid shred-version. The code to adopt entrypoint shred
// version can then be deleted from gossip and get_rpc_node above.
let expected_shred_version = value_t!(matches, "expected_shred_version", u16)
.ok()
.or_else(|| get_cluster_shred_version(&entrypoint_addrs));
let accountsdb_plugin_config_files = if matches.is_present("accountsdb_plugin_config") {
Some(
values_t_or_exit!(matches, "accountsdb_plugin_config", String)
.into_iter()
.map(PathBuf::from)
.collect(),
)
} else {
None
};
if matches.is_present("minimal_rpc_api") {
warn!("--minimal-rpc-api is now the default behavior. This flag is deprecated and can be removed from the launch args")
}
let mut validator_config = ValidatorConfig {
require_tower: matches.is_present("require_tower"),
tower_path: value_t!(matches, "tower", PathBuf).ok(),
dev_halt_at_slot: value_t!(matches, "dev_halt_at_slot", Slot).ok(),
expected_genesis_hash: matches
.value_of("expected_genesis_hash")
.map(|s| Hash::from_str(s).unwrap()),
expected_bank_hash: matches
.value_of("expected_bank_hash")
.map(|s| Hash::from_str(s).unwrap()),
expected_shred_version,
new_hard_forks: hardforks_of(&matches, "hard_forks"),
rpc_config: JsonRpcConfig {
enable_rpc_transaction_history: matches.is_present("enable_rpc_transaction_history"),
enable_cpi_and_log_storage: matches.is_present("enable_cpi_and_log_storage"),
enable_bigtable_ledger_storage: matches
.is_present("enable_rpc_bigtable_ledger_storage"),
enable_bigtable_ledger_upload: matches.is_present("enable_bigtable_ledger_upload"),
identity_pubkey: identity_keypair.pubkey(),
faucet_addr: matches.value_of("rpc_faucet_addr").map(|address| {
solana_net_utils::parse_host_port(address).expect("failed to parse faucet address")
}),
full_api: matches.is_present("full_rpc_api"),
obsolete_v1_7_api: matches.is_present("obsolete_v1_7_rpc_api"),
max_multiple_accounts: Some(value_t_or_exit!(
matches,
"rpc_max_multiple_accounts",
usize
)),
health_check_slot_distance: value_t_or_exit!(
matches,
"health_check_slot_distance",
u64
),
rpc_threads: value_t_or_exit!(matches, "rpc_threads", usize),
rpc_niceness_adj: value_t_or_exit!(matches, "rpc_niceness_adj", i8),
rpc_bigtable_timeout: value_t!(matches, "rpc_bigtable_timeout", u64)
.ok()
.map(Duration::from_secs),
account_indexes: account_indexes.clone(),
rpc_scan_and_fix_roots: matches.is_present("rpc_scan_and_fix_roots"),
},
accountsdb_plugin_config_files,
rpc_addrs: value_t!(matches, "rpc_port", u16).ok().map(|rpc_port| {
(
SocketAddr::new(rpc_bind_address, rpc_port),
SocketAddr::new(rpc_bind_address, rpc_port + 1),
// If additional ports are added, +2 needs to be skipped to avoid a conflict with
// the websocket port (which is +2) in web3.js This odd port shifting is tracked at
// https://github.com/solana-labs/solana/issues/12250
)
}),
pubsub_config: PubSubConfig {
enable_vote_subscription: matches.is_present("rpc_pubsub_enable_vote_subscription"),
max_active_subscriptions: value_t_or_exit!(
matches,
"rpc_pubsub_max_active_subscriptions",
usize
),
queue_capacity_items: value_t_or_exit!(
matches,
"rpc_pubsub_queue_capacity_items",
usize
),
queue_capacity_bytes: value_t_or_exit!(
matches,
"rpc_pubsub_queue_capacity_bytes",
usize
),
worker_threads: value_t_or_exit!(matches, "rpc_pubsub_worker_threads", usize),
notification_threads: value_of(&matches, "rpc_pubsub_notification_threads"),
},
voting_disabled: matches.is_present("no_voting") || restricted_repair_only_mode,
wait_for_supermajority: value_t!(matches, "wait_for_supermajority", Slot).ok(),
known_validators,
repair_validators,
gossip_validators,
frozen_accounts: values_t!(matches, "frozen_accounts", Pubkey).unwrap_or_default(),
no_rocksdb_compaction,
rocksdb_compaction_interval,
rocksdb_max_compaction_jitter,
wal_recovery_mode,
poh_verify: !matches.is_present("skip_poh_verify"),
debug_keys,
contact_debug_interval,
bpf_jit: !matches.is_present("no_bpf_jit"),
send_transaction_service_config: send_transaction_service::Config {
retry_rate_ms: value_t_or_exit!(matches, "rpc_send_transaction_retry_ms", u64),
leader_forward_count: value_t_or_exit!(
matches,
"rpc_send_transaction_leader_forward_count",
u64
),
default_max_retries: value_t!(
matches,
"rpc_send_transaction_default_max_retries",
usize
)
.ok(),
service_max_retries: value_t_or_exit!(
matches,
"rpc_send_transaction_service_max_retries",
usize
),
},
no_poh_speed_test: matches.is_present("no_poh_speed_test"),
no_os_network_stats_reporting: matches.is_present("no_os_network_stats_reporting"),
poh_pinned_cpu_core: value_of(&matches, "poh_pinned_cpu_core")
.unwrap_or(poh_service::DEFAULT_PINNED_CPU_CORE),
poh_hashes_per_batch: value_of(&matches, "poh_hashes_per_batch")
.unwrap_or(poh_service::DEFAULT_HASHES_PER_BATCH),
account_indexes,
accounts_db_caching_enabled: !matches.is_present("no_accounts_db_caching"),
accounts_db_test_hash_calculation: matches.is_present("accounts_db_test_hash_calculation"),
accounts_db_skip_shrink: matches.is_present("accounts_db_skip_shrink"),
accounts_db_use_index_hash_calculation: matches.is_present("accounts_db_index_hashing"),
tpu_coalesce_ms,
no_wait_for_vote_to_start_leader: matches.is_present("no_wait_for_vote_to_start_leader"),
accounts_shrink_ratio,
..ValidatorConfig::default()
};
let vote_account = pubkey_of(&matches, "vote_account").unwrap_or_else(|| {
if !validator_config.voting_disabled {
warn!("--vote-account not specified, validator will not vote");
validator_config.voting_disabled = true;
}
Keypair::new().pubkey()
});
let dynamic_port_range =
solana_net_utils::parse_port_range(matches.value_of("dynamic_port_range").unwrap())
.expect("invalid dynamic_port_range");
let account_paths: Vec<PathBuf> =
if let Ok(account_paths) = values_t!(matches, "account_paths", String) {
account_paths
.join(",")
.split(',')
.map(PathBuf::from)
.collect()
} else {
vec![ledger_path.join("accounts")]
};
let account_shrink_paths: Option<Vec<PathBuf>> =
values_t!(matches, "account_shrink_path", String)
.map(|shrink_paths| shrink_paths.into_iter().map(PathBuf::from).collect())
.ok();
// Create and canonicalize account paths to avoid issues with symlink creation
validator_config.account_paths = account_paths
.into_iter()
.map(|account_path| {
match fs::create_dir_all(&account_path).and_then(|_| fs::canonicalize(&account_path)) {
Ok(account_path) => account_path,
Err(err) => {
eprintln!(
"Unable to access account path: {:?}, err: {:?}",
account_path, err
);
exit(1);
}
}
})
.collect();
validator_config.account_shrink_paths = account_shrink_paths.map(|paths| {
paths
.into_iter()
.map(|account_path| {
match fs::create_dir_all(&account_path)
.and_then(|_| fs::canonicalize(&account_path))
{
Ok(account_path) => account_path,
Err(err) => {
eprintln!(
"Unable to access account path: {:?}, err: {:?}",
account_path, err
);
exit(1);
}
}
})
.collect()
});
let snapshot_interval_slots = value_t_or_exit!(matches, "snapshot_interval_slots", u64);
let maximum_local_snapshot_age = value_t_or_exit!(matches, "maximum_local_snapshot_age", u64);
let maximum_snapshots_to_retain =
value_t_or_exit!(matches, "maximum_snapshots_to_retain", usize);
let snapshot_packager_niceness_adj =
value_t_or_exit!(matches, "snapshot_packager_niceness_adj", i8);
let minimal_snapshot_download_speed =
value_t_or_exit!(matches, "minimal_snapshot_download_speed", f32);
let maximum_snapshot_download_abort =
value_t_or_exit!(matches, "maximum_snapshot_download_abort", u64);
let snapshot_output_dir = if matches.is_present("snapshots") {
PathBuf::from(matches.value_of("snapshots").unwrap())
} else {
ledger_path.clone()
};
let snapshot_path = snapshot_output_dir.join("snapshot");
fs::create_dir_all(&snapshot_path).unwrap_or_else(|err| {
eprintln!(
"Failed to create snapshots directory {:?}: {}",
snapshot_path, err
);
exit(1);
});
let archive_format = {
let archive_format_str = value_t_or_exit!(matches, "snapshot_archive_format", String);
match archive_format_str.as_str() {
"bz2" => ArchiveFormat::TarBzip2,
"gzip" => ArchiveFormat::TarGzip,
"zstd" => ArchiveFormat::TarZstd,
"tar" | "none" => ArchiveFormat::Tar,
_ => panic!("Archive format not recognized: {}", archive_format_str),
}
};
let snapshot_version =
matches
.value_of("snapshot_version")
.map_or(SnapshotVersion::default(), |s| {
s.parse::<SnapshotVersion>().unwrap_or_else(|err| {
eprintln!("Error: {}", err);
exit(1)
})
});
validator_config.snapshot_config = Some(SnapshotConfig {
snapshot_interval_slots: if snapshot_interval_slots > 0 {
snapshot_interval_slots
} else {
std::u64::MAX
},
snapshot_path,
snapshot_package_output_path: snapshot_output_dir.clone(),
archive_format,
snapshot_version,
maximum_snapshots_to_retain,
packager_thread_niceness_adj: snapshot_packager_niceness_adj,
});
validator_config.accounts_hash_interval_slots =
value_t_or_exit!(matches, "accounts_hash_interval_slots", u64);
if validator_config.accounts_hash_interval_slots == 0 {
eprintln!("Accounts hash interval should not be 0.");
exit(1);
}
if is_snapshot_config_invalid(
snapshot_interval_slots,
validator_config.accounts_hash_interval_slots,
) {
eprintln!("Invalid snapshot interval provided ({}), must be a multiple of accounts_hash_interval_slots ({})",
snapshot_interval_slots,
validator_config.accounts_hash_interval_slots,
);
exit(1);
}
if matches.is_present("limit_ledger_size") {
let limit_ledger_size = match matches.value_of("limit_ledger_size") {
Some(_) => value_t_or_exit!(matches, "limit_ledger_size", u64),
None => DEFAULT_MAX_LEDGER_SHREDS,
};
if limit_ledger_size < DEFAULT_MIN_MAX_LEDGER_SHREDS {
eprintln!(
"The provided --limit-ledger-size value was too small, the minimum value is {}",
DEFAULT_MIN_MAX_LEDGER_SHREDS
);
exit(1);
}
validator_config.max_ledger_shreds = Some(limit_ledger_size);
}
if matches.is_present("halt_on_known_validators_accounts_hash_mismatch") {
validator_config.halt_on_known_validators_accounts_hash_mismatch = true;
}
let public_rpc_addr = matches.value_of("public_rpc_addr").map(|addr| {
solana_net_utils::parse_host_port(addr).unwrap_or_else(|e| {
eprintln!("failed to parse public rpc address: {}", e);
exit(1);
})
});
let mut ledger_lock = ledger_lockfile(&ledger_path);
let _ledger_write_guard = lock_ledger(&ledger_path, &mut ledger_lock);
let start_progress = Arc::new(RwLock::new(ValidatorStartProgress::default()));
let admin_service_cluster_info = Arc::new(RwLock::new(None));
admin_rpc_service::run(
&ledger_path,
admin_rpc_service::AdminRpcRequestMetadata {
rpc_addr: validator_config.rpc_addrs.map(|(rpc_addr, _)| rpc_addr),
start_time: std::time::SystemTime::now(),
validator_exit: validator_config.validator_exit.clone(),
start_progress: start_progress.clone(),
authorized_voter_keypairs: authorized_voter_keypairs.clone(),
cluster_info: admin_service_cluster_info.clone(),
},
);
let gossip_host: IpAddr = matches
.value_of("gossip_host")
.map(|gossip_host| {
solana_net_utils::parse_host(gossip_host).unwrap_or_else(|err| {
eprintln!("Failed to parse --gossip-host: {}", err);
exit(1);
})
})
.unwrap_or_else(|| {
if !entrypoint_addrs.is_empty() {
let mut order: Vec<_> = (0..entrypoint_addrs.len()).collect();
order.shuffle(&mut thread_rng());
let gossip_host = order.into_iter().find_map(|i| {
let entrypoint_addr = &entrypoint_addrs[i];
info!(
"Contacting {} to determine the validator's public IP address",
entrypoint_addr
);
solana_net_utils::get_public_ip_addr(entrypoint_addr).map_or_else(
|err| {
eprintln!(
"Failed to contact cluster entrypoint {}: {}",
entrypoint_addr, err
);
None
},
Some,
)
});
gossip_host.unwrap_or_else(|| {
eprintln!("Unable to determine the validator's public IP address");
exit(1);
})
} else {
std::net::IpAddr::V4(std::net::Ipv4Addr::new(127, 0, 0, 1))
}
});
let gossip_addr = SocketAddr::new(
gossip_host,
value_t!(matches, "gossip_port", u16).unwrap_or_else(|_| {
solana_net_utils::find_available_port_in_range(bind_address, (0, 1)).unwrap_or_else(
|err| {
eprintln!("Unable to find an available gossip port: {}", err);
exit(1);
},
)
}),
);
let cluster_entrypoints = entrypoint_addrs
.iter()
.map(ContactInfo::new_gossip_entry_point)
.collect::<Vec<_>>();
let mut node = Node::new_with_external_ip(
&identity_keypair.pubkey(),
&gossip_addr,
dynamic_port_range,
bind_address,
);
if restricted_repair_only_mode {
let any = SocketAddr::new(std::net::IpAddr::V4(std::net::Ipv4Addr::new(0, 0, 0, 0)), 0);
// When in --restricted_repair_only_mode is enabled only the gossip and repair ports
// need to be reachable by the entrypoint to respond to gossip pull requests and repair
// requests initiated by the node. All other ports are unused.
node.info.tpu = any;
node.info.tpu_forwards = any;
node.info.tvu = any;
node.info.tvu_forwards = any;
node.info.serve_repair = any;
// A node in this configuration shouldn't be an entrypoint to other nodes
node.sockets.ip_echo = None;
}
if !private_rpc {
if let Some(public_rpc_addr) = public_rpc_addr {
node.info.rpc = public_rpc_addr;
node.info.rpc_pubsub = public_rpc_addr;
} else if let Some((rpc_addr, rpc_pubsub_addr)) = validator_config.rpc_addrs {
node.info.rpc = SocketAddr::new(node.info.gossip.ip(), rpc_addr.port());
node.info.rpc_pubsub = SocketAddr::new(node.info.gossip.ip(), rpc_pubsub_addr.port());
}
}
solana_metrics::set_host_id(identity_keypair.pubkey().to_string());
solana_metrics::set_panic_hook("validator");
solana_ledger::entry::init_poh();
solana_runtime::snapshot_utils::remove_tmp_snapshot_archives(&snapshot_output_dir);
let should_check_duplicate_instance = !matches.is_present("no_duplicate_instance_check");
if !cluster_entrypoints.is_empty() {
rpc_bootstrap(
&node,
&identity_keypair,
&ledger_path,
&snapshot_output_dir,
&vote_account,
authorized_voter_keypairs.clone(),
&cluster_entrypoints,
&mut validator_config,
rpc_bootstrap_config,
no_port_check,
use_progress_bar,
maximum_local_snapshot_age,
should_check_duplicate_instance,
&start_progress,
minimal_snapshot_download_speed,
maximum_snapshot_download_abort,
socket_addr_space,
);
*start_progress.write().unwrap() = ValidatorStartProgress::Initializing;
}
if operation == Operation::Initialize {
info!("Validator ledger initialization complete");
return;
}
let validator = Validator::new(
node,
&identity_keypair,
&ledger_path,
&vote_account,
authorized_voter_keypairs,
cluster_entrypoints,
&validator_config,
should_check_duplicate_instance,
start_progress,
socket_addr_space,
);
*admin_service_cluster_info.write().unwrap() = Some(validator.cluster_info.clone());
if let Some(filename) = init_complete_file {
File::create(filename).unwrap_or_else(|_| {
error!("Unable to create: {}", filename);
exit(1);
});
}
info!("Validator initialized");
validator.join();
info!("Validator exiting..");
}
fn process_account_indexes(matches: &ArgMatches) -> AccountSecondaryIndexes {
let account_indexes: HashSet<AccountIndex> = matches
.values_of("account_indexes")
.unwrap_or_default()
.map(|value| match value {
"program-id" => AccountIndex::ProgramId,
"spl-token-mint" => AccountIndex::SplTokenMint,
"spl-token-owner" => AccountIndex::SplTokenOwner,
_ => unreachable!(),
})
.collect();
let account_indexes_include_keys: HashSet<Pubkey> =
values_t!(matches, "account_index_include_key", Pubkey)
.unwrap_or_default()
.iter()
.cloned()
.collect();
let account_indexes_exclude_keys: HashSet<Pubkey> =
values_t!(matches, "account_index_exclude_key", Pubkey)
.unwrap_or_default()
.iter()
.cloned()
.collect();
let exclude_keys = !account_indexes_exclude_keys.is_empty();
let include_keys = !account_indexes_include_keys.is_empty();
let keys = if !account_indexes.is_empty() && (exclude_keys || include_keys) {
let account_indexes_keys = AccountSecondaryIndexesIncludeExclude {
exclude: exclude_keys,
keys: if exclude_keys {
account_indexes_exclude_keys
} else {
account_indexes_include_keys
},
};
Some(account_indexes_keys)
} else {
None
};
AccountSecondaryIndexes {
keys,
indexes: account_indexes,
}
}
| 41.201149 | 159 | 0.539455 |
26df66e5b1b9cb0b3815f0c1f676dbaddc7221c5 | 5,569 | #[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::CALIB {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = r" Value of the field"]
pub struct TENMSR {
bits: u32,
}
impl TENMSR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct SKEWR {
bits: bool,
}
impl SKEWR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct NOREFR {
bits: bool,
}
impl NOREFR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Proxy"]
pub struct _TENMSW<'a> {
w: &'a mut W,
}
impl<'a> _TENMSW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u32) -> &'a mut W {
const MASK: u32 = 16777215;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _SKEWW<'a> {
w: &'a mut W,
}
impl<'a> _SKEWW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 30;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _NOREFW<'a> {
w: &'a mut W,
}
impl<'a> _NOREFW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 31;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:23 - Calibration value"]
#[inline]
pub fn tenms(&self) -> TENMSR {
let bits = {
const MASK: u32 = 16777215;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u32
};
TENMSR { bits }
}
#[doc = "Bit 30 - SKEW flag: Indicates whether the TENMS value is exact"]
#[inline]
pub fn skew(&self) -> SKEWR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 30;
((self.bits >> OFFSET) & MASK as u32) != 0
};
SKEWR { bits }
}
#[doc = "Bit 31 - NOREF flag. Reads as zero"]
#[inline]
pub fn noref(&self) -> NOREFR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 31;
((self.bits >> OFFSET) & MASK as u32) != 0
};
NOREFR { bits }
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:23 - Calibration value"]
#[inline]
pub fn tenms(&mut self) -> _TENMSW {
_TENMSW { w: self }
}
#[doc = "Bit 30 - SKEW flag: Indicates whether the TENMS value is exact"]
#[inline]
pub fn skew(&mut self) -> _SKEWW {
_SKEWW { w: self }
}
#[doc = "Bit 31 - NOREF flag. Reads as zero"]
#[inline]
pub fn noref(&mut self) -> _NOREFW {
_NOREFW { w: self }
}
}
| 24.861607 | 77 | 0.496678 |
3aa0588f9779980ab20cb98709d558254ab838ed | 1,628 | use nalgebra as na;
use super::Rect;
impl<T: na::RealField> Rect<T> {
/// Check if a point is contained within this rectangle.
///
/// # Returns
///
/// - `true` when the point is contained within the rectangle. Comparison
/// is inclusive, so the edges of the rectangle are considered 'inside'.
pub fn contains(&self, vec: &na::Vector2<T>) -> bool {
if vec.x >= self.left
&& vec.x <= self.right
&& vec.y >= self.bottom
&& vec.y <= self.top
{
true
} else {
false
}
}
pub fn width(&self) -> T {
(self.right - self.left).abs()
}
pub fn height(&self) -> T {
(self.top - self.bottom).abs()
}
}
#[cfg(test)]
mod test {
use super::super::*;
use nalgebra as na;
#[test]
fn not_inside() {
let rect = Rect {
left: -1.0,
right: 1.0,
bottom: -1.0,
top: 1.0,
};
let point = na::Point2::new(-2.0, 2.0);
assert!(
rect.contains(&point.coords) == false,
"the rectangle {:#?} should not contain the point {}",
rect,
point
);
}
#[test]
fn inside() {
let rect = Rect {
left: -1.0,
right: 1.0,
bottom: -1.0,
top: 1.0,
};
let point = na::Point2::new(0.5, -0.5);
assert!(
rect.contains(&point.coords) == true,
"the rectangle {:#?} should contain the point {}",
rect,
point
);
}
}
| 22.30137 | 78 | 0.442875 |
f95c6df535756dcff43c44627a4d70d643d717e0 | 4,812 | #[doc = "Register `IC_DMA_RDLR` reader"]
pub struct R(crate::R<IC_DMA_RDLR_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<IC_DMA_RDLR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<IC_DMA_RDLR_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<IC_DMA_RDLR_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `IC_DMA_RDLR` writer"]
pub struct W(crate::W<IC_DMA_RDLR_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<IC_DMA_RDLR_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<IC_DMA_RDLR_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<IC_DMA_RDLR_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `DMARDL` reader - Receive Data Level. This bit field controls the level at which a DMA request is made by the receive logic. The watermark level = DMARDL+1; that is, dma_rx_req is generated when the number of valid data entries in the receive FIFO is equal to or more than this field value + 1, and RDMAE =1. For instance, when DMARDL is 0, then dma_rx_req is asserted when 1 or more data entries are present in the receive FIFO.
Reset value: 0x0"]
pub struct DMARDL_R(crate::FieldReader<u8, u8>);
impl DMARDL_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
DMARDL_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for DMARDL_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `DMARDL` writer - Receive Data Level. This bit field controls the level at which a DMA request is made by the receive logic. The watermark level = DMARDL+1; that is, dma_rx_req is generated when the number of valid data entries in the receive FIFO is equal to or more than this field value + 1, and RDMAE =1. For instance, when DMARDL is 0, then dma_rx_req is asserted when 1 or more data entries are present in the receive FIFO.
Reset value: 0x0"]
pub struct DMARDL_W<'a> {
w: &'a mut W,
}
impl<'a> DMARDL_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
}
}
impl R {
#[doc = "Bits 0:3 - Receive Data Level. This bit field controls the level at which a DMA request is made by the receive logic. The watermark level = DMARDL+1; that is, dma_rx_req is generated when the number of valid data entries in the receive FIFO is equal to or more than this field value + 1, and RDMAE =1. For instance, when DMARDL is 0, then dma_rx_req is asserted when 1 or more data entries are present in the receive FIFO.
Reset value: 0x0"]
#[inline(always)]
pub fn dmardl(&self) -> DMARDL_R {
DMARDL_R::new((self.bits & 0x0f) as u8)
}
}
impl W {
#[doc = "Bits 0:3 - Receive Data Level. This bit field controls the level at which a DMA request is made by the receive logic. The watermark level = DMARDL+1; that is, dma_rx_req is generated when the number of valid data entries in the receive FIFO is equal to or more than this field value + 1, and RDMAE =1. For instance, when DMARDL is 0, then dma_rx_req is asserted when 1 or more data entries are present in the receive FIFO.
Reset value: 0x0"]
#[inline(always)]
pub fn dmardl(&mut self) -> DMARDL_W {
DMARDL_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 = "I2C Receive Data Level Register
This register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).
For information about available fields see [ic_dma_rdlr](index.html) module"]
pub struct IC_DMA_RDLR_SPEC;
impl crate::RegisterSpec for IC_DMA_RDLR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [ic_dma_rdlr::R](R) reader structure"]
impl crate::Readable for IC_DMA_RDLR_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [ic_dma_rdlr::W](W) writer structure"]
impl crate::Writable for IC_DMA_RDLR_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets IC_DMA_RDLR to value 0"]
impl crate::Resettable for IC_DMA_RDLR_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| 41.482759 | 446 | 0.665004 |
d6e5d3d48f18c6dd4ee269ff53e989b320f14cbc | 10,447 | // 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::AppInfo;
use crate::AppLaunchContext;
use glib::object::IsA;
use glib::translate::*;
use std::boxed::Box as Box_;
use std::fmt;
#[cfg(any(feature = "v2_60", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_60")))]
use std::mem;
use std::ptr;
glib::wrapper! {
#[doc(alias = "GDesktopAppInfo")]
pub struct DesktopAppInfo(Object<ffi::GDesktopAppInfo, ffi::GDesktopAppInfoClass>) @implements AppInfo;
match fn {
type_ => || ffi::g_desktop_app_info_get_type(),
}
}
impl DesktopAppInfo {
#[doc(alias = "g_desktop_app_info_new")]
pub fn new(desktop_id: &str) -> Option<DesktopAppInfo> {
unsafe { from_glib_full(ffi::g_desktop_app_info_new(desktop_id.to_glib_none().0)) }
}
#[doc(alias = "g_desktop_app_info_new_from_filename")]
#[doc(alias = "new_from_filename")]
pub fn from_filename(filename: impl AsRef<std::path::Path>) -> Option<DesktopAppInfo> {
unsafe {
from_glib_full(ffi::g_desktop_app_info_new_from_filename(
filename.as_ref().to_glib_none().0,
))
}
}
#[doc(alias = "g_desktop_app_info_new_from_keyfile")]
#[doc(alias = "new_from_keyfile")]
pub fn from_keyfile(key_file: &glib::KeyFile) -> Option<DesktopAppInfo> {
unsafe {
from_glib_full(ffi::g_desktop_app_info_new_from_keyfile(
key_file.to_glib_none().0,
))
}
}
#[doc(alias = "g_desktop_app_info_get_action_name")]
#[doc(alias = "get_action_name")]
pub fn action_name(&self, action_name: &str) -> glib::GString {
unsafe {
from_glib_full(ffi::g_desktop_app_info_get_action_name(
self.to_glib_none().0,
action_name.to_glib_none().0,
))
}
}
#[doc(alias = "g_desktop_app_info_get_boolean")]
#[doc(alias = "get_boolean")]
pub fn boolean(&self, key: &str) -> bool {
unsafe {
from_glib(ffi::g_desktop_app_info_get_boolean(
self.to_glib_none().0,
key.to_glib_none().0,
))
}
}
#[doc(alias = "g_desktop_app_info_get_categories")]
#[doc(alias = "get_categories")]
pub fn categories(&self) -> Option<glib::GString> {
unsafe {
from_glib_none(ffi::g_desktop_app_info_get_categories(
self.to_glib_none().0,
))
}
}
#[doc(alias = "g_desktop_app_info_get_filename")]
#[doc(alias = "get_filename")]
pub fn filename(&self) -> Option<std::path::PathBuf> {
unsafe { from_glib_none(ffi::g_desktop_app_info_get_filename(self.to_glib_none().0)) }
}
#[doc(alias = "g_desktop_app_info_get_generic_name")]
#[doc(alias = "get_generic_name")]
pub fn generic_name(&self) -> Option<glib::GString> {
unsafe {
from_glib_none(ffi::g_desktop_app_info_get_generic_name(
self.to_glib_none().0,
))
}
}
#[doc(alias = "g_desktop_app_info_get_is_hidden")]
#[doc(alias = "get_is_hidden")]
pub fn is_hidden(&self) -> bool {
unsafe { from_glib(ffi::g_desktop_app_info_get_is_hidden(self.to_glib_none().0)) }
}
#[doc(alias = "g_desktop_app_info_get_keywords")]
#[doc(alias = "get_keywords")]
pub fn keywords(&self) -> Vec<glib::GString> {
unsafe {
FromGlibPtrContainer::from_glib_none(ffi::g_desktop_app_info_get_keywords(
self.to_glib_none().0,
))
}
}
#[cfg(any(feature = "v2_56", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_56")))]
#[doc(alias = "g_desktop_app_info_get_locale_string")]
#[doc(alias = "get_locale_string")]
pub fn locale_string(&self, key: &str) -> Option<glib::GString> {
unsafe {
from_glib_full(ffi::g_desktop_app_info_get_locale_string(
self.to_glib_none().0,
key.to_glib_none().0,
))
}
}
#[doc(alias = "g_desktop_app_info_get_nodisplay")]
#[doc(alias = "get_nodisplay")]
pub fn is_nodisplay(&self) -> bool {
unsafe { from_glib(ffi::g_desktop_app_info_get_nodisplay(self.to_glib_none().0)) }
}
#[doc(alias = "g_desktop_app_info_get_show_in")]
#[doc(alias = "get_show_in")]
pub fn shows_in(&self, desktop_env: Option<&str>) -> bool {
unsafe {
from_glib(ffi::g_desktop_app_info_get_show_in(
self.to_glib_none().0,
desktop_env.to_glib_none().0,
))
}
}
#[doc(alias = "g_desktop_app_info_get_startup_wm_class")]
#[doc(alias = "get_startup_wm_class")]
pub fn startup_wm_class(&self) -> Option<glib::GString> {
unsafe {
from_glib_none(ffi::g_desktop_app_info_get_startup_wm_class(
self.to_glib_none().0,
))
}
}
#[doc(alias = "g_desktop_app_info_get_string")]
#[doc(alias = "get_string")]
pub fn string(&self, key: &str) -> Option<glib::GString> {
unsafe {
from_glib_full(ffi::g_desktop_app_info_get_string(
self.to_glib_none().0,
key.to_glib_none().0,
))
}
}
#[cfg(any(feature = "v2_60", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v2_60")))]
#[doc(alias = "g_desktop_app_info_get_string_list")]
#[doc(alias = "get_string_list")]
pub fn string_list(&self, key: &str) -> Vec<glib::GString> {
unsafe {
let mut length = mem::MaybeUninit::uninit();
let ret = FromGlibContainer::from_glib_full_num(
ffi::g_desktop_app_info_get_string_list(
self.to_glib_none().0,
key.to_glib_none().0,
length.as_mut_ptr(),
),
length.assume_init() as usize,
);
ret
}
}
#[doc(alias = "g_desktop_app_info_has_key")]
pub fn has_key(&self, key: &str) -> bool {
unsafe {
from_glib(ffi::g_desktop_app_info_has_key(
self.to_glib_none().0,
key.to_glib_none().0,
))
}
}
#[doc(alias = "g_desktop_app_info_launch_action")]
pub fn launch_action(
&self,
action_name: &str,
launch_context: Option<&impl IsA<AppLaunchContext>>,
) {
unsafe {
ffi::g_desktop_app_info_launch_action(
self.to_glib_none().0,
action_name.to_glib_none().0,
launch_context.map(|p| p.as_ref()).to_glib_none().0,
);
}
}
#[doc(alias = "g_desktop_app_info_launch_uris_as_manager")]
pub fn launch_uris_as_manager(
&self,
uris: &[&str],
launch_context: Option<&impl IsA<AppLaunchContext>>,
spawn_flags: glib::SpawnFlags,
user_setup: Option<Box_<dyn FnOnce() + 'static>>,
pid_callback: Option<&mut dyn (FnMut(&DesktopAppInfo, glib::Pid))>,
) -> Result<(), glib::Error> {
let user_setup_data: Box_<Option<Box_<dyn FnOnce() + 'static>>> = Box_::new(user_setup);
unsafe extern "C" fn user_setup_func(user_data: glib::ffi::gpointer) {
let callback: Box_<Option<Box_<dyn FnOnce() + 'static>>> =
Box_::from_raw(user_data as *mut _);
let callback = (*callback).expect("cannot get closure...");
callback()
}
let user_setup = if user_setup_data.is_some() {
Some(user_setup_func as _)
} else {
None
};
let pid_callback_data: Option<&mut dyn (FnMut(&DesktopAppInfo, glib::Pid))> = pid_callback;
unsafe extern "C" fn pid_callback_func(
appinfo: *mut ffi::GDesktopAppInfo,
pid: glib::ffi::GPid,
user_data: glib::ffi::gpointer,
) {
let appinfo = from_glib_borrow(appinfo);
let pid = from_glib(pid);
let callback: *mut Option<&mut dyn (FnMut(&DesktopAppInfo, glib::Pid))> =
user_data as *const _ as usize
as *mut Option<&mut dyn (FnMut(&DesktopAppInfo, glib::Pid))>;
if let Some(ref mut callback) = *callback {
callback(&appinfo, pid)
} else {
panic!("cannot get closure...")
};
}
let pid_callback = if pid_callback_data.is_some() {
Some(pid_callback_func as _)
} else {
None
};
let super_callback0: Box_<Option<Box_<dyn FnOnce() + 'static>>> = user_setup_data;
let super_callback1: &Option<&mut dyn (FnMut(&DesktopAppInfo, glib::Pid))> =
&pid_callback_data;
unsafe {
let mut error = ptr::null_mut();
let is_ok = ffi::g_desktop_app_info_launch_uris_as_manager(
self.to_glib_none().0,
uris.to_glib_none().0,
launch_context.map(|p| p.as_ref()).to_glib_none().0,
spawn_flags.into_glib(),
user_setup,
Box_::into_raw(super_callback0) as *mut _,
pid_callback,
super_callback1 as *const _ as usize as *mut _,
&mut error,
);
assert_eq!(is_ok == 0, !error.is_null());
if error.is_null() {
Ok(())
} else {
Err(from_glib_full(error))
}
}
}
#[doc(alias = "g_desktop_app_info_list_actions")]
pub fn list_actions(&self) -> Vec<glib::GString> {
unsafe {
FromGlibPtrContainer::from_glib_none(ffi::g_desktop_app_info_list_actions(
self.to_glib_none().0,
))
}
}
#[doc(alias = "g_desktop_app_info_get_implementations")]
#[doc(alias = "get_implementations")]
pub fn implementations(interface: &str) -> Vec<DesktopAppInfo> {
unsafe {
FromGlibPtrContainer::from_glib_full(ffi::g_desktop_app_info_get_implementations(
interface.to_glib_none().0,
))
}
}
}
impl fmt::Display for DesktopAppInfo {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("DesktopAppInfo")
}
}
| 34.478548 | 107 | 0.570307 |
8f1cff2905579aab5850f421cb4b0ebb991b6eea | 1,244 | /*
* Ory APIs
*
* Documentation for all public and administrative Ory APIs. Administrative APIs can only be accessed with a valid Personal Access Token. Public APIs are mostly used in browsers.
*
* The version of the OpenAPI document: v0.0.1-alpha.30
* Contact: [email protected]
* Generated by: https://openapi-generator.tech
*/
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SubmitSelfServiceLoginFlowWithLookupSecretMethodBody {
/// Sending the anti-csrf token is only required for browser login flows.
#[serde(rename = "csrf_token", skip_serializing_if = "Option::is_none")]
pub csrf_token: Option<String>,
/// The lookup secret.
#[serde(rename = "lookup_secret")]
pub lookup_secret: String,
/// Method should be set to \"lookup_secret\" when logging in using the lookup_secret strategy.
#[serde(rename = "method")]
pub method: String,
}
impl SubmitSelfServiceLoginFlowWithLookupSecretMethodBody {
pub fn new(lookup_secret: String, method: String) -> SubmitSelfServiceLoginFlowWithLookupSecretMethodBody {
SubmitSelfServiceLoginFlowWithLookupSecretMethodBody {
csrf_token: None,
lookup_secret,
method,
}
}
}
| 32.736842 | 179 | 0.71463 |
d9d291ed59eafbd194de809e69e5e068aa9a2f7c | 6,762 | // 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::borrow::Cow;
use common_arrow::arrow::compute::arity::unary;
use crate::prelude::*;
macro_rules! apply {
($self:expr, $f:expr) => {{
if $self.null_count() == 0 {
$self.into_no_null_iter().map($f).collect()
} else {
$self.inner().iter().map(|opt_v| opt_v.map($f)).collect()
}
}};
}
macro_rules! apply_enumerate {
($self:expr, $f:expr) => {{
if $self.null_count() == 0 {
$self.into_no_null_iter().enumerate().map($f).collect()
} else {
$self
.inner()
.iter()
.enumerate()
.map(|(idx, opt_v)| opt_v.map(|v| $f((idx, v))))
.collect()
}
}};
}
pub trait ArrayApply<'a, A, B> {
/// Apply a closure elementwise and cast to a Numeric DFPrimitiveArray. This is fastest when the null check branching is more expensive
/// than the closure application.
///
/// Null values remain null.
fn apply_cast_numeric<F, S>(&'a self, f: F) -> DFPrimitiveArray<S>
where
F: Fn(A) -> S + Copy,
S: DFPrimitiveType;
/// Apply a closure on optional values and cast to Numeric DFPrimitiveArray without null values.
fn branch_apply_cast_numeric_no_null<F, S>(&'a self, f: F) -> DFPrimitiveArray<S>
where
F: Fn(Option<A>) -> S + Copy,
S: DFPrimitiveType;
/// Apply a closure elementwise. This is fastest when the null check branching is more expensive
/// than the closure application. Often it is.
///
/// Null values remain null.
#[must_use]
fn apply<F>(&'a self, f: F) -> Self
where F: Fn(A) -> B + Copy;
/// Apply a closure elementwise. The closure gets the index of the element as first argument.
#[must_use]
fn apply_with_idx<F>(&'a self, f: F) -> Self
where F: Fn((usize, A)) -> B + Copy;
/// Apply a closure elementwise. The closure gets the index of the element as first argument.
#[must_use]
fn apply_with_idx_on_opt<F>(&'a self, f: F) -> Self
where F: Fn((usize, Option<A>)) -> Option<B> + Copy;
}
impl<'a, T> ArrayApply<'a, T, T> for DFPrimitiveArray<T>
where T: DFPrimitiveType
{
fn apply_cast_numeric<F, S>(&self, f: F) -> DFPrimitiveArray<S>
where
F: Fn(T) -> S + Copy,
S: DFPrimitiveType,
{
let array = unary(self.inner(), f, S::data_type().to_arrow());
DFPrimitiveArray::<S>::new(array)
}
fn branch_apply_cast_numeric_no_null<F, S>(&self, f: F) -> DFPrimitiveArray<S>
where
F: Fn(Option<T>) -> S + Copy,
S: DFPrimitiveType,
{
let array = unary(self.inner(), |n| f(Some(n)), S::data_type().to_arrow());
DFPrimitiveArray::<S>::new(array)
}
fn apply<F>(&'a self, f: F) -> Self
where F: Fn(T) -> T + Copy {
let array = unary(self.inner(), f, T::data_type().to_arrow());
DFPrimitiveArray::<T>::new(array)
}
fn apply_with_idx<F>(&'a self, f: F) -> Self
where F: Fn((usize, T)) -> T + Copy {
if self.null_count() == 0 {
let ca: Self = self
.into_no_null_iter()
.enumerate()
.map(|(idx, v)| f((idx, *v)))
.collect_trusted();
ca
} else {
self.into_iter()
.enumerate()
.map(|(idx, opt_v)| opt_v.map(|v| f((idx, *v))))
.collect_trusted()
}
}
fn apply_with_idx_on_opt<F>(&'a self, f: F) -> Self
where F: Fn((usize, Option<T>)) -> Option<T> + Copy {
self.into_iter()
.enumerate()
.map(|(idx, v)| f((idx, v.copied())))
.collect_trusted()
}
}
impl<'a> ArrayApply<'a, bool, bool> for DFBooleanArray {
fn apply_cast_numeric<F, S>(&self, f: F) -> DFPrimitiveArray<S>
where
F: Fn(bool) -> S + Copy,
S: DFPrimitiveType,
{
let values = self.array.values().iter().map(f);
let values = AlignedVec::<_>::from_trusted_len_iter(values);
let validity = self.array.validity().cloned();
to_primitive::<S>(values, validity)
}
fn branch_apply_cast_numeric_no_null<F, S>(&self, f: F) -> DFPrimitiveArray<S>
where
F: Fn(Option<bool>) -> S + Copy,
S: DFPrimitiveType,
{
let av: AlignedVec<_> = self.into_iter().map(f).collect();
to_primitive::<S>(av, None)
}
fn apply<F>(&self, f: F) -> Self
where F: Fn(bool) -> bool + Copy {
apply!(self, f)
}
fn apply_with_idx<F>(&'a self, f: F) -> Self
where F: Fn((usize, bool)) -> bool + Copy {
apply_enumerate!(self, f)
}
fn apply_with_idx_on_opt<F>(&'a self, f: F) -> Self
where F: Fn((usize, Option<bool>)) -> Option<bool> + Copy {
self.into_iter().enumerate().map(f).collect()
}
}
impl<'a> ArrayApply<'a, &'a [u8], Cow<'a, [u8]>> for DFStringArray {
fn apply_cast_numeric<F, S>(&'a self, f: F) -> DFPrimitiveArray<S>
where
F: Fn(&'a [u8]) -> S + Copy,
S: DFPrimitiveType,
{
let arr = self.inner();
let values_iter = arr.values_iter().map(f);
let av = AlignedVec::<_>::from_trusted_len_iter(values_iter);
let validity = self.validity();
to_primitive::<S>(av, validity.cloned())
}
fn branch_apply_cast_numeric_no_null<F, S>(&'a self, f: F) -> DFPrimitiveArray<S>
where
F: Fn(Option<&'a [u8]>) -> S + Copy,
S: DFPrimitiveType,
{
let av: AlignedVec<_> = AlignedVec::<_>::from_trusted_len_iter(self.inner().iter().map(f));
let validity = self.validity();
to_primitive::<S>(av, validity.cloned())
}
fn apply<F>(&'a self, f: F) -> Self
where F: Fn(&'a [u8]) -> Cow<'a, [u8]> + Copy {
apply!(self, f)
}
fn apply_with_idx<F>(&'a self, f: F) -> Self
where F: Fn((usize, &'a [u8])) -> Cow<'a, [u8]> + Copy {
apply_enumerate!(self, f)
}
fn apply_with_idx_on_opt<F>(&'a self, f: F) -> Self
where F: Fn((usize, Option<&'a [u8]>)) -> Option<Cow<'a, [u8]>> + Copy {
self.into_iter().enumerate().map(f).collect()
}
}
| 32.666667 | 139 | 0.561668 |
3a14197c77bec3ba289315fc1cfb8773f58a6a2f | 3,526 | //! Implementation of panics via stack unwinding
//!
//! This crate is an implementation of panics in Rust using "most native" stack
//! unwinding mechanism of the platform this is being compiled for. This
//! essentially gets categorized into three buckets currently:
//!
//! 1. MSVC targets use SEH in the `seh.rs` file.
//! 2. Emscripten uses C++ exceptions in the `emcc.rs` file.
//! 3. All other targets use libunwind/libgcc in the `gcc.rs` file.
//!
//! More documentation about each implementation can be found in the respective
//! module.
#![no_std]
#![unstable(feature = "panic_unwind", issue = "32837")]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/",
issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/")]
#![feature(core_intrinsics)]
#![feature(lang_items)]
#![feature(libc)]
#![feature(nll)]
#![feature(panic_unwind)]
#![feature(raw)]
#![feature(staged_api)]
#![feature(std_internals)]
#![feature(unwind_attributes)]
#![panic_runtime]
#![feature(panic_runtime)]
use alloc::boxed::Box;
use core::intrinsics;
use core::mem;
use core::raw;
use core::panic::BoxMeUp;
cfg_if::cfg_if! {
if #[cfg(target_os = "emscripten")] {
#[path = "emcc.rs"]
mod imp;
} else if #[cfg(target_arch = "wasm32")] {
#[path = "dummy.rs"]
mod imp;
} else if #[cfg(target_os = "hermit")] {
#[path = "hermit.rs"]
mod imp;
} else if #[cfg(all(target_env = "msvc", target_arch = "aarch64"))] {
#[path = "dummy.rs"]
mod imp;
} else if #[cfg(target_env = "msvc")] {
#[path = "seh.rs"]
mod imp;
} else {
// Rust runtime's startup objects depend on these symbols, so make them public.
#[cfg(all(target_os="windows", target_arch = "x86", target_env="gnu"))]
pub use imp::eh_frame_registry::*;
#[path = "gcc.rs"]
mod imp;
}
}
mod dwarf;
// Entry point for catching an exception, implemented using the `try` intrinsic
// in the compiler.
//
// The interaction between the `payload` function and the compiler is pretty
// hairy and tightly coupled, for more information see the compiler's
// implementation of this.
#[no_mangle]
pub unsafe extern "C" fn __rust_maybe_catch_panic(f: fn(*mut u8),
data: *mut u8,
data_ptr: *mut usize,
vtable_ptr: *mut usize)
-> u32 {
let mut payload = imp::payload();
if intrinsics::r#try(f, data, &mut payload as *mut _ as *mut _) == 0 {
0
} else {
let obj = mem::transmute::<_, raw::TraitObject>(imp::cleanup(payload));
*data_ptr = obj.data as usize;
*vtable_ptr = obj.vtable as usize;
1
}
}
// Entry point for raising an exception, just delegates to the platform-specific
// implementation.
#[no_mangle]
#[unwind(allowed)]
pub unsafe extern "C" fn __rust_start_panic(payload: usize) -> u32 {
let payload = payload as *mut &mut dyn BoxMeUp;
let payload = (*payload).take_box();
// Miri panic support: cfg'd out of normal builds just to be sure.
// When going through normal codegen, `miri_start_panic` is a NOP, so the
// Miri-enabled sysroot still supports normal unwinding. But when executed in
// Miri, this line initiates unwinding.
#[cfg(miri)]
core::intrinsics::miri_start_panic(payload);
imp::panic(Box::from_raw(payload))
}
| 33.580952 | 87 | 0.613159 |
9bb66ef80d3c49b55da27dfe6babc26c1ed6e93d | 11,201 | use crate::mount::Mount;
use crate::theme::Theme;
use colored::*;
use std::cmp;
use std::fmt;
use std::io::{self, stdout, Write};
use std::path::Path;
pub fn format_count(num: f64, delimiter: f64) -> String {
let units = ["B", "k", "M", "G", "T", "P", "E", "Z", "Y"];
if num < 1_f64 {
return format!("{}", num);
}
let exponent = cmp::min(num.log(delimiter).floor() as i32, (units.len() - 1) as i32);
let pretty_bytes = format!("{:.*}", 1, num / delimiter.powi(exponent));
let unit = units[exponent as usize];
format!("{}{}", pretty_bytes, unit)
}
#[inline]
pub fn format_percentage(percentage: Option<f32>) -> String {
match percentage {
Some(percentage) => format!(
"{:>5.1}{}",
(percentage * 10.0).round() / 10.0,
"%".color(Color::White)
),
None => format!("{:>6}", "-"),
}
}
pub fn bar(width: usize, percentage: Option<f32>, theme: &Theme) -> String {
let fill_len_total = (percentage.unwrap_or(0.0) as f32 / 100.0 * width as f32).ceil() as usize;
let fill_len_low = std::cmp::min(
fill_len_total,
(width as f32 * theme.threshold_usage_medium / 100.0).ceil() as usize,
);
let fill_len_medium = std::cmp::min(
fill_len_total,
(width as f32 * theme.threshold_usage_high / 100.0).ceil() as usize,
) - fill_len_low;
let fill_len_high = fill_len_total - fill_len_low - fill_len_medium;
let color_empty = match percentage {
Some(_) => theme.color_usage_low,
None => theme.color_usage_void,
}
.unwrap_or(Color::Green);
let fill_low = theme
.char_bar_filled
.to_string()
.repeat(fill_len_low)
.color(theme.color_usage_low.unwrap_or(Color::Green));
let fill_medium = theme
.char_bar_filled
.to_string()
.repeat(fill_len_medium)
.color(theme.color_usage_medium.unwrap_or(Color::Yellow));
let fill_high = theme
.char_bar_filled
.to_string()
.repeat(fill_len_high)
.color(theme.color_usage_high.unwrap_or(Color::Red));
let empty = theme
.char_bar_empty
.to_string()
.repeat(width - fill_len_total)
.color(color_empty);
format!(
"{}{}{}{}{}{}",
theme.char_bar_open, fill_low, fill_medium, fill_high, empty, theme.char_bar_close
)
}
pub fn lvm_alias(device: &str) -> Option<String> {
if !device.starts_with("/dev/mapper/") {
return None;
}
let device = &device["/dev/mapper/".len()..].replace("--", "$$");
if !device.contains('-') {
return None;
}
let mut it = device.splitn(2, '-');
let vg = it.next().unwrap_or("");
let lv = it.next().unwrap_or("");
Some(format!("/dev/{}/{}", vg, lv).replace("$$", "-"))
}
#[inline]
pub fn get_best_mount_match<'a>(path: &Path, mnts: &'a [Mount]) -> Option<&'a Mount> {
let scores = mnts
.iter()
.map(|mnt| (calculate_path_match_score(path, mnt), mnt));
let best = scores.max_by_key(|x| x.0)?;
Some(best.1)
}
#[inline]
pub fn calculate_path_match_score(path: &Path, mnt: &Mount) -> usize {
if path.starts_with(&mnt.mnt_dir) {
mnt.mnt_dir.len()
} else {
0
}
}
#[inline]
pub fn cmp_by_capacity_and_dir_name(a: &Mount, b: &Mount) -> cmp::Ordering {
u64::min(1, a.capacity)
.cmp(&u64::min(1, b.capacity))
.reverse()
.then(a.mnt_dir.cmp(&b.mnt_dir))
}
#[inline]
pub fn mnt_matches_filter(mnt: &Mount, filter: &str) -> bool {
filter.strip_suffix('*').map_or_else(
|| mnt.mnt_fsname == filter,
|start| mnt.mnt_fsname.starts_with(start),
)
}
#[inline]
pub fn calc_total(mnts: &[Mount]) -> Mount {
let mut total = Mount::named("total".to_string());
total.free = mnts.iter().map(|mnt| mnt.free).sum();
total.used = mnts.iter().map(|mnt| mnt.used).sum();
total.capacity = mnts.iter().map(|mnt| mnt.capacity).sum();
total
}
#[inline]
pub fn try_print(args: fmt::Arguments) -> io::Result<()> {
stdout().write_fmt(args)
}
#[macro_export]
macro_rules! try_print {
($($arg:tt)*) => ($crate::try_print(format_args!($($arg)*)));
}
#[macro_export]
macro_rules! try_println {
($fmt:expr) => (try_print!(concat!($fmt, "\n")));
($fmt:expr, $($arg:tt)*) => (try_print!(concat!($fmt, "\n"), $($arg)*));
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
#[test]
fn format_count_zero() {
let s = format_count(0.0, 1024.0);
assert_eq!(s, "0");
}
#[test]
fn format_count_bytes() {
let s = format_count(12.0, 1024.0);
assert_eq!(s, "12.0B");
}
#[test]
fn format_count_megabyte() {
let s = format_count(12693000.0, 1024.0);
assert_eq!(s, "12.1M");
}
#[test]
fn format_count_very_large() {
let s = format_count(2535301200456458802993406410752.0, 1024.0);
assert_eq!(s, "2097152.0Y");
}
#[test]
fn format_percentage_zero() {
let s = format_percentage(Option::Some(0f32));
assert_eq!(s, format!(" 0.0{}", "%".color(Color::White)));
}
#[test]
fn format_percentage_fraction() {
let s = format_percentage(Option::Some(0.3333333333333333f32));
assert_eq!(s, format!(" 0.3{}", "%".color(Color::White)));
}
#[test]
fn format_percentage_hundred() {
let s = format_percentage(Option::Some(100f32));
assert_eq!(s, format!("100.0{}", "%".color(Color::White)));
}
#[test]
fn format_percentage_none() {
let s = format_percentage(Option::None);
assert_eq!(s, " -");
}
#[test]
fn lvm_alias_none() {
let s = lvm_alias("/dev/mapper/crypto");
assert_eq!(s, None);
}
#[test]
fn lvm_alias_simple() {
let s = lvm_alias("/dev/mapper/crypto-foo");
assert_eq!(s, Some("/dev/crypto/foo".to_string()));
}
#[test]
fn lvm_alias_two_dashes() {
let s = lvm_alias("/dev/mapper/crypto--foo");
assert_eq!(s, None);
}
#[test]
fn lvm_alias_three_dashes() {
let s = lvm_alias("/dev/mapper/crypto---foo");
assert_eq!(s, Some("/dev/crypto-/foo".to_string()));
}
#[test]
fn lvm_alias_four_dashes() {
let s = lvm_alias("/dev/mapper/crypto----foo");
assert_eq!(s, None);
}
#[test]
fn lvm_alias_five_dashes() {
let s = lvm_alias("/dev/mapper/crypto-----foo");
assert_eq!(s, Some("/dev/crypto--/foo".to_string()));
}
#[test]
fn get_best_mount_match_simple() {
let mut mnt1 = Mount::named("foo".into());
mnt1.mnt_dir = "/a".to_string();
let mut mnt2 = Mount::named("bar".into());
mnt2.mnt_dir = "/a/b".to_string();
let mut mnt3 = Mount::named("fizz".into());
mnt3.mnt_dir = "/a/b/c".to_string();
let mut mnt4 = Mount::named("buzz".into());
mnt4.mnt_dir = "/a/b/c/d".to_string();
let mnts = &[mnt1, mnt2, mnt3, mnt4];
let matched = get_best_mount_match(&PathBuf::from("/a/b/c"), mnts).unwrap();
assert_eq!(matched.mnt_dir, "/a/b/c");
}
#[test]
fn calculate_path_match_score_simple() {
let mut mnt1 = Mount::named("foo".into());
mnt1.mnt_dir = "/a/s/d".to_string();
let score = calculate_path_match_score(&PathBuf::from("/a/s/d/f"), &mnt1);
assert_eq!(score, 6);
}
#[test]
fn cmp_by_capacity_and_dir_name_equal() {
let mnt1 = Mount::named("foo".into());
let mnt2 = Mount::named("bar".into());
let ord = cmp_by_capacity_and_dir_name(&mnt1, &mnt2);
assert_eq!(ord, cmp::Ordering::Equal);
}
#[test]
fn cmp_by_capacity_and_dir_name_greater_capacity_greater_name() {
let mut mnt1 = Mount::named("foo".into());
mnt1.capacity = 123;
mnt1.mnt_dir = "/b".to_string();
let mut mnt2 = Mount::named("bar".into());
mnt2.capacity = 64;
mnt2.mnt_dir = "/a".to_string();
let ord = cmp_by_capacity_and_dir_name(&mnt1, &mnt2);
assert_eq!(ord, cmp::Ordering::Greater);
}
#[test]
fn cmp_by_capacity_and_dir_name_smaller_capacity_greater_name() {
let mut mnt1 = Mount::named("foo".into());
mnt1.capacity = 64;
mnt1.mnt_dir = "/b".to_string();
let mut mnt2 = Mount::named("bar".into());
mnt2.capacity = 123;
mnt2.mnt_dir = "/a".to_string();
let ord = cmp_by_capacity_and_dir_name(&mnt1, &mnt2);
assert_eq!(ord, cmp::Ordering::Greater);
}
#[test]
fn cmp_by_capacity_and_dir_name_greater_capacity_smaller_name() {
let mut mnt1 = Mount::named("foo".into());
mnt1.capacity = 123;
mnt1.mnt_dir = "/a".to_string();
let mut mnt2 = Mount::named("bar".into());
mnt2.capacity = 64;
mnt2.mnt_dir = "/b".to_string();
let ord = cmp_by_capacity_and_dir_name(&mnt1, &mnt2);
assert_eq!(ord, cmp::Ordering::Less);
}
#[test]
fn cmp_by_capacity_and_dir_name_smaller_capacity_smaller_name() {
let mut mnt1 = Mount::named("foo".into());
mnt1.capacity = 64;
mnt1.mnt_dir = "/a".to_string();
let mut mnt2 = Mount::named("bar".into());
mnt2.capacity = 123;
mnt2.mnt_dir = "/b".to_string();
let ord = cmp_by_capacity_and_dir_name(&mnt1, &mnt2);
assert_eq!(ord, cmp::Ordering::Less);
}
#[test]
fn cmp_by_capacity_and_dir_name_equal_capacity_greater_name() {
let mut mnt1 = Mount::named("foo".into());
mnt1.capacity = 123;
mnt1.mnt_dir = "/b".to_string();
let mut mnt2 = Mount::named("bar".into());
mnt2.capacity = 123;
mnt2.mnt_dir = "/a".to_string();
let ord = cmp_by_capacity_and_dir_name(&mnt1, &mnt2);
assert_eq!(ord, cmp::Ordering::Greater);
}
#[test]
fn cmp_by_capacity_and_dir_name_greater_capacity_equal_name() {
let mut mnt1 = Mount::named("foo".into());
mnt1.capacity = 123;
mnt1.mnt_dir = "/a".to_string();
let mut mnt2 = Mount::named("bar".into());
mnt2.capacity = 64;
mnt2.mnt_dir = "/a".to_string();
let ord = cmp_by_capacity_and_dir_name(&mnt1, &mnt2);
assert_eq!(ord, cmp::Ordering::Equal);
}
#[test]
fn calc_total_simple() {
let mut mnt1 = Mount::named("foo".into());
mnt1.free = 123;
mnt1.used = 456;
mnt1.capacity = 123 + 456;
let mut mnt2 = Mount::named("bar".into());
mnt2.free = 678;
mnt2.used = 9123;
mnt2.capacity = 678 + 9123;
let mut mnt3 = Mount::named("fizz".into());
mnt3.free = 4567;
mnt3.used = 0;
mnt3.capacity = 4567;
let mut mnt4 = Mount::named("buzz".into());
mnt4.free = 0;
mnt4.used = 890123;
mnt4.capacity = 890123;
let total = calc_total(&[mnt1, mnt2, mnt3, mnt4]);
assert_eq!(total.mnt_fsname, "total");
assert_eq!(total.free, 5368);
assert_eq!(total.used, 899702);
assert_eq!(total.capacity, 5368 + 899702);
}
}
| 29.55409 | 99 | 0.570128 |
4bcf4c93833ef064b106ee4c050b5910822a8be6 | 3,241 | use crate::*;
test_case!(expr, async move {
use gluesql_core::{
ast::IndexOperator::*,
executor::AlterError,
prelude::{Payload, Value::*},
};
run!(
r#"
CREATE TABLE Test (
id INTEGER,
num INTEGER,
name TEXT
)"#
);
run!(
r#"
INSERT INTO Test
(id, num, name)
VALUES
(1, 2, "Hello");
"#
);
test!(Ok(Payload::CreateIndex), "CREATE INDEX idx_id ON Test (id)");
test!(
Ok(Payload::CreateIndex),
"CREATE INDEX idx_typed_string ON Test ((id))"
);
test!(
Ok(Payload::CreateIndex),
"CREATE INDEX idx_binary_op ON Test (num || name);"
);
test!(
Ok(Payload::CreateIndex),
"CREATE INDEX idx_unary_op ON Test (-num);"
);
test!(
Ok(Payload::CreateIndex),
"CREATE INDEX idx_cast ON Test (CAST(id AS TEXT));"
);
test!(
Err(AlterError::IdentifierNotFound(expr!("100")).into()),
"CREATE INDEX idx_literal ON Test (100)"
);
test!(
Ok(Payload::Insert(1)),
r#"INSERT INTO Test VALUES (4, 7, "Well");"#
);
test!(
Ok(select!(
id | num | name
I64 | I64 | Str;
1 2 "Hello".to_owned();
4 7 "Well".to_owned()
)),
"SELECT id, num, name FROM Test"
);
test_idx!(
Ok(select!(
id | num | name
I64 | I64 | Str;
1 2 "Hello".to_owned()
)),
idx!(idx_id, LtEq, "1"),
"SELECT id, num, name FROM Test WHERE id <= 1"
);
test_idx!(
Ok(select!(
id | num | name
I64 | I64 | Str;
1 2 "Hello".to_owned()
)),
idx!(idx_id, LtEq, "(1)"),
"SELECT id, num, name FROM Test WHERE id <= (1)"
);
test_idx!(
Ok(select!(
id | num | name
I64 | I64 | Str;
1 2 "Hello".to_owned()
)),
idx!(idx_binary_op, Eq, r#""2Hello""#),
r#"SELECT id, num, name FROM Test WHERE num || name = "2Hello""#
);
test_idx!(
Ok(select!(
id | num | name
I64 | I64 | Str;
1 2 "Hello".to_owned()
)),
idx!(idx_binary_op, Eq, r#""2Hello""#),
r#"SELECT id, num, name FROM Test WHERE (num || name) = "2Hello""#
);
test_idx!(
Ok(select!(
id | num | name
I64 | I64 | Str;
4 7 "Well".to_owned()
)),
idx!(idx_binary_op, Eq, r#""7Well""#),
r#"SELECT id, num, name FROM Test WHERE "7Well" = (num || name)"#
);
test_idx!(
Ok(select!(
id | num | name
I64 | I64 | Str;
4 7 "Well".to_owned()
)),
idx!(idx_unary_op, Lt, "-2"),
"SELECT id, num, name FROM Test WHERE -num < -2"
);
test_idx!(
Ok(select!(
id | num | name
I64 | I64 | Str;
4 7 "Well".to_owned()
)),
idx!(idx_cast, Eq, r#""4""#),
r#"SELECT id, num, name FROM Test WHERE CAST(id AS TEXT) = "4""#
);
});
| 23.15 | 74 | 0.435668 |
ed97813932e8508ef0c0bb0ffdfce72f5ebf8859 | 44,968 | use std::collections::HashMap;
use std::cell::RefCell;
use std::default::Default;
use std::collections::BTreeMap;
use serde_json as json;
use std::io;
use std::fs;
use std::mem;
use std::thread::sleep;
use crate::client;
// ##############
// UTILITIES ###
// ############
// ########
// HUB ###
// ######
/// Central instance to access all QPXExpress related resource activities
///
/// # Examples
///
/// Instantiate a new hub
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate yup_oauth2 as oauth2;
/// extern crate google_qpxexpress1 as qpxexpress1;
/// use qpxexpress1::api::TripsSearchRequest;
/// use qpxexpress1::{Result, Error};
/// # async fn dox() {
/// use std::default::Default;
/// use oauth2;
/// use qpxexpress1::QPXExpress;
///
/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
/// // `client_secret`, among other things.
/// let secret: oauth2::ApplicationSecret = Default::default();
/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
/// // unless you replace `None` with the desired Flow.
/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
/// // retrieve them from storage.
/// let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// secret,
/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// ).build().await.unwrap();
/// let mut hub = QPXExpress::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = TripsSearchRequest::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.trips().search(req)
/// .doit().await;
///
/// match result {
/// Err(e) => match e {
/// // The Error enum provides details about what exactly happened.
/// // You can also just use its `Debug`, `Display` or `Error` traits
/// Error::HttpError(_)
/// |Error::Io(_)
/// |Error::MissingAPIKey
/// |Error::MissingToken(_)
/// |Error::Cancelled
/// |Error::UploadSizeLimitExceeded(_, _)
/// |Error::Failure(_)
/// |Error::BadRequest(_)
/// |Error::FieldClash(_)
/// |Error::JsonDecodeError(_, _) => println!("{}", e),
/// },
/// Ok(res) => println!("Success: {:?}", res),
/// }
/// # }
/// ```
pub struct QPXExpress<> {
client: hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>,
auth: oauth2::authenticator::Authenticator<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>>,
_user_agent: String,
_base_url: String,
_root_url: String,
}
impl<'a, > client::Hub for QPXExpress<> {}
impl<'a, > QPXExpress<> {
pub fn new(client: hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>, authenticator: oauth2::authenticator::Authenticator<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>>) -> QPXExpress<> {
QPXExpress {
client,
auth: authenticator,
_user_agent: "google-api-rust-client/2.0.4".to_string(),
_base_url: "https://www.googleapis.com/qpxExpress/v1/trips/".to_string(),
_root_url: "https://www.googleapis.com/".to_string(),
}
}
pub fn trips(&'a self) -> TripMethods<'a> {
TripMethods { hub: &self }
}
/// Set the user-agent header field to use in all requests to the server.
/// It defaults to `google-api-rust-client/2.0.4`.
///
/// Returns the previously set user-agent.
pub fn user_agent(&mut self, agent_name: String) -> String {
mem::replace(&mut self._user_agent, agent_name)
}
/// Set the base url to use in all requests to the server.
/// It defaults to `https://www.googleapis.com/qpxExpress/v1/trips/`.
///
/// Returns the previously set base url.
pub fn base_url(&mut self, new_base_url: String) -> String {
mem::replace(&mut self._base_url, new_base_url)
}
/// Set the root url to use in all requests to the server.
/// It defaults to `https://www.googleapis.com/`.
///
/// Returns the previously set root url.
pub fn root_url(&mut self, new_root_url: String) -> String {
mem::replace(&mut self._root_url, new_root_url)
}
}
// ############
// SCHEMAS ###
// ##########
/// The make, model, and type of an aircraft.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct AircraftData {
/// The aircraft code. For example, for a Boeing 777 the code would be 777.
pub code: Option<String>,
/// Identifies this as an aircraftData object. Value: the fixed string qpxexpress#aircraftData
pub kind: Option<String>,
/// The name of an aircraft, for example Boeing 777.
pub name: Option<String>,
}
impl client::Part for AircraftData {}
/// An airport.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct AirportData {
/// The city code an airport is located in. For example, for JFK airport, this is NYC.
pub city: Option<String>,
/// An airport's code. For example, for Boston Logan airport, this is BOS.
pub code: Option<String>,
/// Identifies this as an airport object. Value: the fixed string qpxexpress#airportData.
pub kind: Option<String>,
/// The name of an airport. For example, for airport BOS the name is "Boston Logan International".
pub name: Option<String>,
}
impl client::Part for AirportData {}
/// Information about an item of baggage.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct BagDescriptor {
/// Provides the commercial name for an optional service.
#[serde(rename="commercialName")]
pub commercial_name: Option<String>,
/// How many of this type of bag will be checked on this flight.
pub count: Option<i32>,
/// A description of the baggage.
pub description: Option<Vec<String>>,
/// Identifies this as a baggage object. Value: the fixed string qpxexpress#bagDescriptor.
pub kind: Option<String>,
/// The standard IATA subcode used to identify this optional service.
pub subcode: Option<String>,
}
impl client::Part for BagDescriptor {}
/// Information about a carrier (ie. an airline, bus line, railroad, etc) that might be useful to display to an end-user.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct CarrierData {
/// The IATA designator of a carrier (airline, etc). For example, for American Airlines, the code is AA.
pub code: Option<String>,
/// Identifies this as a kind of carrier (ie. an airline, bus line, railroad, etc). Value: the fixed string qpxexpress#carrierData.
pub kind: Option<String>,
/// The long, full name of a carrier. For example: American Airlines.
pub name: Option<String>,
}
impl client::Part for CarrierData {}
/// Information about a city that might be useful to an end-user; typically the city of an airport.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct CityData {
/// The IATA character ID of a city. For example, for Boston this is BOS.
pub code: Option<String>,
/// The two-character country code of the country the city is located in. For example, US for the United States of America.
pub country: Option<String>,
/// Identifies this as a city, typically with one or more airports. Value: the fixed string qpxexpress#cityData.
pub kind: Option<String>,
/// The full name of a city. An example would be: New York.
pub name: Option<String>,
}
impl client::Part for CityData {}
/// Detailed information about components found in the solutions of this response, including a trip's airport, city, taxes, airline, and aircraft.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Data {
/// The aircraft that is flying between an origin and destination.
pub aircraft: Option<Vec<AircraftData>>,
/// The airport of an origin or destination.
pub airport: Option<Vec<AirportData>>,
/// The airline carrier of the aircraft flying between an origin and destination. Allowed values are IATA carrier codes.
pub carrier: Option<Vec<CarrierData>>,
/// The city that is either the origin or destination of part of a trip.
pub city: Option<Vec<CityData>>,
/// Identifies this as QPX Express response resource, including a trip's airport, city, taxes, airline, and aircraft. Value: the fixed string qpxexpress#data.
pub kind: Option<String>,
/// The taxes due for flying between an origin and a destination.
pub tax: Option<Vec<TaxData>>,
}
impl client::Part for Data {}
/// Complete information about a fare used in the solution to a low-fare search query. In the airline industry a fare is a price an airline charges for one-way travel between two points. A fare typically contains a carrier code, two city codes, a price, and a fare basis. (A fare basis is a one-to-eight character alphanumeric code used to identify a fare.)
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct FareInfo {
/// no description provided
#[serde(rename="basisCode")]
pub basis_code: Option<String>,
/// The carrier of the aircraft or other vehicle commuting between two points.
pub carrier: Option<String>,
/// The city code of the city the trip ends at.
pub destination: Option<String>,
/// A unique identifier of the fare.
pub id: Option<String>,
/// Identifies this as a fare object. Value: the fixed string qpxexpress#fareInfo.
pub kind: Option<String>,
/// The city code of the city the trip begins at.
pub origin: Option<String>,
/// Whether this is a private fare, for example one offered only to select customers rather than the general public.
pub private: Option<bool>,
}
impl client::Part for FareInfo {}
/// A flight is a sequence of legs with the same airline carrier and flight number. (A leg is the smallest unit of travel, in the case of a flight a takeoff immediately followed by a landing at two set points on a particular carrier with a particular flight number.) The naive view is that a flight is scheduled travel of an aircraft between two points, with possibly intermediate stops, but carriers will frequently list flights that require a change of aircraft between legs.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct FlightInfo {
/// no description provided
pub carrier: Option<String>,
/// The flight number.
pub number: Option<String>,
}
impl client::Part for FlightInfo {}
/// Information about free baggage allowed on one segment of a trip.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct FreeBaggageAllowance {
/// A representation of a type of bag, such as an ATPCo subcode, Commercial Name, or other description.
#[serde(rename="bagDescriptor")]
pub bag_descriptor: Option<Vec<BagDescriptor>>,
/// The maximum number of kilos all the free baggage together may weigh.
pub kilos: Option<i32>,
/// The maximum number of kilos any one piece of baggage may weigh.
#[serde(rename="kilosPerPiece")]
pub kilos_per_piece: Option<i32>,
/// Identifies this as free baggage object, allowed on one segment of a trip. Value: the fixed string qpxexpress#freeBaggageAllowance.
pub kind: Option<String>,
/// The number of free pieces of baggage allowed.
pub pieces: Option<i32>,
/// The number of pounds of free baggage allowed.
pub pounds: Option<i32>,
}
impl client::Part for FreeBaggageAllowance {}
/// Information about a leg. (A leg is the smallest unit of travel, in the case of a flight a takeoff immediately followed by a landing at two set points on a particular carrier with a particular flight number.)
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LegInfo {
/// The aircraft (or bus, ferry, railcar, etc) travelling between the two points of this leg.
pub aircraft: Option<String>,
/// The scheduled time of arrival at the destination of the leg, local to the point of arrival.
#[serde(rename="arrivalTime")]
pub arrival_time: Option<String>,
/// Whether you have to change planes following this leg. Only applies to the next leg.
#[serde(rename="changePlane")]
pub change_plane: Option<bool>,
/// Duration of a connection following this leg, in minutes.
#[serde(rename="connectionDuration")]
pub connection_duration: Option<i32>,
/// The scheduled departure time of the leg, local to the point of departure.
#[serde(rename="departureTime")]
pub departure_time: Option<String>,
/// The leg destination as a city and airport.
pub destination: Option<String>,
/// The terminal the flight is scheduled to arrive at.
#[serde(rename="destinationTerminal")]
pub destination_terminal: Option<String>,
/// The scheduled travelling time from the origin to the destination.
pub duration: Option<i32>,
/// An identifier that uniquely identifies this leg in the solution.
pub id: Option<String>,
/// Identifies this as a leg object. A leg is the smallest unit of travel, in the case of a flight a takeoff immediately followed by a landing at two set points on a particular carrier with a particular flight number. Value: the fixed string qpxexpress#legInfo.
pub kind: Option<String>,
/// A simple, general description of the meal(s) served on the flight, for example: "Hot meal".
pub meal: Option<String>,
/// The number of miles in this leg.
pub mileage: Option<i32>,
/// In percent, the published on time performance on this leg.
#[serde(rename="onTimePerformance")]
pub on_time_performance: Option<i32>,
/// Department of Transportation disclosure information on the actual operator of a flight in a code share. (A code share refers to a marketing agreement between two carriers, where one carrier will list in its schedules (and take bookings for) flights that are actually operated by another carrier.)
#[serde(rename="operatingDisclosure")]
pub operating_disclosure: Option<String>,
/// The leg origin as a city and airport.
pub origin: Option<String>,
/// The terminal the flight is scheduled to depart from.
#[serde(rename="originTerminal")]
pub origin_terminal: Option<String>,
/// Whether passenger information must be furnished to the United States Transportation Security Administration (TSA) prior to departure.
pub secure: Option<bool>,
}
impl client::Part for LegInfo {}
/// The number and type of passengers. Unfortunately the definition of an infant, child, adult, and senior citizen varies across carriers and reservation systems.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PassengerCounts {
/// The number of passengers that are adults.
#[serde(rename="adultCount")]
pub adult_count: Option<i32>,
/// The number of passengers that are children.
#[serde(rename="childCount")]
pub child_count: Option<i32>,
/// The number of passengers that are infants travelling in the lap of an adult.
#[serde(rename="infantInLapCount")]
pub infant_in_lap_count: Option<i32>,
/// The number of passengers that are infants each assigned a seat.
#[serde(rename="infantInSeatCount")]
pub infant_in_seat_count: Option<i32>,
/// Identifies this as a passenger count object, representing the number of passengers. Value: the fixed string qpxexpress#passengerCounts.
pub kind: Option<String>,
/// The number of passengers that are senior citizens.
#[serde(rename="seniorCount")]
pub senior_count: Option<i32>,
}
impl client::Part for PassengerCounts {}
/// The price of one or more travel segments. The currency used to purchase tickets is usually determined by the sale/ticketing city or the sale/ticketing country, unless none are specified, in which case it defaults to that of the journey origin country.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PricingInfo {
/// The total fare in the base fare currency (the currency of the country of origin). This element is only present when the sales currency and the currency of the country of commencement are different.
#[serde(rename="baseFareTotal")]
pub base_fare_total: Option<String>,
/// The fare used to price one or more segments.
pub fare: Option<Vec<FareInfo>>,
/// The horizontal fare calculation. This is a field on a ticket that displays all of the relevant items that go into the calculation of the fare.
#[serde(rename="fareCalculation")]
pub fare_calculation: Option<String>,
/// Identifies this as a pricing object, representing the price of one or more travel segments. Value: the fixed string qpxexpress#pricingInfo.
pub kind: Option<String>,
/// The latest ticketing time for this pricing assuming the reservation occurs at ticketing time and there is no change in fares/rules. The time is local to the point of sale (POS).
#[serde(rename="latestTicketingTime")]
pub latest_ticketing_time: Option<String>,
/// The number of passengers to which this price applies.
pub passengers: Option<PassengerCounts>,
/// The passenger type code for this pricing. An alphanumeric code used by a carrier to restrict fares to certain categories of passenger. For instance, a fare might be valid only for senior citizens.
pub ptc: Option<String>,
/// Whether the fares on this pricing are refundable.
pub refundable: Option<bool>,
/// The total fare in the sale or equivalent currency.
#[serde(rename="saleFareTotal")]
pub sale_fare_total: Option<String>,
/// The taxes in the sale or equivalent currency.
#[serde(rename="saleTaxTotal")]
pub sale_tax_total: Option<String>,
/// Total per-passenger price (fare and tax) in the sale or equivalent currency.
#[serde(rename="saleTotal")]
pub sale_total: Option<String>,
/// The per-segment price and baggage information.
#[serde(rename="segmentPricing")]
pub segment_pricing: Option<Vec<SegmentPricing>>,
/// The taxes used to calculate the tax total per ticket.
pub tax: Option<Vec<TaxInfo>>,
}
impl client::Part for PricingInfo {}
/// Details of a segment of a flight; a segment is one or more consecutive legs on the same flight. For example a hypothetical flight ZZ001, from DFW to OGG, would have one segment with two legs: DFW to HNL (leg 1), HNL to OGG (leg 2), and DFW to OGG (legs 1 and 2).
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct SegmentInfo {
/// The booking code or class for this segment.
#[serde(rename="bookingCode")]
pub booking_code: Option<String>,
/// The number of seats available in this booking code on this segment.
#[serde(rename="bookingCodeCount")]
pub booking_code_count: Option<i32>,
/// The cabin booked for this segment.
pub cabin: Option<String>,
/// In minutes, the duration of the connection following this segment.
#[serde(rename="connectionDuration")]
pub connection_duration: Option<i32>,
/// The duration of the flight segment in minutes.
pub duration: Option<i32>,
/// The flight this is a segment of.
pub flight: Option<FlightInfo>,
/// An id uniquely identifying the segment in the solution.
pub id: Option<String>,
/// Identifies this as a segment object. A segment is one or more consecutive legs on the same flight. For example a hypothetical flight ZZ001, from DFW to OGG, could have one segment with two legs: DFW to HNL (leg 1), HNL to OGG (leg 2). Value: the fixed string qpxexpress#segmentInfo.
pub kind: Option<String>,
/// The legs composing this segment.
pub leg: Option<Vec<LegInfo>>,
/// The solution-based index of a segment in a married segment group. Married segments can only be booked together. For example, an airline might report a certain booking code as sold out from Boston to Pittsburgh, but as available as part of two married segments Boston to Chicago connecting through Pittsburgh. For example content of this field, consider the round-trip flight ZZ1 PHX-PHL ZZ2 PHL-CLT ZZ3 CLT-PHX. This has three segments, with the two outbound ones (ZZ1 ZZ2) married. In this case, the two outbound segments belong to married segment group 0, and the return segment belongs to married segment group 1.
#[serde(rename="marriedSegmentGroup")]
pub married_segment_group: Option<String>,
/// Whether the operation of this segment remains subject to government approval.
#[serde(rename="subjectToGovernmentApproval")]
pub subject_to_government_approval: Option<bool>,
}
impl client::Part for SegmentInfo {}
/// The price of this segment.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct SegmentPricing {
/// A segment identifier unique within a single solution. It is used to refer to different parts of the same solution.
#[serde(rename="fareId")]
pub fare_id: Option<String>,
/// Details of the free baggage allowance on this segment.
#[serde(rename="freeBaggageOption")]
pub free_baggage_option: Option<Vec<FreeBaggageAllowance>>,
/// Identifies this as a segment pricing object, representing the price of this segment. Value: the fixed string qpxexpress#segmentPricing.
pub kind: Option<String>,
/// Unique identifier in the response of this segment.
#[serde(rename="segmentId")]
pub segment_id: Option<String>,
}
impl client::Part for SegmentPricing {}
/// Information about a slice. A slice represents a traveller's intent, the portion of a low-fare search corresponding to a traveler's request to get between two points. One-way journeys are generally expressed using 1 slice, round-trips using 2. For example, if a traveler specifies the following trip in a user interface:
/// | Origin | Destination | Departure Date | | BOS | LAX | March 10, 2007 | | LAX | SYD | March 17, 2007 | | SYD | BOS | March 22, 2007 |
/// then this is a three slice trip.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct SliceInfo {
/// The duration of the slice in minutes.
pub duration: Option<i32>,
/// Identifies this as a slice object. A slice represents a traveller's intent, the portion of a low-fare search corresponding to a traveler's request to get between two points. One-way journeys are generally expressed using 1 slice, round-trips using 2. Value: the fixed string qpxexpress#sliceInfo.
pub kind: Option<String>,
/// The segment(s) constituting the slice.
pub segment: Option<Vec<SegmentInfo>>,
}
impl client::Part for SliceInfo {}
/// Criteria a desired slice must satisfy.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct SliceInput {
/// Slices with only the carriers in this alliance should be returned; do not use this field with permittedCarrier. Allowed values are ONEWORLD, SKYTEAM, and STAR.
pub alliance: Option<String>,
/// Departure date in YYYY-MM-DD format.
pub date: Option<String>,
/// Airport or city IATA designator of the destination.
pub destination: Option<String>,
/// Identifies this as a slice input object, representing the criteria a desired slice must satisfy. Value: the fixed string qpxexpress#sliceInput.
pub kind: Option<String>,
/// The longest connection between two legs, in minutes, you are willing to accept.
#[serde(rename="maxConnectionDuration")]
pub max_connection_duration: Option<i32>,
/// The maximum number of stops you are willing to accept in this slice.
#[serde(rename="maxStops")]
pub max_stops: Option<i32>,
/// Airport or city IATA designator of the origin.
pub origin: Option<String>,
/// A list of 2-letter IATA airline designators. Slices with only these carriers should be returned.
#[serde(rename="permittedCarrier")]
pub permitted_carrier: Option<Vec<String>>,
/// Slices must depart in this time of day range, local to the point of departure.
#[serde(rename="permittedDepartureTime")]
pub permitted_departure_time: Option<TimeOfDayRange>,
/// Prefer solutions that book in this cabin for this slice. Allowed values are COACH, PREMIUM_COACH, BUSINESS, and FIRST.
#[serde(rename="preferredCabin")]
pub preferred_cabin: Option<String>,
/// A list of 2-letter IATA airline designators. Exclude slices that use these carriers.
#[serde(rename="prohibitedCarrier")]
pub prohibited_carrier: Option<Vec<String>>,
}
impl client::Part for SliceInput {}
/// Tax data.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct TaxData {
/// An identifier uniquely identifying a tax in a response.
pub id: Option<String>,
/// Identifies this as a tax data object, representing some tax. Value: the fixed string qpxexpress#taxData.
pub kind: Option<String>,
/// The name of a tax.
pub name: Option<String>,
}
impl client::Part for TaxData {}
/// Tax information.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct TaxInfo {
/// Whether this is a government charge or a carrier surcharge.
#[serde(rename="chargeType")]
pub charge_type: Option<String>,
/// The code to enter in the ticket's tax box.
pub code: Option<String>,
/// For government charges, the country levying the charge.
pub country: Option<String>,
/// Identifier uniquely identifying this tax in a response. Not present for unnamed carrier surcharges.
pub id: Option<String>,
/// Identifies this as a tax information object. Value: the fixed string qpxexpress#taxInfo.
pub kind: Option<String>,
/// The price of the tax in the sales or equivalent currency.
#[serde(rename="salePrice")]
pub sale_price: Option<String>,
}
impl client::Part for TaxInfo {}
/// Two times in a single day defining a time range.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct TimeOfDayRange {
/// The earliest time of day in HH:MM format.
#[serde(rename="earliestTime")]
pub earliest_time: Option<String>,
/// Identifies this as a time of day range object, representing two times in a single day defining a time range. Value: the fixed string qpxexpress#timeOfDayRange.
pub kind: Option<String>,
/// The latest time of day in HH:MM format.
#[serde(rename="latestTime")]
pub latest_time: Option<String>,
}
impl client::Part for TimeOfDayRange {}
/// Trip information.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct TripOption {
/// Identifier uniquely identifying this trip in a response.
pub id: Option<String>,
/// Identifies this as a trip information object. Value: the fixed string qpxexpress#tripOption.
pub kind: Option<String>,
/// Per passenger pricing information.
pub pricing: Option<Vec<PricingInfo>>,
/// The total price for all passengers on the trip, in the form of a currency followed by an amount, e.g. USD253.35.
#[serde(rename="saleTotal")]
pub sale_total: Option<String>,
/// The slices that make up this trip's itinerary.
pub slice: Option<Vec<SliceInfo>>,
}
impl client::Part for TripOption {}
/// A QPX Express search request, which will yield one or more solutions.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct TripOptionsRequest {
/// Do not return solutions that cost more than this price. The alphabetical part of the price is in ISO 4217. The format, in regex, is [A-Z]{3}\d+(\.\d+)? Example: $102.07
#[serde(rename="maxPrice")]
pub max_price: Option<String>,
/// Counts for each passenger type in the request.
pub passengers: Option<PassengerCounts>,
/// Return only solutions with refundable fares.
pub refundable: Option<bool>,
/// IATA country code representing the point of sale. This determines the "equivalent amount paid" currency for the ticket.
#[serde(rename="saleCountry")]
pub sale_country: Option<String>,
/// The slices that make up the itinerary of this trip. A slice represents a traveler's intent, the portion of a low-fare search corresponding to a traveler's request to get between two points. One-way journeys are generally expressed using one slice, round-trips using two. An example of a one slice trip with three segments might be BOS-SYD, SYD-LAX, LAX-BOS if the traveler only stopped in SYD and LAX just long enough to change planes.
pub slice: Option<Vec<SliceInput>>,
/// The number of solutions to return, maximum 500.
pub solutions: Option<i32>,
/// IATA country code representing the point of ticketing.
#[serde(rename="ticketingCountry")]
pub ticketing_country: Option<String>,
}
impl client::Part for TripOptionsRequest {}
/// A QPX Express search response.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct TripOptionsResponse {
/// Informational data global to list of solutions.
pub data: Option<Data>,
/// Identifies this as a QPX Express trip response object, which consists of zero or more solutions. Value: the fixed string qpxexpress#tripOptions.
pub kind: Option<String>,
/// An identifier uniquely identifying this response.
#[serde(rename="requestId")]
pub request_id: Option<String>,
/// A list of priced itinerary solutions to the QPX Express query.
#[serde(rename="tripOption")]
pub trip_option: Option<Vec<TripOption>>,
}
impl client::Part for TripOptionsResponse {}
/// A QPX Express search request.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [search trips](TripSearchCall) (request)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct TripsSearchRequest {
/// A QPX Express search request. Required values are at least one adult or senior passenger, an origin, a destination, and a date.
pub request: Option<TripOptionsRequest>,
}
impl client::RequestValue for TripsSearchRequest {}
/// A QPX Express search response.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [search trips](TripSearchCall) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct TripsSearchResponse {
/// Identifies this as a QPX Express API search response resource. Value: the fixed string qpxExpress#tripsSearch.
pub kind: Option<String>,
/// All possible solutions to the QPX Express search request.
pub trips: Option<TripOptionsResponse>,
}
impl client::ResponseResult for TripsSearchResponse {}
// ###################
// MethodBuilders ###
// #################
/// A builder providing access to all methods supported on *trip* resources.
/// It is not used directly, but through the `QPXExpress` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate yup_oauth2 as oauth2;
/// extern crate google_qpxexpress1 as qpxexpress1;
///
/// # async fn dox() {
/// use std::default::Default;
/// use oauth2;
/// use qpxexpress1::QPXExpress;
///
/// let secret: oauth2::ApplicationSecret = Default::default();
/// let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// secret,
/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// ).build().await.unwrap();
/// let mut hub = QPXExpress::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `search(...)`
/// // to build up your call.
/// let rb = hub.trips();
/// # }
/// ```
pub struct TripMethods<'a>
where {
hub: &'a QPXExpress<>,
}
impl<'a> client::MethodsBuilder for TripMethods<'a> {}
impl<'a> TripMethods<'a> {
/// Create a builder to help you perform the following task:
///
/// Returns a list of flights.
///
/// # Arguments
///
/// * `request` - No description provided.
pub fn search(&self, request: TripsSearchRequest) -> TripSearchCall<'a> {
TripSearchCall {
hub: self.hub,
_request: request,
_delegate: Default::default(),
_additional_params: Default::default(),
}
}
}
// ###################
// CallBuilders ###
// #################
/// Returns a list of flights.
///
/// A builder for the *search* method supported by a *trip* resource.
/// It is not used directly, but through a `TripMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_qpxexpress1 as qpxexpress1;
/// use qpxexpress1::api::TripsSearchRequest;
/// # async fn dox() {
/// # use std::default::Default;
/// # use oauth2;
/// # use qpxexpress1::QPXExpress;
///
/// # let secret: oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
/// # let mut hub = QPXExpress::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = TripsSearchRequest::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.trips().search(req)
/// .doit().await;
/// # }
/// ```
pub struct TripSearchCall<'a>
where {
hub: &'a QPXExpress<>,
_request: TripsSearchRequest,
_delegate: Option<&'a mut dyn client::Delegate>,
_additional_params: HashMap<String, String>,
}
impl<'a> client::CallBuilder for TripSearchCall<'a> {}
impl<'a> TripSearchCall<'a> {
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, TripsSearchResponse)> {
use std::io::{Read, Seek};
use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION};
use client::ToParts;
let mut dd = client::DefaultDelegate;
let mut dlg: &mut dyn client::Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(client::MethodInfo { id: "qpxExpress.trips.search",
http_method: hyper::Method::POST });
let mut params: Vec<(&str, String)> = Vec::with_capacity(3 + self._additional_params.len());
for &field in ["alt"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(client::Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "search";
let key = dlg.api_key();
match key {
Some(value) => params.push(("key", value)),
None => {
dlg.finished(false);
return Err(client::Error::MissingAPIKey)
}
}
let url = url::Url::parse_with_params(&url, params).unwrap();
let mut json_mime_type: mime::Mime = "application/json".parse().unwrap();
let mut request_value_reader =
{
let mut value = json::value::to_value(&self._request).expect("serde to work");
client::remove_json_null_values(&mut value);
let mut dst = io::Cursor::new(Vec::with_capacity(128));
json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap();
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
loop {
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder().method(hyper::Method::POST).uri(url.clone().into_string())
.header(USER_AGENT, self.hub._user_agent.clone());
let request = req_builder
.header(CONTENT_TYPE, format!("{}", json_mime_type.to_string()))
.header(CONTENT_LENGTH, request_size as u64)
.body(hyper::body::Body::from(request_value_reader.get_ref().clone()));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let client::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(client::Error::HttpError(err))
}
Ok(mut res) => {
if !res.status().is_success() {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
let json_server_error = json::from_str::<client::JsonServerError>(&res_body_string).ok();
let server_error = json::from_str::<client::ServerError>(&res_body_string)
.or_else(|_| json::from_str::<client::ErrorResponse>(&res_body_string).map(|r| r.error))
.ok();
if let client::Retry::After(d) = dlg.http_failure(&res,
json_server_error,
server_error) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<client::ErrorResponse>(&res_body_string){
Err(_) => Err(client::Error::Failure(res)),
Ok(serr) => Err(client::Error::BadRequest(serr))
}
}
let result_value = {
let res_body_string = client::get_body_as_string(res.body_mut()).await;
match json::from_str(&res_body_string) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&res_body_string, &err);
return Err(client::Error::JsonDecodeError(res_body_string, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: TripsSearchRequest) -> TripSearchCall<'a> {
self._request = new_value;
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn client::Delegate) -> TripSearchCall<'a> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *alt* (query-string) - Data format for the response.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.
/// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
pub fn param<T>(mut self, name: T, value: T) -> TripSearchCall<'a>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
}
| 43.956989 | 624 | 0.670343 |
89759cf1dd641864bf2d89ab2235a0ccc1839eb6 | 3,840 | use super::{Aabb, DynamicTree, TreeCallback};
use ::dynamics::FixtureHandle;
use cgmath::*;
use std::cmp;
pub trait BroadPhaseCallback<'a> {
fn add_pair(&mut self, fixture_a: FixtureHandle<'a>, fixture_b: FixtureHandle<'a>);
}
struct PairManager {
pairs: Vec<(u32, u32)>,
cur_proxy_id: u32,
}
impl PairManager {
fn new() -> Self {
PairManager {
pairs: Vec::new(),
cur_proxy_id: 0,
}
}
}
impl TreeCallback for PairManager {
fn query_callback(&mut self, proxy_id: u32) -> bool {
/*let cur_proxy_id = match self.cur_proxy_id {
Some(cur_proxy_id) => cur_proxy_id,
None => return false,
}*/
if proxy_id == self.cur_proxy_id {
return true;
}
let proxy_id_a = cmp::min(proxy_id, self.cur_proxy_id);
let proxy_id_b = cmp::max(proxy_id, self.cur_proxy_id);
self.pairs.push((proxy_id_a, proxy_id_b));
true
}
}
pub struct BroadPhase<'a> {
tree: DynamicTree<FixtureHandle<'a>>,
pair_manager: PairManager,
move_buffer: Vec<u32>,
}
impl<'a> BroadPhase<'a> {
pub fn new() -> Self {
BroadPhase {
tree: DynamicTree::new(),
pair_manager: PairManager::new(),
move_buffer: Vec::new(),
}
}
pub fn create_proxy(&mut self, aabb: &Aabb, fixture: FixtureHandle<'a>) -> u32 {
let result = self.tree.create_proxy(aabb, Some(fixture));
self.move_buffer.push(result);
result
}
pub fn destroy_proxy(&mut self, proxy_id: u32) {
self.remove_from_move_buffer(proxy_id);
self.tree.destroy_proxy(proxy_id);
}
pub fn move_proxy(&mut self, proxy_id: u32, aabb: &Aabb, displacement: Vector2<f32>) {
if self.tree.move_proxy(proxy_id, aabb, displacement) {
self.move_buffer.push(proxy_id);
}
}
pub fn touch_proxy(&mut self, proxy_id: u32) {
self.move_buffer.push(proxy_id);
}
fn remove_from_move_buffer(&mut self, proxy_id: u32) {
//let to_remove = self.move_buffer.iter().enumerate().filter(|&(i, id)| *id == proxy_id).map(|(i, _)| i).collect::<Vec<usize>>();
let mut to_remove = Vec::new();
for (i, id) in self.move_buffer.iter().enumerate() {
if proxy_id == *id {
to_remove.push(i);
}
}
for i in &to_remove {
self.move_buffer.swap_remove(*i);
}
}
pub fn test_overlap(&self, proxy_id_a: u32, proxy_id_b: u32) -> bool {
let aabb_a = self.tree.get_fat_aabb(proxy_id_a);
let aabb_b = self.tree.get_fat_aabb(proxy_id_b);
aabb_a.overlaps(&aabb_b)
}
pub fn get_fat_aabb(&self, proxy_id: u32) -> Aabb {
self.tree.get_fat_aabb(proxy_id)
}
/*pub fn get_user_data(&self, proxy_id: u32) -> Option<&FixtureHandle> {
self.tree.get_user_data(proxy_id)
}*/
pub fn update_pairs(&mut self, callback: &mut BroadPhaseCallback<'a>) {
self.pair_manager.pairs.clear();
for i in &self.move_buffer {
self.pair_manager.cur_proxy_id = *i;
let fat_aabb = self.tree.get_fat_aabb(*i);
self.tree.query(&mut self.pair_manager, &fat_aabb);
}
self.move_buffer.clear();
self.pair_manager.pairs.sort();
self.pair_manager.pairs.dedup();
for &(proxy_id_a, proxy_id_b) in &self.pair_manager.pairs {
let fixture_a = self.tree.get_user_data(proxy_id_a).unwrap().clone();
let fixture_b = self.tree.get_user_data(proxy_id_b).unwrap().clone();
callback.add_pair(fixture_a, fixture_b);
}
}
pub fn print(&self) {
self.tree.print();
}
}
/*impl TreeCallback for BroadPhase {
fn query_callback(&mut self) {
}
}*/
| 28.029197 | 137 | 0.592188 |
751394bacb22d4f9228c7c7c48e389e2b865d112 | 17,424 | use byteorder::{ByteOrder, LittleEndian, WriteBytesExt};
use solana_sdk::{
account::KeyedAccount, bpf_loader_deprecated, entrypoint::MAX_PERMITTED_DATA_INCREASE,
instruction::InstructionError, pubkey::Pubkey,
};
use std::{
io::prelude::*,
mem::{align_of, size_of},
};
/// Look for a duplicate account and return its position if found
pub fn is_dup(accounts: &[KeyedAccount], keyed_account: &KeyedAccount) -> (bool, usize) {
for (i, account) in accounts.iter().enumerate() {
if account == keyed_account {
return (true, i);
}
}
(false, 0)
}
pub fn serialize_parameters(
loader_id: &Pubkey,
program_id: &Pubkey,
keyed_accounts: &[KeyedAccount],
data: &[u8],
) -> Result<Vec<u8>, InstructionError> {
if *loader_id == bpf_loader_deprecated::id() {
serialize_parameters_unaligned(program_id, keyed_accounts, data)
} else {
serialize_parameters_aligned(program_id, keyed_accounts, data)
}
}
pub fn deserialize_parameters(
loader_id: &Pubkey,
keyed_accounts: &[KeyedAccount],
buffer: &[u8],
) -> Result<(), InstructionError> {
if *loader_id == bpf_loader_deprecated::id() {
deserialize_parameters_unaligned(keyed_accounts, buffer)
} else {
deserialize_parameters_aligned(keyed_accounts, buffer)
}
}
pub fn serialize_parameters_unaligned(
program_id: &Pubkey,
keyed_accounts: &[KeyedAccount],
instruction_data: &[u8],
) -> Result<Vec<u8>, InstructionError> {
assert_eq!(32, size_of::<Pubkey>());
// Calculate size in order to alloc once
let mut size = size_of::<u64>();
for (i, keyed_account) in keyed_accounts.iter().enumerate() {
let (is_dup, _) = is_dup(&keyed_accounts[..i], keyed_account);
size += 1; // dup, signer, writable, executable
if !is_dup {
let data_len = keyed_account.data_len()?;
size += size_of::<Pubkey>() // key
+ size_of::<Pubkey>() // owner
+ size_of::<u64>() // lamports
+ size_of::<u64>() // data len
+ data_len
+ MAX_PERMITTED_DATA_INCREASE
+ (data_len as *const u8).align_offset(align_of::<u128>())
+ size_of::<u64>(); // rent epoch;
}
}
size += size_of::<u64>() // data len
+ instruction_data.len()
+ size_of::<Pubkey>(); // program id;
let mut v: Vec<u8> = Vec::with_capacity(size);
v.write_u64::<LittleEndian>(keyed_accounts.len() as u64)
.unwrap();
for (i, keyed_account) in keyed_accounts.iter().enumerate() {
let (is_dup, position) = is_dup(&keyed_accounts[..i], keyed_account);
if is_dup {
v.write_u8(position as u8).unwrap();
} else {
v.write_u8(std::u8::MAX).unwrap();
v.write_u8(keyed_account.signer_key().is_some() as u8)
.unwrap();
v.write_u8(keyed_account.is_writable() as u8).unwrap();
v.write_all(keyed_account.unsigned_key().as_ref()).unwrap();
v.write_u64::<LittleEndian>(keyed_account.lamports()?)
.unwrap();
v.write_u64::<LittleEndian>(keyed_account.data_len()? as u64)
.unwrap();
v.write_all(&keyed_account.try_account_ref()?.data).unwrap();
v.write_all(keyed_account.owner()?.as_ref()).unwrap();
v.write_u8(keyed_account.executable()? as u8).unwrap();
v.write_u64::<LittleEndian>(keyed_account.rent_epoch()? as u64)
.unwrap();
}
}
v.write_u64::<LittleEndian>(instruction_data.len() as u64)
.unwrap();
v.write_all(instruction_data).unwrap();
v.write_all(program_id.as_ref()).unwrap();
Ok(v)
}
pub fn deserialize_parameters_unaligned(
keyed_accounts: &[KeyedAccount],
buffer: &[u8],
) -> Result<(), InstructionError> {
assert_eq!(32, size_of::<Pubkey>());
let mut start = size_of::<u64>(); // number of accounts
for (i, keyed_account) in keyed_accounts.iter().enumerate() {
let (is_dup, _) = is_dup(&keyed_accounts[..i], keyed_account);
start += 1; // is_dup
if !is_dup {
start += size_of::<u8>(); // is_signer
start += size_of::<u8>(); // is_writable
start += size_of::<Pubkey>(); // pubkey
keyed_account.try_account_ref_mut()?.lamports =
LittleEndian::read_u64(&buffer[start..]);
start += size_of::<u64>() // lamports
+ size_of::<u64>(); // data length
let end = start + keyed_account.data_len()?;
keyed_account
.try_account_ref_mut()?
.data
.clone_from_slice(&buffer[start..end]);
start += keyed_account.data_len()? // data
+ size_of::<Pubkey>() // owner
+ size_of::<u8>() // executable
+ size_of::<u64>(); // rent_epoch
}
}
Ok(())
}
pub fn serialize_parameters_aligned(
program_id: &Pubkey,
keyed_accounts: &[KeyedAccount],
instruction_data: &[u8],
) -> Result<Vec<u8>, InstructionError> {
assert_eq!(32, size_of::<Pubkey>());
// Calculate size in order to alloc once
let mut size = size_of::<u64>();
for (i, keyed_account) in keyed_accounts.iter().enumerate() {
let (is_dup, _) = is_dup(&keyed_accounts[..i], keyed_account);
size += 8; // dup, signer, writable, executable
if !is_dup {
let data_len = keyed_account.data_len()?;
size += size_of::<Pubkey>() // key
+ size_of::<Pubkey>() // owner
+ size_of::<u64>() // lamports
+ size_of::<u64>() // data len
+ data_len
+ MAX_PERMITTED_DATA_INCREASE
+ (data_len as *const u8).align_offset(align_of::<u128>())
+ size_of::<u64>(); // rent epoch;
}
}
size += size_of::<u64>() // data len
+ instruction_data.len()
+ size_of::<Pubkey>(); // program id;
let mut v: Vec<u8> = Vec::with_capacity(size);
// Serialize into the buffer
v.write_u64::<LittleEndian>(keyed_accounts.len() as u64)
.unwrap();
if v.as_ptr().align_offset(align_of::<u128>()) != 0 {
panic!();
}
for (i, keyed_account) in keyed_accounts.iter().enumerate() {
let (is_dup, position) = is_dup(&keyed_accounts[..i], keyed_account);
if is_dup {
v.write_u8(position as u8).unwrap();
v.write_all(&[0u8, 0, 0, 0, 0, 0, 0]).unwrap(); // 7 bytes of padding to make 64-bit aligned
} else {
v.write_u8(std::u8::MAX).unwrap();
v.write_u8(keyed_account.signer_key().is_some() as u8)
.unwrap();
v.write_u8(keyed_account.is_writable() as u8).unwrap();
v.write_u8(keyed_account.executable()? as u8).unwrap();
v.write_all(&[0u8, 0, 0, 0]).unwrap(); // 4 bytes of padding to make 128-bit aligned
v.write_all(keyed_account.unsigned_key().as_ref()).unwrap();
v.write_all(keyed_account.owner()?.as_ref()).unwrap();
v.write_u64::<LittleEndian>(keyed_account.lamports()?)
.unwrap();
v.write_u64::<LittleEndian>(keyed_account.data_len()? as u64)
.unwrap();
v.write_all(&keyed_account.try_account_ref()?.data).unwrap();
v.resize(
v.len()
+ MAX_PERMITTED_DATA_INCREASE
+ (v.len() as *const u8).align_offset(align_of::<u128>()),
0,
);
v.write_u64::<LittleEndian>(keyed_account.rent_epoch()? as u64)
.unwrap();
}
}
v.write_u64::<LittleEndian>(instruction_data.len() as u64)
.unwrap();
v.write_all(instruction_data).unwrap();
v.write_all(program_id.as_ref()).unwrap();
Ok(v)
}
pub fn deserialize_parameters_aligned(
keyed_accounts: &[KeyedAccount],
buffer: &[u8],
) -> Result<(), InstructionError> {
assert_eq!(32, size_of::<Pubkey>());
let mut start = size_of::<u64>(); // number of accounts
for (i, keyed_account) in keyed_accounts.iter().enumerate() {
let (is_dup, _) = is_dup(&keyed_accounts[..i], keyed_account);
start += size_of::<u8>(); // position
if is_dup {
start += 7; // padding to 64-bit aligned
} else {
let mut account = keyed_account.try_account_ref_mut()?;
start += size_of::<u8>() // is_signer
+ size_of::<u8>() // is_writable
+ size_of::<u8>() // executable
+ 4 // padding to 128-bit aligned
+ size_of::<Pubkey>(); // key
account.owner = Pubkey::new(&buffer[start..start + size_of::<Pubkey>()]);
start += size_of::<Pubkey>(); // owner
account.lamports = LittleEndian::read_u64(&buffer[start..]);
start += size_of::<u64>(); // lamports
let pre_len = account.data.len();
let post_len = LittleEndian::read_u64(&buffer[start..]) as usize;
start += size_of::<u64>(); // data length
let mut data_end = start + pre_len;
if post_len != pre_len
&& (post_len.saturating_sub(pre_len)) <= MAX_PERMITTED_DATA_INCREASE
{
account.data.resize(post_len, 0);
data_end = start + post_len;
}
account.data.clone_from_slice(&buffer[start..data_end]);
start += pre_len + MAX_PERMITTED_DATA_INCREASE; // data
start += (start as *const u8).align_offset(align_of::<u128>());
start += size_of::<u64>(); // rent_epoch
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use solana_sdk::{
account::Account, account_info::AccountInfo, bpf_loader, entrypoint::deserialize,
};
use std::{
cell::RefCell,
rc::Rc,
// Hide Result from bindgen gets confused about generics in non-generic type declarations
slice::{from_raw_parts, from_raw_parts_mut},
};
#[test]
fn test_serialize_parameters() {
let program_id = Pubkey::new_rand();
let dup_key = Pubkey::new_rand();
let keys = vec![dup_key, dup_key, Pubkey::new_rand(), Pubkey::new_rand()];
let accounts = [
RefCell::new(Account {
lamports: 1,
data: vec![1u8, 2, 3, 4, 5],
owner: bpf_loader::id(),
executable: false,
rent_epoch: 100,
}),
// dup of first
RefCell::new(Account {
lamports: 1,
data: vec![1u8, 2, 3, 4, 5],
owner: bpf_loader::id(),
executable: false,
rent_epoch: 100,
}),
RefCell::new(Account {
lamports: 2,
data: vec![11u8, 12, 13, 14, 15, 16, 17, 18, 19],
owner: bpf_loader::id(),
executable: true,
rent_epoch: 200,
}),
RefCell::new(Account {
lamports: 3,
data: vec![],
owner: bpf_loader::id(),
executable: false,
rent_epoch: 3100,
}),
];
let keyed_accounts: Vec<_> = keys
.iter()
.zip(&accounts)
.map(|(key, account)| KeyedAccount::new(&key, false, &account))
.collect();
let instruction_data = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
// check serialize_parameters_aligned
let mut serialized = serialize_parameters(
&bpf_loader::id(),
&program_id,
&keyed_accounts,
&instruction_data,
)
.unwrap();
let (de_program_id, de_accounts, de_instruction_data) =
unsafe { deserialize(&mut serialized[0] as *mut u8) };
assert_eq!(&program_id, de_program_id);
assert_eq!(instruction_data, de_instruction_data);
assert_eq!(
(&de_instruction_data[0] as *const u8).align_offset(align_of::<u128>()),
0
);
for ((account, account_info), key) in accounts.iter().zip(de_accounts).zip(keys.clone()) {
assert_eq!(key, *account_info.key);
let account = account.borrow();
assert_eq!(account.lamports, account_info.lamports());
assert_eq!(&account.data[..], &account_info.data.borrow()[..]);
assert_eq!(&account.owner, account_info.owner);
assert_eq!(account.executable, account_info.executable);
assert_eq!(account.rent_epoch, account_info.rent_epoch);
assert_eq!(
(*account_info.lamports.borrow() as *const u64).align_offset(align_of::<u64>()),
0
);
assert_eq!(
account_info
.data
.borrow()
.as_ptr()
.align_offset(align_of::<u128>()),
0
);
}
// check serialize_parameters_unaligned
let mut serialized = serialize_parameters(
&bpf_loader_deprecated::id(),
&program_id,
&keyed_accounts,
&instruction_data,
)
.unwrap();
let (de_program_id, de_accounts, de_instruction_data) =
unsafe { deserialize_unaligned(&mut serialized[0] as *mut u8) };
assert_eq!(&program_id, de_program_id);
assert_eq!(instruction_data, de_instruction_data);
for ((account, account_info), key) in accounts.iter().zip(de_accounts).zip(keys) {
assert_eq!(key, *account_info.key);
let account = account.borrow();
assert_eq!(account.lamports, account_info.lamports());
assert_eq!(&account.data[..], &account_info.data.borrow()[..]);
assert_eq!(&account.owner, account_info.owner);
assert_eq!(account.executable, account_info.executable);
assert_eq!(account.rent_epoch, account_info.rent_epoch);
}
}
// the old bpf_loader in-program deserializer bpf_loader::id()
#[allow(clippy::type_complexity)]
pub unsafe fn deserialize_unaligned<'a>(
input: *mut u8,
) -> (&'a Pubkey, Vec<AccountInfo<'a>>, &'a [u8]) {
let mut offset: usize = 0;
// number of accounts present
#[allow(clippy::cast_ptr_alignment)]
let num_accounts = *(input.add(offset) as *const u64) as usize;
offset += size_of::<u64>();
// account Infos
let mut accounts = Vec::with_capacity(num_accounts);
for _ in 0..num_accounts {
let dup_info = *(input.add(offset) as *const u8);
offset += size_of::<u8>();
if dup_info == std::u8::MAX {
#[allow(clippy::cast_ptr_alignment)]
let is_signer = *(input.add(offset) as *const u8) != 0;
offset += size_of::<u8>();
#[allow(clippy::cast_ptr_alignment)]
let is_writable = *(input.add(offset) as *const u8) != 0;
offset += size_of::<u8>();
let key: &Pubkey = &*(input.add(offset) as *const Pubkey);
offset += size_of::<Pubkey>();
#[allow(clippy::cast_ptr_alignment)]
let lamports = Rc::new(RefCell::new(&mut *(input.add(offset) as *mut u64)));
offset += size_of::<u64>();
#[allow(clippy::cast_ptr_alignment)]
let data_len = *(input.add(offset) as *const u64) as usize;
offset += size_of::<u64>();
let data = Rc::new(RefCell::new({
from_raw_parts_mut(input.add(offset), data_len)
}));
offset += data_len;
let owner: &Pubkey = &*(input.add(offset) as *const Pubkey);
offset += size_of::<Pubkey>();
#[allow(clippy::cast_ptr_alignment)]
let executable = *(input.add(offset) as *const u8) != 0;
offset += size_of::<u8>();
#[allow(clippy::cast_ptr_alignment)]
let rent_epoch = *(input.add(offset) as *const u64);
offset += size_of::<u64>();
accounts.push(AccountInfo {
is_signer,
is_writable,
key,
lamports,
data,
owner,
executable,
rent_epoch,
});
} else {
// duplicate account, clone the original
accounts.push(accounts[dup_info as usize].clone());
}
}
// instruction data
#[allow(clippy::cast_ptr_alignment)]
let instruction_data_len = *(input.add(offset) as *const u64) as usize;
offset += size_of::<u64>();
let instruction_data = { from_raw_parts(input.add(offset), instruction_data_len) };
offset += instruction_data_len;
// program Id
let program_id: &Pubkey = &*(input.add(offset) as *const Pubkey);
(program_id, accounts, instruction_data)
}
}
| 37.878261 | 104 | 0.541093 |
f46ef982d4d24a3f8f5d5b6669214f750e874bf0 | 16,802 | use crate::data::Value;
use crate::errors::ErrorBuilder;
use crate::funcs;
use crate::lang;
use crate::operator;
use failure::Fail;
#[derive(Debug, Fail)]
pub enum TypeError {
#[fail(display = "Expected boolean expression, found {}", found)]
ExpectedBool { found: String },
#[fail(display = "Expected an expression")]
ExpectedExpr,
#[fail(
display = "Wrong number of patterns for parse. Pattern has {} but {} were extracted",
pattern, extracted
)]
ParseNumPatterns { pattern: usize, extracted: usize },
#[fail(display = "Two `from` clauses were provided")]
DoubleFromClause,
#[fail(display = "Limit must be a non-zero integer, found {}", limit)]
InvalidLimit { limit: f64 },
#[fail(display = "Unknown function {}", name)]
UnknownFunction { name: String },
#[fail(display = "Expected a duration for the timeslice (e.g. 1h)")]
ExpectedDuration,
}
pub trait TypeCheck<O> {
fn type_check<E: ErrorBuilder>(self, error_builder: &E) -> Result<O, TypeError>;
}
impl TypeCheck<operator::BoolExpr> for lang::ComparisonOp {
fn type_check<E: ErrorBuilder>(
self,
_error_builder: &E,
) -> Result<operator::BoolExpr, TypeError> {
match self {
lang::ComparisonOp::Eq => Ok(operator::BoolExpr::Eq),
lang::ComparisonOp::Neq => Ok(operator::BoolExpr::Neq),
lang::ComparisonOp::Gt => Ok(operator::BoolExpr::Gt),
lang::ComparisonOp::Lt => Ok(operator::BoolExpr::Lt),
lang::ComparisonOp::Gte => Ok(operator::BoolExpr::Gte),
lang::ComparisonOp::Lte => Ok(operator::BoolExpr::Lte),
}
}
}
impl TypeCheck<operator::ArithmeticExpr> for lang::ArithmeticOp {
fn type_check<E: ErrorBuilder>(
self,
_error_builder: &E,
) -> Result<operator::ArithmeticExpr, TypeError> {
match self {
lang::ArithmeticOp::Add => Ok(operator::ArithmeticExpr::Add),
lang::ArithmeticOp::Subtract => Ok(operator::ArithmeticExpr::Subtract),
lang::ArithmeticOp::Multiply => Ok(operator::ArithmeticExpr::Multiply),
lang::ArithmeticOp::Divide => Ok(operator::ArithmeticExpr::Divide),
}
}
}
impl TypeCheck<operator::LogicalExpr> for lang::LogicalOp {
fn type_check<E: ErrorBuilder>(
self,
_error_builder: &E,
) -> Result<operator::LogicalExpr, TypeError> {
match self {
lang::LogicalOp::And => Ok(operator::LogicalExpr::And),
lang::LogicalOp::Or => Ok(operator::LogicalExpr::Or),
}
}
}
impl TypeCheck<operator::Expr> for lang::Expr {
fn type_check<E: ErrorBuilder>(self, error_builder: &E) -> Result<operator::Expr, TypeError> {
match self {
lang::Expr::Column { head, rest } => {
let head = match head {
lang::DataAccessAtom::Key(s) => s,
lang::DataAccessAtom::Index(_) => return Err(TypeError::ExpectedExpr),
};
let rest = rest
.iter()
.map(|s| match s {
lang::DataAccessAtom::Key(s) => operator::ValueRef::Field(s.to_string()),
lang::DataAccessAtom::Index(i) => operator::ValueRef::IndexAt(*i),
})
.collect();
Ok(operator::Expr::NestedColumn { head, rest })
}
lang::Expr::Unary { op, operand } => match op {
lang::UnaryOp::Not => Ok(operator::Expr::BoolUnary(operator::UnaryExpr {
operator: operator::BoolUnaryExpr::Not,
operand: Box::new((*operand).type_check(error_builder)?),
})),
},
lang::Expr::Binary { op, left, right } => match op {
lang::BinaryOp::Comparison(com_op) => {
Ok(operator::Expr::Comparison(operator::BinaryExpr::<
operator::BoolExpr,
> {
left: Box::new((*left).type_check(error_builder)?),
right: Box::new((*right).type_check(error_builder)?),
operator: com_op.type_check(error_builder)?,
}))
}
lang::BinaryOp::Arithmetic(arith_op) => {
Ok(operator::Expr::Arithmetic(operator::BinaryExpr::<
operator::ArithmeticExpr,
> {
left: Box::new((*left).type_check(error_builder)?),
right: Box::new((*right).type_check(error_builder)?),
operator: arith_op.type_check(error_builder)?,
}))
}
lang::BinaryOp::Logical(logical_op) => {
Ok(operator::Expr::Logical(operator::BinaryExpr::<
operator::LogicalExpr,
> {
left: Box::new((*left).type_check(error_builder)?),
right: Box::new((*right).type_check(error_builder)?),
operator: logical_op.type_check(error_builder)?,
}))
}
},
lang::Expr::FunctionCall { name, args } => {
let converted_args: Result<Vec<operator::Expr>, TypeError> = args
.into_iter()
.map(|arg| arg.type_check(error_builder))
.collect();
if let Some(func) = funcs::FUNC_MAP.get(name.as_str()) {
Ok(operator::Expr::FunctionCall {
func,
args: converted_args?,
})
} else {
Err(TypeError::UnknownFunction { name })
}
}
lang::Expr::IfOp {
cond,
value_if_true,
value_if_false,
} => Ok(operator::Expr::IfOp {
cond: Box::new(cond.type_check(error_builder)?),
value_if_true: Box::new(value_if_true.type_check(error_builder)?),
value_if_false: Box::new(value_if_false.type_check(error_builder)?),
}),
lang::Expr::Value(value) => {
let boxed = Box::new(value);
let static_value: &'static mut Value = Box::leak(boxed);
Ok(operator::Expr::Value(static_value))
}
lang::Expr::Error => Err(TypeError::ExpectedExpr),
}
}
}
const DEFAULT_LIMIT: i64 = 10;
impl TypeCheck<Box<dyn operator::OperatorBuilder + Send + Sync>>
for lang::Positioned<lang::InlineOperator>
{
/// Convert the operator syntax to a builder that can instantiate an operator for the
/// pipeline. Any semantic errors in the operator syntax should be detected here.
fn type_check<T: ErrorBuilder>(
self,
error_builder: &T,
) -> Result<Box<dyn operator::OperatorBuilder + Send + Sync>, TypeError> {
match self.value {
lang::InlineOperator::Json { input_column } => Ok(Box::new(operator::ParseJson::new(
input_column
.map(|e| e.type_check(error_builder))
.transpose()?,
))),
lang::InlineOperator::Logfmt { input_column } => {
Ok(Box::new(operator::ParseLogfmt::new(
input_column
.map(|e| e.type_check(error_builder))
.transpose()?,
)))
}
lang::InlineOperator::Parse {
pattern,
fields,
input_column,
no_drop,
} => {
let regex = pattern.to_regex();
let input_column = match input_column {
(Some(from), None) | (None, Some(from)) => Some(from.value),
(None, None) => None,
(Some(l), Some(r)) => {
let e = TypeError::DoubleFromClause;
error_builder
.report_error_for(&e)
.with_code_pointer(&l, "")
.with_code_pointer(&r, "")
.with_resolution("Only one from clause is allowed")
.send_report();
return Err(e);
}
};
if (regex.captures_len() - 1) != fields.len() {
Err(TypeError::ParseNumPatterns {
pattern: regex.captures_len() - 1,
extracted: fields.len(),
})
} else {
Ok(Box::new(operator::Parse::new(
regex,
fields,
input_column
.map(|e| e.type_check(error_builder))
.transpose()?,
operator::ParseOptions {
drop_nonmatching: !no_drop,
},
)))
}
}
lang::InlineOperator::Fields { fields, mode } => {
let omode = match mode {
lang::FieldMode::Except => operator::FieldMode::Except,
lang::FieldMode::Only => operator::FieldMode::Only,
};
Ok(Box::new(operator::Fields::new(&fields, omode)))
}
lang::InlineOperator::Where { expr: Some(expr) } => match expr
.value
.type_check(error_builder)?
{
operator::Expr::Value(constant) => {
if let Value::Bool(bool_value) = constant {
Ok(Box::new(operator::Where::new(*bool_value)))
} else {
let e = TypeError::ExpectedBool {
found: format!("{:?}", constant),
};
error_builder
.report_error_for(&e)
.with_code_range(expr.range, "This is constant")
.with_resolution("Perhaps you meant to compare a field to this value?")
.with_resolution(format!("example: where field1 == {}", constant))
.send_report();
Err(e)
}
}
generic_expr => Ok(Box::new(operator::Where::new(generic_expr))),
},
lang::InlineOperator::Where { expr: None } => {
let e = TypeError::ExpectedExpr;
error_builder
.report_error_for(&e)
.with_code_pointer(&self, "No condition provided for this 'where'")
.with_resolution(
"Insert an expression whose result determines whether a record should be \
passed downstream",
)
.with_resolution("example: where duration > 100")
.send_report();
Err(e)
}
lang::InlineOperator::Limit { count: Some(count) } => match count.value {
limit if limit.trunc() == 0.0 || limit.fract() != 0.0 => {
let e = TypeError::InvalidLimit { limit };
error_builder
.report_error_for(e.to_string())
.with_code_pointer(
&count,
if limit.fract() != 0.0 {
"Fractional limits are not allowed"
} else {
"Zero is not allowed"
},
)
.with_resolution("Use a positive integer to select the first N rows")
.with_resolution("Use a negative integer to select the last N rows")
.send_report();
Err(e)
}
limit => Ok(Box::new(operator::LimitDef::new(limit as i64))),
},
lang::InlineOperator::Limit { count: None } => {
Ok(Box::new(operator::LimitDef::new(DEFAULT_LIMIT)))
}
lang::InlineOperator::Split {
separator,
input_column,
output_column,
} => Ok(Box::new(operator::Split::new(
separator,
input_column
.map(|e| e.type_check(error_builder))
.transpose()?,
output_column
.map(|e| e.type_check(error_builder))
.transpose()?,
))),
lang::InlineOperator::Timeslice { duration: None, .. } => {
Err(TypeError::ExpectedDuration)
}
lang::InlineOperator::Timeslice {
input_column,
duration: Some(duration),
output_column,
} => Ok(Box::new(operator::Timeslice::new(
input_column.type_check(error_builder)?,
duration,
output_column,
))),
lang::InlineOperator::Total {
input_column,
output_column,
} => Ok(Box::new(operator::TotalDef::new(
input_column.type_check(error_builder)?,
output_column,
))),
lang::InlineOperator::FieldExpression { value, name } => Ok(Box::new(
operator::FieldExpressionDef::new(value.type_check(error_builder)?, name),
)),
}
}
}
impl TypeCheck<Box<dyn operator::AggregateFunction>> for lang::Positioned<lang::AggregateFunction> {
fn type_check<T: ErrorBuilder>(
self,
error_builder: &T,
) -> Result<Box<dyn operator::AggregateFunction>, TypeError> {
match self.value {
lang::AggregateFunction::Count { condition } => {
let expr = condition.map(|c| c.type_check(error_builder)).transpose()?;
Ok(Box::new(operator::Count::new(expr)))
}
lang::AggregateFunction::Min { column } => Ok(Box::new(operator::Min::empty(
column.type_check(error_builder)?,
))),
lang::AggregateFunction::Average { column } => Ok(Box::new(operator::Average::empty(
column.type_check(error_builder)?,
))),
lang::AggregateFunction::Max { column } => Ok(Box::new(operator::Max::empty(
column.type_check(error_builder)?,
))),
lang::AggregateFunction::Sum { column } => Ok(Box::new(operator::Sum::empty(
column.type_check(error_builder)?,
))),
lang::AggregateFunction::Percentile {
column, percentile, ..
} => Ok(Box::new(operator::Percentile::empty(
column.type_check(error_builder)?,
percentile,
))),
lang::AggregateFunction::CountDistinct { column: Some(pos) } => {
match pos.value.as_slice() {
[column] => Ok(Box::new(operator::CountDistinct::empty(
column.clone().type_check(error_builder)?,
))),
_ => {
error_builder
.report_error_for("Expecting a single expression to count")
.with_code_pointer(
&pos,
match pos.value.len() {
0 => "No expression given",
_ => "Only a single expression can be given",
},
)
.with_resolution("example: count_distinct(field_to_count)")
.send_report();
Err(TypeError::ExpectedExpr)
}
}
}
lang::AggregateFunction::CountDistinct { column: None } => {
error_builder
.report_error_for("Expecting an expression to count")
.with_code_pointer(&self, "No field argument given")
.with_resolution("example: count_distinct(field_to_count)")
.send_report();
Err(TypeError::ExpectedExpr)
}
lang::AggregateFunction::Error => unreachable!(),
}
}
}
| 41.48642 | 100 | 0.473932 |
71cc130ecc8edf5f83d060573af1e0d5a7751e2a | 6,080 | use anyhow::Error;
use std::{
collections::HashMap,
fs::{create_dir_all, read_dir},
io::{self},
path::PathBuf,
sync::Arc,
};
use swc::{config::SourceMapsConfig, resolver::environment_resolver};
use swc_atoms::js_word;
use swc_bundler::{BundleKind, Bundler, Config, ModuleRecord};
use swc_common::{FileName, Span, GLOBALS};
use swc_ecma_ast::{
Bool, EsVersion, Expr, ExprOrSuper, Ident, KeyValueProp, Lit, MemberExpr, MetaPropExpr,
PropName, Str, TargetEnv,
};
use swc_ecma_loader::NODE_BUILTINS;
use swc_ecma_transforms::fixer;
use swc_ecma_visit::FoldWith;
use swc_node_bundler::loaders::swc::SwcLoader;
use testing::NormalizedOutput;
#[testing::fixture("tests/pass/**/input")]
fn pass(input_dir: PathBuf) {
let _ = pretty_env_logger::try_init();
let entry = input_dir.parent().unwrap().to_path_buf();
let _ = create_dir_all(entry.join("output"));
let entries = read_dir(&input_dir)
.unwrap()
.filter(|e| match e {
Ok(e) => {
if e.path()
.file_name()
.unwrap()
.to_string_lossy()
.starts_with("entry")
{
true
} else {
false
}
}
_ => false,
})
.map(|e| -> Result<_, io::Error> {
let e = e?;
Ok((
e.file_name().to_string_lossy().to_string(),
FileName::Real(e.path()),
))
})
.collect::<Result<HashMap<_, _>, _>>()
.unwrap();
testing::run_test2(false, |cm, _handler| {
let compiler = Arc::new(swc::Compiler::new(cm.clone()));
GLOBALS.set(compiler.globals(), || {
let loader = SwcLoader::new(
compiler.clone(),
swc::config::Options {
swcrc: true,
..Default::default()
},
);
let mut bundler = Bundler::new(
compiler.globals(),
cm.clone(),
&loader,
environment_resolver(TargetEnv::Node, Default::default()),
Config {
require: true,
disable_inliner: true,
module: Default::default(),
external_modules: NODE_BUILTINS.to_vec().into_iter().map(From::from).collect(),
},
Box::new(Hook),
);
let modules = bundler
.bundle(entries)
.map_err(|err| println!("{:?}", err))?;
println!("Bundled as {} modules", modules.len());
let mut error = false;
for bundled in modules {
let code = compiler
.print(
&bundled.module.fold_with(&mut fixer(None)),
None,
None,
false,
EsVersion::Es2020,
SourceMapsConfig::Bool(false),
&Default::default(),
None,
false,
Some(true.into()),
)
.expect("failed to print?")
.code;
let name = match bundled.kind {
BundleKind::Named { name } | BundleKind::Lib { name } => PathBuf::from(name),
BundleKind::Dynamic => format!("dynamic.{}.js", bundled.id).into(),
};
let output_path = entry
.join("output")
.join(name.file_name().unwrap())
.with_extension("js");
println!("Printing {}", output_path.display());
// {
// let status = Command::new("node")
// .arg(&output_path)
// .stdout(Stdio::inherit())
// .stderr(Stdio::inherit())
// .status()
// .unwrap();
// assert!(status.success());
// }
let s = NormalizedOutput::from(code);
match s.compare_to_file(&output_path) {
Ok(_) => {}
Err(err) => {
println!("Diff: {:?}", err);
error = true;
}
}
}
if error {
return Err(());
}
Ok(())
})
})
.expect("failed to process a module");
}
struct Hook;
impl swc_bundler::Hook for Hook {
fn get_import_meta_props(
&self,
span: Span,
module_record: &ModuleRecord,
) -> Result<Vec<KeyValueProp>, Error> {
Ok(vec![
KeyValueProp {
key: PropName::Ident(Ident::new(js_word!("url"), span)),
value: Box::new(Expr::Lit(Lit::Str(Str {
span,
value: module_record.file_name.to_string().into(),
has_escape: false,
kind: Default::default(),
}))),
},
KeyValueProp {
key: PropName::Ident(Ident::new(js_word!("main"), span)),
value: Box::new(if module_record.is_entry {
Expr::Member(MemberExpr {
span,
obj: ExprOrSuper::Expr(Box::new(Expr::MetaProp(MetaPropExpr {
meta: Ident::new(js_word!("import"), span),
prop: Ident::new(js_word!("meta"), span),
}))),
prop: Box::new(Expr::Ident(Ident::new(js_word!("main"), span))),
computed: false,
})
} else {
Expr::Lit(Lit::Bool(Bool { span, value: false }))
}),
},
])
}
}
| 32.513369 | 99 | 0.426809 |
feec5d52ffd7ab9f54b51f0086e722c4086f289b | 32,251 | use crate::RustIrDatabase;
use chalk_ir::cast::{Cast, Caster};
use chalk_ir::fold::shift::Shift;
use chalk_ir::fold::Subst;
use chalk_ir::*;
use chalk_rust_ir::*;
use std::iter;
/// Trait for lowering a given piece of rust-ir source (e.g., an impl
/// or struct definition) into its associated "program clauses" --
/// that is, into the lowered, logical rules that it defines.
pub trait ToProgramClauses {
fn to_program_clauses(&self, db: &dyn RustIrDatabase, clauses: &mut Vec<ProgramClause>);
}
impl ToProgramClauses for ImplDatum {
/// Given `impl<T: Clone> Clone for Vec<T> { ... }`, generate:
///
/// ```notrust
/// -- Rule Implemented-From-Impl
/// forall<T> {
/// Implemented(Vec<T>: Clone) :- Implemented(T: Clone).
/// }
/// ```
///
/// For a negative impl like `impl... !Clone for ...`, however, we
/// generate nothing -- this is just a way to *opt out* from the
/// default auto trait impls, it doesn't have any positive effect
/// on its own.
fn to_program_clauses(&self, _db: &dyn RustIrDatabase, clauses: &mut Vec<ProgramClause>) {
if self.is_positive() {
clauses.push(
self.binders
.map_ref(|bound| ProgramClauseImplication {
consequence: bound.trait_ref.trait_ref().clone().cast(),
conditions: bound.where_clauses.iter().cloned().casted().collect(),
})
.cast(),
);
}
}
}
impl ToProgramClauses for AssociatedTyValue {
/// Given the following trait:
///
/// ```notrust
/// trait Iterable {
/// type IntoIter<'a>: 'a;
/// }
/// ```
///
/// Then for the following impl:
/// ```notrust
/// impl<T> Iterable for Vec<T> {
/// type IntoIter<'a> = Iter<'a, T>;
/// }
/// ```
///
/// we generate:
///
/// ```notrust
/// -- Rule Normalize-From-Impl
/// forall<'a, T> {
/// Normalize(<Vec<T> as Iterable>::IntoIter<'a> -> Iter<'a, T>>) :-
/// Implemented(Vec<T>: Iterable), // (1)
/// Implemented(Iter<'a, T>: 'a). // (2)
/// }
/// ```
///
/// and:
///
/// ```notrust
/// forall<'a, T> {
/// UnselectedNormalize(Vec<T>::IntoIter<'a> -> Iter<'a, T>) :-
/// InScope(Iterable),
/// Normalize(<Vec<T> as Iterable>::IntoIter<'a> -> Iter<'a, T>).
/// }
/// ```
fn to_program_clauses(&self, db: &dyn RustIrDatabase, clauses: &mut Vec<ProgramClause>) {
let impl_datum = db.impl_datum(self.impl_id);
let associated_ty = db.associated_ty_data(self.associated_ty_id);
// Begin with the innermost parameters (`'a`) and then add those from impl (`T`).
let all_binders: Vec<_> = self
.value
.binders
.iter()
.chain(impl_datum.binders.binders.iter())
.cloned()
.collect();
let impl_trait_ref = impl_datum
.binders
.value
.trait_ref
.trait_ref()
.shifted_in(self.value.len());
let all_parameters: Vec<_> = self
.value
.binders
.iter()
.zip(0..)
.map(|p| p.to_parameter())
.chain(impl_trait_ref.parameters.iter().cloned())
.collect();
// Assemble the full list of conditions for projection to be valid.
// This comes in two parts, marked as (1) and (2) in doc above:
//
// 1. require that the trait is implemented
// 2. any where-clauses from the `type` declaration in the trait: the
// parameters must be substituted with those of the impl
let where_clauses = associated_ty
.where_clauses
.iter()
.map(|wc| Subst::apply(&all_parameters, wc))
.casted();
let conditions: Vec<Goal> = where_clauses
.chain(Some(impl_trait_ref.clone().cast()))
.collect();
// Bound parameters + `Self` type of the trait-ref
let parameters: Vec<_> = {
// First add refs to the bound parameters (`'a`, in above example)
let parameters = self.value.binders.iter().zip(0..).map(|p| p.to_parameter());
// Then add the `Self` type (`Vec<T>`, in above example)
parameters
.chain(Some(impl_trait_ref.parameters[0].clone()))
.collect()
};
let projection = ProjectionTy {
associated_ty_id: self.associated_ty_id,
// Add the remaining parameters of the trait-ref, if any
parameters: parameters
.iter()
.chain(&impl_trait_ref.parameters[1..])
.cloned()
.collect(),
};
let normalize_goal = DomainGoal::Normalize(Normalize {
projection: projection.clone(),
ty: self.value.value.ty.clone(),
});
// Determine the normalization
let normalization = Binders {
binders: all_binders.clone(),
value: ProgramClauseImplication {
consequence: normalize_goal.clone(),
conditions: conditions,
},
}
.cast();
let unselected_projection = UnselectedProjectionTy {
type_name: associated_ty.name.clone(),
parameters: parameters,
};
let unselected_normalization = Binders {
binders: all_binders,
value: ProgramClauseImplication {
consequence: DomainGoal::UnselectedNormalize(UnselectedNormalize {
projection: unselected_projection,
ty: self.value.value.ty.clone(),
}),
conditions: vec![
normalize_goal.cast(),
DomainGoal::InScope(impl_trait_ref.trait_id.into()).cast(),
],
},
}
.cast();
clauses.push(normalization);
clauses.push(unselected_normalization);
}
}
impl ToProgramClauses for StructDatum {
/// Given the following type definition: `struct Foo<T: Eq> { }`, generate:
///
/// ```notrust
/// -- Rule WellFormed-Type
/// forall<T> {
/// WF(Foo<T>) :- WF(T: Eq).
/// }
///
/// -- Rule Implied-Bound-From-Type
/// forall<T> {
/// FromEnv(T: Eq) :- FromEnv(Foo<T>).
/// }
///
/// forall<T> {
/// IsFullyVisible(Foo<T>) :- IsFullyVisible(T).
/// }
/// ```
///
/// If the type `Foo` is marked `#[upstream]`, we also generate:
///
/// ```notrust
/// forall<T> { IsUpstream(Foo<T>). }
/// ```
///
/// Otherwise, if the type `Foo` is not marked `#[upstream]`, we generate:
/// ```notrust
/// forall<T> { IsLocal(Foo<T>). }
/// ```
///
/// Given an `#[upstream]` type that is also fundamental:
///
/// ```notrust
/// #[upstream]
/// #[fundamental]
/// struct Box<T> {}
/// ```
///
/// We generate the following clauses:
///
/// ```notrust
/// forall<T> { IsLocal(Box<T>) :- IsLocal(T). }
///
/// forall<T> { IsUpstream(Box<T>) :- IsUpstream(T). }
///
/// // Generated for both upstream and local fundamental types
/// forall<T> { DownstreamType(Box<T>) :- DownstreamType(T). }
/// ```
///
fn to_program_clauses(&self, _db: &dyn RustIrDatabase, clauses: &mut Vec<ProgramClause>) {
let wf = self
.binders
.map_ref(|bound_datum| ProgramClauseImplication {
consequence: WellFormed::Ty(bound_datum.self_ty.clone().cast()).cast(),
conditions: bound_datum
.where_clauses
.iter()
.cloned()
.map(|wc| wc.map(|bound| bound.into_well_formed_goal()))
.casted()
.collect(),
})
.cast();
let is_fully_visible = self
.binders
.map_ref(|bound_datum| ProgramClauseImplication {
consequence: DomainGoal::IsFullyVisible(bound_datum.self_ty.clone().cast()),
conditions: bound_datum
.self_ty
.type_parameters()
.map(|ty| DomainGoal::IsFullyVisible(ty).cast())
.collect(),
})
.cast();
clauses.push(wf);
clauses.push(is_fully_visible);
// Fundamental types often have rules in the form of:
// Goal(FundamentalType<T>) :- Goal(T)
// This macro makes creating that kind of clause easy
macro_rules! fundamental_rule {
($goal:ident) => {
// Fundamental types must always have at least one type parameter for this rule to
// make any sense. We currently do not have have any fundamental types with more than
// one type parameter, nor do we know what the behaviour for that should be. Thus, we
// are asserting here that there is only a single type parameter until the day when
// someone makes a decision about how that should behave.
assert_eq!(self.binders.value.self_ty.len_type_parameters(), 1,
"Only fundamental types with a single parameter are supported");
clauses.push(self.binders.map_ref(|bound_datum| ProgramClauseImplication {
consequence: DomainGoal::$goal(bound_datum.self_ty.clone().cast()),
conditions: vec![
DomainGoal::$goal(
// This unwrap is safe because we asserted above for the presence of a type
// parameter
bound_datum.self_ty.first_type_parameter().unwrap()
).cast(),
],
}).cast());
};
}
// Types that are not marked `#[upstream]` satisfy IsLocal(TypeName)
if !self.binders.value.flags.upstream {
// `IsLocalTy(Ty)` depends *only* on whether the type is marked #[upstream] and nothing else
let is_local = self
.binders
.map_ref(|bound_datum| ProgramClauseImplication {
consequence: DomainGoal::IsLocal(bound_datum.self_ty.clone().cast()),
conditions: Vec::new(),
})
.cast();
clauses.push(is_local);
} else if self.binders.value.flags.fundamental {
// If a type is `#[upstream]`, but is also `#[fundamental]`, it satisfies IsLocal
// if and only if its parameters satisfy IsLocal
fundamental_rule!(IsLocal);
fundamental_rule!(IsUpstream);
} else {
// The type is just upstream and not fundamental
let is_upstream = self
.binders
.map_ref(|bound_datum| ProgramClauseImplication {
consequence: DomainGoal::IsUpstream(bound_datum.self_ty.clone().cast()),
conditions: Vec::new(),
})
.cast();
clauses.push(is_upstream);
}
if self.binders.value.flags.fundamental {
fundamental_rule!(DownstreamType);
}
let condition = DomainGoal::FromEnv(FromEnv::Ty(self.binders.value.self_ty.clone().cast()));
for wc in self
.binders
.value
.where_clauses
.iter()
.cloned()
.map(|wc| wc.map(|bound| bound.into_from_env_goal()))
{
// We move the binders of the where-clause to the left, e.g. if we had:
//
// `forall<T> { WellFormed(Foo<T>) :- forall<'a> Implemented(T: Fn(&'a i32)) }`
//
// then the reverse rule will be:
//
// `forall<'a, T> { FromEnv(T: Fn(&'a i32)) :- FromEnv(Foo<T>) }`
//
let shift = wc.binders.len();
clauses.push(
Binders {
binders: wc
.binders
.into_iter()
.chain(self.binders.binders.clone())
.collect(),
value: ProgramClauseImplication {
consequence: wc.value,
conditions: vec![condition.clone().shifted_in(shift).cast()],
},
}
.cast(),
);
}
}
}
impl ToProgramClauses for TraitDatum {
/// Given the following trait declaration: `trait Ord<T> where Self: Eq<T> { ... }`, generate:
///
/// ```notrust
/// -- Rule WellFormed-TraitRef
/// forall<Self, T> {
/// WF(Self: Ord<T>) :- Implemented(Self: Ord<T>), WF(Self: Eq<T>).
/// }
/// ```
///
/// and the reverse rules:
///
/// ```notrust
/// -- Rule Implemented-From-Env
/// forall<Self, T> {
/// (Self: Ord<T>) :- FromEnv(Self: Ord<T>).
/// }
///
/// -- Rule Implied-Bound-From-Trait
/// forall<Self, T> {
/// FromEnv(Self: Eq<T>) :- FromEnv(Self: Ord<T>).
/// }
/// ```
///
/// As specified in the orphan rules, if a trait is not marked `#[upstream]`, the current crate
/// can implement it for any type. To represent that, we generate:
///
/// ```notrust
/// // `Ord<T>` would not be `#[upstream]` when compiling `std`
/// forall<Self, T> { LocalImplAllowed(Self: Ord<T>). }
/// ```
///
/// For traits that are `#[upstream]` (i.e. not in the current crate), the orphan rules dictate
/// that impls are allowed as long as at least one type parameter is local and each type
/// prior to that is fully visible. That means that each type prior to the first local
/// type cannot contain any of the type parameters of the impl.
///
/// This rule is fairly complex, so we expand it and generate a program clause for each
/// possible case. This is represented as follows:
///
/// ```notrust
/// // for `#[upstream] trait Foo<T, U, V> where Self: Eq<T> { ... }`
/// forall<Self, T, U, V> {
/// LocalImplAllowed(Self: Foo<T, U, V>) :- IsLocal(Self).
/// }
///
/// forall<Self, T, U, V> {
/// LocalImplAllowed(Self: Foo<T, U, V>) :-
/// IsFullyVisible(Self),
/// IsLocal(T).
/// }
///
/// forall<Self, T, U, V> {
/// LocalImplAllowed(Self: Foo<T, U, V>) :-
/// IsFullyVisible(Self),
/// IsFullyVisible(T),
/// IsLocal(U).
/// }
///
/// forall<Self, T, U, V> {
/// LocalImplAllowed(Self: Foo<T, U, V>) :-
/// IsFullyVisible(Self),
/// IsFullyVisible(T),
/// IsFullyVisible(U),
/// IsLocal(V).
/// }
/// ```
///
/// The overlap check uses compatible { ... } mode to ensure that it accounts for impls that
/// may exist in some other *compatible* world. For every upstream trait, we add a rule to
/// account for the fact that upstream crates are able to compatibly add impls of upstream
/// traits for upstream types.
///
/// ```notrust
/// // For `#[upstream] trait Foo<T, U, V> where Self: Eq<T> { ... }`
/// forall<Self, T, U, V> {
/// Implemented(Self: Foo<T, U, V>) :-
/// Implemented(Self: Eq<T>), // where clauses
/// Compatible, // compatible modality
/// IsUpstream(Self),
/// IsUpstream(T),
/// IsUpstream(U),
/// IsUpstream(V),
/// CannotProve. // returns ambiguous
/// }
/// ```
///
/// In certain situations, this is too restrictive. Consider the following code:
///
/// ```notrust
/// /* In crate std */
/// trait Sized { }
/// struct str { }
///
/// /* In crate bar (depends on std) */
/// trait Bar { }
/// impl Bar for str { }
/// impl<T> Bar for T where T: Sized { }
/// ```
///
/// Here, because of the rules we've defined, these two impls overlap. The std crate is
/// upstream to bar, and thus it is allowed to compatibly implement Sized for str. If str
/// can implement Sized in a compatible future, these two impls definitely overlap since the
/// second impl covers all types that implement Sized.
///
/// The solution we've got right now is to mark Sized as "fundamental" when it is defined.
/// This signals to the Rust compiler that it can rely on the fact that str does not
/// implement Sized in all contexts. A consequence of this is that we can no longer add an
/// implementation of Sized compatibly for str. This is the trade off you make when defining
/// a fundamental trait.
///
/// To implement fundamental traits, we simply just do not add the rule above that allows
/// upstream types to implement upstream traits. Fundamental traits are not allowed to
/// compatibly do that.
fn to_program_clauses(&self, _db: &dyn RustIrDatabase, clauses: &mut Vec<ProgramClause>) {
let trait_ref = self.binders.value.trait_ref.clone();
let trait_ref_impl = WhereClause::Implemented(self.binders.value.trait_ref.clone());
let wf = self
.binders
.map_ref(|bound| ProgramClauseImplication {
consequence: WellFormed::Trait(trait_ref.clone()).cast(),
conditions: {
bound
.where_clauses
.iter()
.cloned()
.map(|wc| wc.map(|bound| bound.into_well_formed_goal()))
.casted()
.chain(Some(DomainGoal::Holds(trait_ref_impl.clone()).cast()))
.collect()
},
})
.cast();
clauses.push(wf);
// The number of parameters will always be at least 1 because of the Self parameter
// that is automatically added to every trait. This is important because otherwise
// the added program clauses would not have any conditions.
let type_parameters: Vec<_> = self.binders.value.trait_ref.type_parameters().collect();
// Add all cases for potential downstream impls that could exist
clauses.extend((0..type_parameters.len()).map(|i| {
let impl_may_exist =
self.binders
.map_ref(|bound_datum| ProgramClauseImplication {
consequence: DomainGoal::Holds(WhereClause::Implemented(
bound_datum.trait_ref.clone(),
)),
conditions: bound_datum
.where_clauses
.iter()
.cloned()
.casted()
.chain(iter::once(DomainGoal::Compatible(()).cast()))
.chain((0..i).map(|j| {
DomainGoal::IsFullyVisible(type_parameters[j].clone()).cast()
}))
.chain(iter::once(
DomainGoal::DownstreamType(type_parameters[i].clone()).cast(),
))
.chain(iter::once(Goal::CannotProve(())))
.collect(),
})
.cast();
impl_may_exist
}));
if !self.binders.value.flags.upstream {
let impl_allowed = self
.binders
.map_ref(|bound_datum| ProgramClauseImplication {
consequence: DomainGoal::LocalImplAllowed(bound_datum.trait_ref.clone()),
conditions: Vec::new(),
})
.cast();
clauses.push(impl_allowed);
} else {
clauses.extend((0..type_parameters.len()).map(|i| {
let impl_maybe_allowed = self
.binders
.map_ref(|bound_datum| ProgramClauseImplication {
consequence: DomainGoal::LocalImplAllowed(bound_datum.trait_ref.clone()),
conditions: (0..i)
.map(|j| DomainGoal::IsFullyVisible(type_parameters[j].clone()).cast())
.chain(iter::once(
DomainGoal::IsLocal(type_parameters[i].clone()).cast(),
))
.collect(),
})
.cast();
impl_maybe_allowed
}));
// Fundamental traits can be reasoned about negatively without any ambiguity, so no
// need for this rule if the trait is fundamental.
if !self.binders.value.flags.fundamental {
let impl_may_exist = self
.binders
.map_ref(|bound_datum| ProgramClauseImplication {
consequence: DomainGoal::Holds(WhereClause::Implemented(
bound_datum.trait_ref.clone(),
)),
conditions: bound_datum
.where_clauses
.iter()
.cloned()
.casted()
.chain(iter::once(DomainGoal::Compatible(()).cast()))
.chain(
bound_datum
.trait_ref
.type_parameters()
.map(|ty| DomainGoal::IsUpstream(ty).cast()),
)
.chain(iter::once(Goal::CannotProve(())))
.collect(),
})
.cast();
clauses.push(impl_may_exist);
}
}
let condition = DomainGoal::FromEnv(FromEnv::Trait(trait_ref.clone()));
clauses.extend(
self.binders
.value
.where_clauses
.iter()
.cloned()
.map(|wc| wc.map(|bound| bound.into_from_env_goal()))
.map(|wc| {
// We move the binders of the where-clause to the left for the reverse rules,
// cf `StructDatum::to_program_clauses`.
let shift = wc.binders.len();
Binders {
binders: wc
.binders
.into_iter()
.chain(self.binders.binders.clone())
.collect(),
value: ProgramClauseImplication {
consequence: wc.value,
conditions: vec![condition.clone().shifted_in(shift).cast()],
},
}
.cast()
}),
);
clauses.push(
self.binders
.map_ref(|_| ProgramClauseImplication {
consequence: DomainGoal::Holds(trait_ref_impl),
conditions: vec![condition.cast()],
})
.cast(),
);
}
}
impl ToProgramClauses for AssociatedTyDatum {
/// For each associated type, we define the "projection
/// equality" rules. There are always two; one for a successful normalization,
/// and one for the "fallback" notion of equality.
///
/// Given: (here, `'a` and `T` represent zero or more parameters)
///
/// ```notrust
/// trait Foo {
/// type Assoc<'a, T>: Bounds where WC;
/// }
/// ```
///
/// we generate the 'fallback' rule:
///
/// ```notrust
/// -- Rule ProjectionEq-Placeholder
/// forall<Self, 'a, T> {
/// ProjectionEq(<Self as Foo>::Assoc<'a, T> = (Foo::Assoc<'a, T>)<Self>).
/// }
/// ```
///
/// and
///
/// ```notrust
/// -- Rule ProjectionEq-Normalize
/// forall<Self, 'a, T, U> {
/// ProjectionEq(<T as Foo>::Assoc<'a, T> = U) :-
/// Normalize(<T as Foo>::Assoc -> U).
/// }
/// ```
///
/// We used to generate an "elaboration" rule like this:
///
/// ```notrust
/// forall<T> {
/// T: Foo :- exists<U> { ProjectionEq(<T as Foo>::Assoc = U) }.
/// }
/// ```
///
/// but this caused problems with the recursive solver. In
/// particular, whenever normalization is possible, we cannot
/// solve that projection uniquely, since we can now elaborate
/// `ProjectionEq` to fallback *or* normalize it. So instead we
/// handle this kind of reasoning through the `FromEnv` predicate.
///
/// We also generate rules specific to WF requirements and implied bounds:
///
/// ```notrust
/// -- Rule WellFormed-AssocTy
/// forall<Self, 'a, T> {
/// WellFormed((Foo::Assoc)<Self, 'a, T>) :- WellFormed(Self: Foo), WellFormed(WC).
/// }
///
/// -- Rule Implied-WC-From-AssocTy
/// forall<Self, 'a, T> {
/// FromEnv(WC) :- FromEnv((Foo::Assoc)<Self, 'a, T>).
/// }
///
/// -- Rule Implied-Bound-From-AssocTy
/// forall<Self, 'a, T> {
/// FromEnv(<Self as Foo>::Assoc<'a,T>: Bounds) :- FromEnv(Self: Foo), WC.
/// }
///
/// -- Rule Implied-Trait-From-AssocTy
/// forall<Self,'a, T> {
/// FromEnv(Self: Foo) :- FromEnv((Foo::Assoc)<Self, 'a,T>).
/// }
/// ```
fn to_program_clauses(&self, db: &dyn RustIrDatabase, clauses: &mut Vec<ProgramClause>) {
let binders: Vec<_> = self
.parameter_kinds
.iter()
.map(|pk| pk.map(|_| ()))
.collect();
let parameters: Vec<_> = binders.iter().zip(0..).map(|p| p.to_parameter()).collect();
let projection = ProjectionTy {
associated_ty_id: self.id,
parameters: parameters.clone(),
};
// Retrieve the trait ref embedding the associated type
let trait_ref = {
let (associated_ty_data, trait_params, _) = db.split_projection(&projection);
TraitRef {
trait_id: associated_ty_data.trait_id,
parameters: trait_params.to_owned(),
}
};
// Construct an application from the projection. So if we have `<T as Iterator>::Item`,
// we would produce `(Iterator::Item)<T>`.
let app = ApplicationTy {
name: TypeName::AssociatedType(self.id),
parameters,
};
let app_ty = Ty::Apply(app);
let projection_eq = ProjectionEq {
projection: projection.clone(),
ty: app_ty.clone(),
};
// Fallback rule. The solver uses this to move between the projection
// and placeholder type.
//
// forall<Self> {
// ProjectionEq(<Self as Foo>::Assoc = (Foo::Assoc)<Self>).
// }
clauses.push(
Binders {
binders: binders.clone(),
value: ProgramClauseImplication {
consequence: projection_eq.clone().cast(),
conditions: vec![],
},
}
.cast(),
);
// Well-formedness of projection type.
//
// forall<Self> {
// WellFormed((Foo::Assoc)<Self>) :- WellFormed(Self: Foo), WellFormed(WC).
// }
clauses.push(
Binders {
binders: binders.clone(),
value: ProgramClauseImplication {
consequence: WellFormed::Ty(app_ty.clone()).cast(),
conditions: iter::once(WellFormed::Trait(trait_ref.clone()).cast())
.chain(
self.where_clauses
.iter()
.cloned()
.map(|wc| wc.map(|bound| bound.into_well_formed_goal()))
.casted(),
)
.collect(),
},
}
.cast(),
);
// Assuming well-formedness of projection type means we can assume
// the trait ref as well. Mostly used in function bodies.
//
// forall<Self> {
// FromEnv(Self: Foo) :- FromEnv((Foo::Assoc)<Self>).
// }
clauses.push(
Binders {
binders: binders.clone(),
value: ProgramClauseImplication {
consequence: FromEnv::Trait(trait_ref.clone()).cast(),
conditions: vec![FromEnv::Ty(app_ty.clone()).cast()],
},
}
.cast(),
);
// Reverse rule for where clauses.
//
// forall<Self> {
// FromEnv(WC) :- FromEnv((Foo::Assoc)<Self>).
// }
//
// This is really a family of clauses, one for each where clause.
clauses.extend(self.where_clauses.iter().map(|wc| {
// Don't forget to move the binders to the left in case of higher-ranked where clauses.
let shift = wc.binders.len();
Binders {
binders: wc.binders.iter().chain(binders.iter()).cloned().collect(),
value: ProgramClauseImplication {
consequence: wc.value.clone().into_from_env_goal(),
conditions: vec![FromEnv::Ty(app_ty.clone()).shifted_in(shift).cast()],
},
}
.cast()
}));
// Reverse rule for implied bounds.
//
// forall<Self> {
// FromEnv(<Self as Foo>::Assoc: Bounds) :- FromEnv(Self: Foo), WC
// }
clauses.extend(self.bounds_on_self().into_iter().map(|bound| {
// Same as above in case of higher-ranked inline bounds.
let shift = bound.binders.len();
let from_env_trait =
iter::once(FromEnv::Trait(trait_ref.clone()).shifted_in(shift).cast());
let where_clauses = self.where_clauses.iter().cloned().casted();
Binders {
binders: bound
.binders
.iter()
.chain(binders.iter())
.cloned()
.collect(),
value: ProgramClauseImplication {
consequence: bound.value.clone().into_from_env_goal(),
conditions: from_env_trait.chain(where_clauses).collect(),
},
}
.cast()
}));
// add new type parameter U
let mut binders = binders;
binders.push(ParameterKind::Ty(()));
let ty = Ty::BoundVar(binders.len() - 1);
// `Normalize(<T as Foo>::Assoc -> U)`
let normalize = Normalize {
projection: projection.clone(),
ty: ty.clone(),
};
// `ProjectionEq(<T as Foo>::Assoc = U)`
let projection_eq = ProjectionEq {
projection: projection.clone(),
ty,
};
// Projection equality rule from above.
//
// forall<T, U> {
// ProjectionEq(<T as Foo>::Assoc = U) :-
// Normalize(<T as Foo>::Assoc -> U).
// }
clauses.push(
Binders {
binders: binders.clone(),
value: ProgramClauseImplication {
consequence: projection_eq.clone().cast(),
conditions: vec![normalize.clone().cast()],
},
}
.cast(),
);
}
}
| 36.690557 | 104 | 0.491799 |
dec3dff686f72854dcb4987ce98e989e3ed2707e | 22,345 | use mqtt::control::variable_header::ConnectReturnCode;
use mqtt::packet::*;
use mqtt::topic_name::TopicNameError;
use mqtt::Encodable;
use mqtt::TopicName;
#[cfg(any(
feature = "direct-methods",
feature = "c2d-messages",
feature = "twin-properties"
))]
use mqtt::{QualityOfService, TopicFilter};
use tokio::io::AsyncWriteExt;
use tokio::io::{ReadHalf, WriteHalf};
use tokio::net::TcpStream;
#[cfg(any(
feature = "direct-methods",
feature = "c2d-messages",
feature = "twin-properties"
))]
use tokio::sync::mpsc::{channel, Receiver};
use tokio::sync::Mutex;
use tokio::{task::JoinHandle, time};
use tokio_native_tls::{TlsConnector, TlsStream};
use async_trait::async_trait;
use crate::message::Message;
#[cfg(any(
feature = "direct-methods",
feature = "c2d-messages",
feature = "twin-properties"
))]
use crate::message::MessageType;
#[cfg(feature = "direct-methods")]
use crate::message::{DirectMethodInvocation, DirectMethodResponse};
use crate::{token::TokenSource, transport::Transport};
use chrono::{Duration, Utc};
use std::sync::Arc;
// Incoming topic names
#[cfg(feature = "direct-methods")]
const METHOD_POST_TOPIC_FILTER: &str = "$iothub/methods/POST/#";
#[cfg(feature = "direct-methods")]
const METHOD_POST_TOPIC_PREFIX: &str = "$iothub/methods/POST/";
#[cfg(feature = "twin-properties")]
const TWIN_RESPONSE_TOPIC_FILTER: &str = "$iothub/twin/res/#";
// const TWIN_RESPONSE_TOPIC_PREFIX: &str = "$iothub/twin/res/";
#[cfg(feature = "twin-properties")]
const TWIN_PATCH_TOPIC_FILTER: &str = "$iothub/twin/PATCH/properties/desired/#";
#[cfg(feature = "twin-properties")]
const TWIN_PATCH_TOPIC_PREFIX: &str = "$iothub/twin/PATCH/properties/desired/";
#[cfg(feature = "twin-properties")]
const TWIN_PATCH_UPDATE_PREFIX: &str = "$iothub/twin/PATCH/properties/reported/";
// Outgoing topic names
#[cfg(feature = "direct-methods")]
fn method_response_topic(status: i32, request_id: &str) -> String {
format!("$iothub/methods/res/{}/?$rid={}", status, request_id)
}
#[cfg(feature = "twin-properties")]
fn twin_get_topic(request_id: &str) -> String {
format!("$iothub/twin/GET/?$rid={}", request_id)
}
#[cfg(feature = "twin-properties")]
fn twin_update_topic(request_id: &str) -> String {
format!("{}?$rid={}", TWIN_PATCH_UPDATE_PREFIX, request_id)
}
#[cfg(feature = "c2d-messages")]
fn device_bound_messages_topic_filter(device_id: &str) -> String {
format!("devices/{}/messages/devicebound/#", device_id)
}
#[cfg(feature = "c2d-messages")]
fn device_bound_messages_topic_prefix(device_id: &str) -> String {
format!("devices/{}/messages/devicebound/", device_id)
}
fn cloud_bound_messages_topic(device_id: &str) -> String {
format!("devices/{}/messages/events/", device_id)
}
const KEEP_ALIVE: u16 = 10;
#[cfg(feature = "direct-methods")]
const REQUEST_ID_PARAM: &str = "?$rid=";
/// Connect to Azure IoT Hub
///
/// # Arguments
///
/// * `hub_name` - The IoT hub resource name
/// * `device_id` - The registered device to connect as
/// * `sas` - The shared access signature for the device to authenticate with
///
/// # Example
/// ```no_run
/// // let (read_socket, write_socket) = client::connect("myiothub".to_string(), "myfirstdevice".to_string(), "SharedAccessSignature sr=myiothub.azure-devices.net%2Fdevices%2Fmyfirstdevice&sig=blahblah&se=1586909077".to_string()).await;
/// ```
async fn tcp_connect(iot_hub: &str) -> crate::Result<TlsStream<TcpStream>> {
let socket = TcpStream::connect((iot_hub, 8883)).await?;
trace!("Connected to tcp socket {:?}", socket);
let cx = TlsConnector::from(
native_tls::TlsConnector::builder()
.min_protocol_version(Some(native_tls::Protocol::Tlsv12))
.build()
.unwrap(),
);
let socket = cx.connect(&iot_hub, socket).await?;
trace!("Connected tls context {:?}", cx);
Ok(socket)
}
pub(crate) async fn mqtt_connect(
hostname: &str,
client_identifier: &str,
username: impl ToString,
password: impl ToString,
) -> crate::Result<TlsStream<TcpStream>> {
let mut socket = tcp_connect(hostname).await?;
let mut conn = ConnectPacket::new(client_identifier);
conn.set_client_identifier(client_identifier);
conn.set_clean_session(false);
conn.set_keep_alive(KEEP_ALIVE);
conn.set_user_name(Some(username.to_string()));
conn.set_password(Some(password.to_string()));
let mut buf = Vec::new();
conn.encode(&mut buf).unwrap();
socket.write_all(&buf[..]).await?;
let packet = VariablePacket::parse(&mut socket).await;
trace!("PACKET {:?}", packet);
match packet {
//TODO: Enum error type instead of strings
Ok(VariablePacket::ConnackPacket(connack)) => {
if connack.connect_return_code() != ConnectReturnCode::ConnectionAccepted {
Err(format!(
"Failed to connect to server, return code {:?}",
connack.connect_return_code()
))
} else {
Ok(())
}
}
Ok(pck) => Err(format!(
"Unexpected packet received after connect {:?}",
pck
)),
Err(err) => Err(format!("Error decoding connack packet {:?}", err)),
}?;
Ok(socket)
}
// async fn ping(interval: u16) {
// let mut ping_interval = time::interval(time::Duration::from_secs(interval.into()));
// loop {
// ping_interval.tick().await;
// // sender.send(SendType::Ping).await.unwrap();
// }
// }
///
#[derive(Clone)]
pub(crate) struct MqttTransport {
token_source: Box<Arc<dyn TokenSource + Send + Sync + 'static>>,
write_socket: Arc<Mutex<WriteHalf<TlsStream<TcpStream>>>>,
read_socket: Arc<Mutex<ReadHalf<TlsStream<TcpStream>>>>,
d2c_topic: TopicName,
device_id: String,
#[cfg(feature = "c2d-messages")]
rx_topic_prefix: String,
ping_join_handle: Option<Arc<JoinHandle<()>>>,
// rx_loop_handle: Option<AbortHandle>,
}
impl Drop for MqttTransport {
fn drop(&mut self) {
// Check to see whether we're the last instance holding the Arc and only abort the ping if so
if let Some(handle) = self.ping_join_handle.take() {
if let Ok(handle) = Arc::try_unwrap(handle) {
handle.abort();
}
}
}
}
impl MqttTransport {
pub(crate) async fn new<TS>(
hub_name: &str,
device_id: String,
token_source: TS,
) -> crate::Result<Self>
where
TS: TokenSource + Send + Sync + 'static,
{
let user_name = format!("{}/{}/?api-version=2018-06-30", hub_name, device_id);
let expiry = Utc::now() + Duration::days(1);
trace!("Generating token that will expire at {}", expiry);
let token = token_source.get(&expiry);
trace!("Using token {}", token);
let socket = mqtt_connect(&hub_name, &device_id, user_name, token).await?;
let (read_socket, write_socket) = tokio::io::split(socket);
let mut mqtt_transport = Self {
token_source: Box::new(Arc::new(token_source)),
write_socket: Arc::new(Mutex::new(write_socket)),
read_socket: Arc::new(Mutex::new(read_socket)),
d2c_topic: TopicName::new(cloud_bound_messages_topic(&device_id)).unwrap(),
device_id: device_id.to_string(),
#[cfg(feature = "c2d-messages")]
rx_topic_prefix: device_bound_messages_topic_prefix(&device_id),
ping_join_handle: None,
// rx_loop_handle: None,
};
mqtt_transport.ping_join_handle = Some(Arc::new(mqtt_transport.ping_on_secs_interval(8)));
Ok(mqtt_transport)
}
///
fn ping_on_secs_interval(&self, ping_interval: u8) -> JoinHandle<()> {
let mut ping_interval = time::interval(time::Duration::from_secs(ping_interval.into()));
let mut cloned_self = self.clone();
tokio::spawn(async move {
loop {
ping_interval.tick().await;
let _ = cloned_self.ping().await;
}
})
}
}
#[async_trait]
impl Transport for MqttTransport {
async fn send_message(&mut self, message: Message) -> crate::Result<()> {
let full_topic = build_topic_name(&self.d2c_topic, &message).unwrap();
trace!("Sending message {:?} to topic {:?}", message, full_topic);
let publish_packet =
PublishPacket::new(full_topic, QoSWithPacketIdentifier::Level0, message.body);
let mut buf = Vec::new();
publish_packet.encode(&mut buf).unwrap();
self.write_socket
.lock()
.await
.write_all(&buf[..])
.await
.map_err(|e| e.into())
}
#[cfg(feature = "twin-properties")]
async fn send_property_update(&mut self, request_id: &str, body: &str) -> crate::Result<()> {
trace!("Publishing twin properties with rid = {}", request_id);
let packet = PublishPacket::new(
TopicName::new(twin_update_topic(&request_id)).unwrap(),
QoSWithPacketIdentifier::Level0,
body.as_bytes(),
);
let mut buf = vec![];
packet.encode(&mut buf).unwrap();
self.write_socket
.lock()
.await
.write_all(&buf[..])
.await
.map_err(|e| e.into())
}
#[cfg(feature = "twin-properties")]
async fn request_twin_properties(&mut self, request_id: &str) -> crate::Result<()> {
trace!(
"Requesting device twin properties with rid = {}",
request_id
);
let packet = PublishPacket::new(
TopicName::new(twin_get_topic(&request_id)).unwrap(),
QoSWithPacketIdentifier::Level0,
"".as_bytes(),
);
let mut buf = vec![];
packet.encode(&mut buf).unwrap();
self.write_socket
.lock()
.await
.write_all(&buf[..])
.await
.map_err(|e| e.into())
}
#[cfg(feature = "direct-methods")]
async fn respond_to_direct_method(
&mut self,
response: DirectMethodResponse,
) -> crate::Result<()> {
// TODO: Append properties and system properties to topic path
trace!(
"Responding to direct method with rid = {}",
response.request_id
);
let publish_packet = PublishPacket::new(
TopicName::new(method_response_topic(response.status, &response.request_id)).unwrap(),
QoSWithPacketIdentifier::Level0,
response.body,
);
let mut buf = Vec::new();
publish_packet.encode(&mut buf).unwrap();
self.write_socket
.lock()
.await
.write_all(&buf[..])
.await
.map_err(|e| e.into())
}
async fn ping(&mut self) -> crate::Result<()> {
debug!("Sending PINGREQ to broker");
let pingreq_packet = PingreqPacket::new();
let mut buf = Vec::new();
pingreq_packet.encode(&mut buf).unwrap();
self.write_socket
.lock()
.await
.write_all(&buf)
.await
.map_err(|e| e.into())
}
#[cfg(any(
feature = "direct-methods",
feature = "c2d-messages",
feature = "twin-properties",
feature = "error-handling-messages",
))]
async fn get_receiver(&mut self) -> Receiver<MessageType> {
let (handler_tx, handler_rx) = channel::<MessageType>(3);
let mut cloned_self = self.clone();
let _ = tokio::spawn(async move {
loop {
let mut socket = cloned_self.read_socket.lock().await;
let packet = match VariablePacket::parse(&mut *socket).await {
Ok(pk) => pk,
Err(err) => {
#[cfg(feature = "error-handling-messages")]
if handler_tx
.send(MessageType::ErrorReceive(err))
.await
.is_err()
{
break;
}
#[cfg(not(feature = "error-handling-messages"))]
error!("Error in receiving packet {}", err);
continue;
}
};
// Networking
trace!("Received PACKET {:?}", packet);
match packet {
// TODO: handle ping req from server and we should send ping response in return
VariablePacket::PingrespPacket(..) => {
debug!("Receiving PINGRESP from broker ..");
}
VariablePacket::PublishPacket(ref publ) => {
let mut message = Message::new(publ.payload().to_vec());
trace!("PUBLISH ({}): {:?}", publ.topic_name(), message);
#[cfg(feature = "c2d-messages")]
if publ.topic_name().starts_with(&cloned_self.rx_topic_prefix) {
// C2D Message
let properties = publ
.topic_name()
.trim_start_matches(&cloned_self.rx_topic_prefix);
let property_tuples =
serde_urlencoded::from_str::<Vec<(String, String)>>(properties)
.unwrap();
for (key, value) in property_tuples {
// We have properties after the topic path
if let Some(system_property_key) = key.strip_prefix("$.") {
message
.system_properties
.insert(system_property_key.to_string(), value);
} else {
message.properties.insert(key, value);
}
}
if handler_tx
.send(MessageType::C2DMessage(message))
.await
.is_err()
{
break;
}
continue;
}
#[cfg(feature = "twin-properties")]
if publ.topic_name().starts_with(TWIN_PATCH_TOPIC_PREFIX) {
// Twin update
if handler_tx
.send(MessageType::DesiredPropertyUpdate(message))
.await
.is_err()
{
break;
}
continue;
}
#[cfg(feature = "direct-methods")]
if publ.topic_name().starts_with(METHOD_POST_TOPIC_PREFIX) {
// Direct method invocation
// Sent to topic in format $iothub/methods/POST/{method name}/?$rid={request id}
// Strip the prefix from the topic left with {method name}/$rid={request id}
let details = &publ.topic_name()[METHOD_POST_TOPIC_PREFIX.len()..];
let method_components: Vec<_> = details.split('/').collect();
let request_id =
method_components[1][REQUEST_ID_PARAM.len()..].to_string();
if handler_tx
.send(MessageType::DirectMethod(DirectMethodInvocation {
method_name: method_components[0].to_string(),
message,
request_id,
}))
.await
.is_err()
{
break;
}
continue;
}
}
_ => {}
}
}
// If mpsc::Sender::send fails, it'll break the loop
// From the docs, the send operation can only fail if the receiving ennd of a channel is disconnected
// If the receiver has been dropped, stop receiving loop and send MQTT unsubscribe
cloned_self.unsubscribe().await;
});
self.subscribe().await;
// Send empty message so hub will respond with device twin data
#[cfg(feature = "twin-properties")]
self.request_twin_properties("0").await.unwrap();
// let (abort_handle, abort_registration) = AbortHandle::new_pair();
// let _ = Abortable::new(handle, abort_registration);
// self.rx_loop_handle = Some(abort_handle);
handler_rx
}
}
#[cfg(any(
feature = "direct-methods",
feature = "c2d-messages",
feature = "twin-properties",
))]
impl MqttTransport {
async fn subscribe(&mut self) {
let topics = vec![
#[cfg(feature = "direct-methods")]
(
TopicFilter::new(METHOD_POST_TOPIC_FILTER).unwrap(),
QualityOfService::Level0,
),
#[cfg(feature = "c2d-messages")]
(
TopicFilter::new(device_bound_messages_topic_filter(&self.device_id)).unwrap(),
QualityOfService::Level0,
),
#[cfg(feature = "twin-properties")]
(
TopicFilter::new(TWIN_RESPONSE_TOPIC_FILTER).unwrap(),
QualityOfService::Level0,
),
#[cfg(feature = "twin-properties")]
(
TopicFilter::new(TWIN_PATCH_TOPIC_FILTER).unwrap(),
QualityOfService::Level0,
),
];
trace!("Subscribing to {:?}", topics);
let subscribe_packet = SubscribePacket::new(10, topics);
let mut buf = Vec::new();
subscribe_packet.encode(&mut buf).unwrap();
self.write_socket
.lock()
.await
.write_all(&buf[..])
.await
.unwrap();
}
async fn unsubscribe(&mut self) {
let topics = vec![
#[cfg(feature = "direct-methods")]
TopicFilter::new(METHOD_POST_TOPIC_FILTER).unwrap(),
#[cfg(feature = "c2d-messages")]
TopicFilter::new(device_bound_messages_topic_filter(&self.device_id)).unwrap(),
#[cfg(feature = "twin-properties")]
TopicFilter::new(TWIN_RESPONSE_TOPIC_FILTER).unwrap(),
#[cfg(feature = "twin-properties")]
TopicFilter::new(TWIN_PATCH_TOPIC_FILTER).unwrap(),
];
trace!("Unsubscribing to {:?}", topics);
let unsubscribe_packet = UnsubscribePacket::new(10, topics);
let mut buf = Vec::new();
unsubscribe_packet.encode(&mut buf).unwrap();
// If the connection is lost, do not unwrap.
let _ = self.write_socket.lock().await.write_all(&buf[..]).await;
}
}
fn build_topic_name(
base_topic: &TopicName,
message: &Message,
) -> Result<TopicName, TopicNameError> {
let capacity = message.system_properties.len() + message.properties.len();
let mut props = std::collections::HashMap::with_capacity(capacity);
props.extend(message.system_properties.iter());
props.extend(message.properties.iter());
// if we reuse the base_topic string as the target for the serializer,
// we end up with an extra ampersand before the key/value pairs
let encoded = form_urlencoded::Serializer::new(String::new())
.extend_pairs(props.iter())
.finish();
TopicName::new(format!("{}{}", base_topic.to_string(), encoded))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Message;
#[test]
fn content_type_is_appended_to_topic_name() {
let message = Message::builder()
.set_body(vec![])
.set_content_type("application/json".to_owned())
.build();
let base_topic = TopicName::new("topic/").unwrap();
let topic_with_properties = build_topic_name(&base_topic, &message).unwrap().to_string();
assert_eq!("topic/%24.ct=application%2Fjson", topic_with_properties);
}
#[test]
fn content_encoding_is_appended_to_topic_name() {
let message = Message::builder()
.set_body(vec![])
.set_content_encoding("utf-8".to_owned())
.build();
let base_topic = TopicName::new("topic/").unwrap();
let topic_with_properties = build_topic_name(&base_topic, &message).unwrap().to_string();
assert_eq!("topic/%24.ce=utf-8", topic_with_properties);
}
#[test]
fn message_id_is_appended_to_topic_name() {
let message = Message::builder()
.set_body(vec![])
.set_message_id("id".to_owned())
.build();
let base_topic = TopicName::new("topic/").unwrap();
let topic_with_properties = build_topic_name(&base_topic, &message).unwrap().to_string();
assert_eq!("topic/%24.mid=id", topic_with_properties);
}
#[test]
fn no_system_properties() {
let message = Message::new(vec![]);
let base_topic = TopicName::new("topic/").unwrap();
let actual = build_topic_name(&base_topic, &message).unwrap();
assert_eq!(base_topic, actual);
}
#[test]
fn app_properties_are_appended_to_topic_name() {
let message = Message::builder()
.set_body(vec![])
.add_message_property("foo".to_owned(), "bar".to_owned())
.build();
let base_topic = TopicName::new("topic/").unwrap();
let topic_with_properties = build_topic_name(&base_topic, &message).unwrap().to_string();
assert_eq!("topic/foo=bar", topic_with_properties);
}
}
| 35.300158 | 236 | 0.548713 |
e58a3768c77ba9ab9af3826622323ff8c0f0a901 | 4,222 | use std::{collections::BTreeMap, path::PathBuf};
use acvm::acir::native_types::Witness;
use acvm::PartialWitnessGenerator;
use acvm::ProofSystemCompiler;
use clap::ArgMatches;
use noir_field::FieldElement;
use noirc_abi::{input_parser::InputValue, Abi};
use crate::{errors::CliError, resolver::Resolver};
use super::{create_dir, write_to_file, PROOFS_DIR, PROOF_EXT, PROVER_INPUT_FILE};
pub(crate) fn run(args: ArgMatches) -> Result<(), CliError> {
let proof_name = args
.subcommand_matches("prove")
.unwrap()
.value_of("proof_name")
.unwrap();
prove(proof_name)
}
/// In Barretenberg, the proof system adds a zero witness in the first index,
/// So when we add witness values, their index start from 1.
const WITNESS_OFFSET: u32 = 1;
fn prove(proof_name: &str) -> Result<(), CliError> {
let curr_dir = std::env::current_dir().unwrap();
let driver = Resolver::resolve_root_config(&curr_dir)?;
let compiled_program = driver.into_compiled_program();
// Parse the initial witness values
let curr_dir = std::env::current_dir().unwrap();
let witness_map = noirc_abi::input_parser::Format::Toml.parse(curr_dir, PROVER_INPUT_FILE);
// Check that enough witness values were supplied
let num_params = compiled_program.abi.as_ref().unwrap().num_parameters();
if num_params != witness_map.len() {
panic!(
"Expected {} number of values, but got {} number of values",
num_params,
witness_map.len()
)
}
let abi = compiled_program.abi.unwrap();
let mut solved_witness = process_abi_with_input(abi, witness_map)?;
let backend = acvm::ConcreteBackend;
let solver_res = backend.solve(&mut solved_witness, compiled_program.circuit.gates.clone());
if let Err(opcode) = solver_res {
return Err(CliError::Generic(format!(
"backend does not currently support the {} opcode. ACVM does not currently fall back to arithmetic gates.",
opcode
)));
}
let backend = acvm::ConcreteBackend;
let proof = backend.prove_with_meta(compiled_program.circuit, solved_witness);
let mut proof_path = create_proof_dir();
proof_path.push(proof_name);
proof_path.set_extension(PROOF_EXT);
println!("proof : {}", hex::encode(&proof));
let path = write_to_file(hex::encode(&proof).as_bytes(), &proof_path);
println!("Proof successfully created and located at {}", path);
Ok(())
}
fn create_proof_dir() -> PathBuf {
create_dir(PROOFS_DIR).expect("could not create the `contract` directory")
}
/// Ordering is important here, which is why we need the ABI to tell us what order to add the elements in
/// We then need the witness map to get the elements field values.
fn process_abi_with_input(
abi: Abi,
witness_map: BTreeMap<String, InputValue>,
) -> Result<BTreeMap<Witness, FieldElement>, CliError> {
let mut solved_witness = BTreeMap::new();
let mut index = 0;
for (param_name, param_type) in abi.parameters.into_iter() {
let value = witness_map
.get(¶m_name)
.unwrap_or_else(|| {
panic!(
"ABI expects the parameter `{}`, but this was not found",
param_name
)
})
.clone();
if !value.matches_abi(param_type) {
return Err(CliError::Generic(format!("The parameters in the main do not match the parameters in the {}.toml file. \n Please check `{}` parameter ", PROVER_INPUT_FILE,param_name)));
}
match value {
InputValue::Field(element) => {
let old_value =
solved_witness.insert(Witness::new(index + WITNESS_OFFSET), element);
assert!(old_value.is_none());
index += 1;
}
InputValue::Vec(arr) => {
for element in arr {
let old_value =
solved_witness.insert(Witness::new(index + WITNESS_OFFSET), element);
assert!(old_value.is_none());
index += 1;
}
}
}
}
Ok(solved_witness)
}
| 34.606557 | 192 | 0.626717 |
11420ee6cee5d1c7ffb8e6639b6b5a9456718030 | 4,393 | use ring::digest::{Algorithm, Digest};
use hashutils::{HashUtils, Hashable};
pub use proof::{Lemma, Positioned, Proof};
use serde::{Serialize, Deserialize};
/// Binary Tree where leaves hold a stand-alone value.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum Tree<T> {
Empty {
hash: Vec<u8>,
},
Leaf {
hash: Vec<u8>,
value: T,
},
Node {
hash: Vec<u8>,
left: Box<Tree<T>>,
right: Box<Tree<T>>,
},
}
impl<T> Tree<T> {
/// Create an empty tree
pub fn empty(hash: Digest) -> Self {
Tree::Empty {
hash: hash.as_ref().into(),
}
}
/// Create a new tree
pub fn new(hash: Digest, value: T) -> Self {
Tree::Leaf {
hash: hash.as_ref().into(),
value,
}
}
/// Create a new leaf
pub fn new_leaf(algo: &'static Algorithm, value: T) -> Tree<T>
where
T: Hashable,
{
let hash = algo.hash_leaf(&value);
Tree::new(hash, value)
}
/// Returns a hash from the tree.
pub fn hash(&self) -> &Vec<u8> {
match *self {
Tree::Empty { ref hash } => hash,
Tree::Leaf { ref hash, .. } => hash,
Tree::Node { ref hash, .. } => hash,
}
}
/// Returns a borrowing iterator over the leaves of the tree.
pub fn iter(&self) -> LeavesIterator<T> {
LeavesIterator::new(self)
}
}
/// An borrowing iterator over the leaves of a `Tree`.
/// Adapted from http://codereview.stackexchange.com/q/110283.
#[allow(missing_debug_implementations)]
pub struct LeavesIterator<'a, T>
where
T: 'a,
{
current_value: Option<&'a T>,
right_nodes: Vec<&'a Tree<T>>,
}
impl<'a, T> LeavesIterator<'a, T> {
fn new(root: &'a Tree<T>) -> Self {
let mut iter = LeavesIterator {
current_value: None,
right_nodes: Vec::new(),
};
iter.add_left(root);
iter
}
fn add_left(&mut self, mut tree: &'a Tree<T>) {
loop {
match *tree {
Tree::Empty { .. } => {
self.current_value = None;
break;
}
Tree::Node {
ref left,
ref right,
..
} => {
self.right_nodes.push(right);
tree = left;
}
Tree::Leaf { ref value, .. } => {
self.current_value = Some(value);
break;
}
}
}
}
}
impl<'a, T> Iterator for LeavesIterator<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<&'a T> {
let result = self.current_value.take();
if let Some(rest) = self.right_nodes.pop() {
self.add_left(rest);
}
result
}
}
/// An iterator over the leaves of a `Tree`.
#[allow(missing_debug_implementations)]
pub struct LeavesIntoIterator<T> {
current_value: Option<T>,
right_nodes: Vec<Tree<T>>,
}
impl<T> LeavesIntoIterator<T> {
fn new(root: Tree<T>) -> Self {
let mut iter = LeavesIntoIterator {
current_value: None,
right_nodes: Vec::new(),
};
iter.add_left(root);
iter
}
fn add_left(&mut self, mut tree: Tree<T>) {
loop {
match tree {
Tree::Empty { .. } => {
self.current_value = None;
break;
}
Tree::Node { left, right, .. } => {
self.right_nodes.push(*right);
tree = *left;
}
Tree::Leaf { value, .. } => {
self.current_value = Some(value);
break;
}
}
}
}
}
impl<T> Iterator for LeavesIntoIterator<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
let result = self.current_value.take();
if let Some(rest) = self.right_nodes.pop() {
self.add_left(rest);
}
result
}
}
impl<T> IntoIterator for Tree<T> {
type Item = T;
type IntoIter = LeavesIntoIterator<T>;
fn into_iter(self) -> Self::IntoIter {
LeavesIntoIterator::new(self)
}
}
| 22.528205 | 85 | 0.478033 |
33ce9bc78117a1a2322d043c5948831d802f1cc7 | 8,806 | use rusqlite::{params, Connection, Error, Result};
use serde::Serialize;
#[derive(Clone, Debug, Serialize)]
pub struct Device {
pub id: i64,
pub name: String,
pub group_id: i32,
pub current_state: bool,
pub references: String,
}
#[derive(Default, Clone)]
pub struct Repo<'a> {
connection_string: &'a str,
}
impl Device {
pub fn new(name: &str, group_id: i32, current_state: bool) -> Device {
Device {
id: 0,
name: String::from(name),
group_id,
current_state,
references: String::new(),
}
}
}
impl Repo<'_> {
pub fn new(connection_string: &str) -> Repo {
Repo { connection_string }
}
pub fn assure_created(&self) -> Result<bool> {
let conn = Connection::open(&self.connection_string)?;
let mut statement =
conn.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='devices'")?;
match statement.exists([]) {
Ok(x) => {
if x {
return Ok(true);
}
}
Err(err) => return Err(err),
}
println!("Table not existing, creating");
match conn.execute(
"
CREATE TABLE devices (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(100) NOT NULL,
group_id INTEGER NOT NULL,
current_state BIT NOT NULL DEFAULT 0
);
CREATE TABLE device_ref_device (
id integer primary key AUTOINCREMENT,
device_id integer REFERENCES devices(id) not null,
reference_device_id integer references devices(id) not null
);
",
params![],
) {
Ok(_) => Ok(true),
Err(err) => Err(err),
}
}
pub fn get_devices(&self) -> Result<Vec<Device>> {
let conn = Connection::open(&self.connection_string)?;
let mut statement = conn.prepare(
"select id, name, group_id, current_state, coalesce(reftable.[references],'') from devices as d
left outer join (select group_concat(reference_device_id) as [references], device_id
from device_ref_device group by device_id) as reftable on d.id = reftable.device_id",
)?;
let mut result: Vec<Device> = vec![];
let device_iter = statement.query_map([], |row| {
Ok(Device {
id: row.get(0)?,
name: row.get(1)?,
group_id: row.get(2)?,
current_state: row.get(3)?,
references: row.get(4)?,
})
})?;
device_iter.for_each(|d| result.push(d.unwrap()));
Ok(result)
}
pub fn get_device(&self, id: i64) -> Result<Option<Device>> {
let conn = Connection::open(&self.connection_string)?;
return match conn.query_row(
"SELECT id, name, group_id, current_state, coalesce((select group_concat(reference_device_id)
from device_ref_device where device_id=?1),'') as [references] FROM devices WHERE id = ?1",
params![id],
|row| {
Ok(Device {
id: row.get(0)?,
name: row.get(1)?,
group_id: row.get(2)?,
current_state: row.get(3)?,
references: row.get(4)?,
})
},
) {
Ok(x) => Ok(Some(x)),
Err(Error::QueryReturnedNoRows) => Ok(None),
Err(err) => {
log::error!("Error: {}", err);
println!("err: {}", err);
return Err(err);
}
};
}
pub fn get_group(&self, group_id: i32) -> Result<Vec<Device>> {
let conn = Connection::open(&self.connection_string)?;
let mut statement = conn
.prepare("select id, name, group_id, current_state, coalesce(reftable.[references],'') from devices as d
left outer join (select group_concat(reference_device_id) as [references], device_id
from device_ref_device group by device_id) as reftable on d.id = reftable.device_id WHERE group_id = ?1")?;
let device_iter = statement.query_map(params![group_id], |row| {
Ok(Device {
id: row.get(0)?,
name: row.get(1)?,
group_id: row.get(2)?,
current_state: row.get(3)?,
references: row.get(4)?,
})
})?;
let mut result: Vec<Device> = vec![];
for device in device_iter {
result.push(device.unwrap());
}
Ok(result)
}
pub fn add_device(&self, device: &mut Device) -> Result<bool> {
let conn = Connection::open(&self.connection_string)?;
let mut statement = conn.prepare("INSERT INTO devices(name, group_id) VALUES(?1, ?2);")?;
match statement.insert(params![device.name, device.group_id]) {
Ok(id) => {
device.id = id;
Ok(true)
}
Err(err) => {
println!("insert err: {}", err);
Err(err)
}
}
}
pub fn update_device(&self, device: &Device) -> Result<bool> {
let conn = Connection::open(&self.connection_string)?;
let mut statement =
conn.prepare("UPDATE devices SET current_state = ?1 WHERE id in (select reference_device_id from device_ref_device where device_id=?2) or id = ?2")?;
match statement.execute(params![device.current_state, device.id]) {
Ok(_) => Ok(true),
Err(err) => Err(err),
}
}
pub fn update_devices(&self, devices: &[Device]) -> Result<bool> {
let conn = Connection::open(&self.connection_string)?;
let mut statement = conn.prepare("UPDATE devices set current_state=?1 where id=?2")?;
for device in devices.iter() {
match statement.execute(params![device.current_state, device.id]) {
Ok(_) => {}
Err(err) => return Err(err),
}
}
Ok(true)
}
}
#[test]
fn test_device_empty_database() {
let repo = Repo::new("test.db");
repo.assure_created().unwrap();
let device = repo.get_device(2);
assert!(device.is_ok());
assert!(device.unwrap().is_none());
std::fs::remove_file("test.db").unwrap();
}
#[test]
fn test_non_existing_database() {
let repo = Repo::new("test.db");
let created = repo.assure_created();
let created2 = repo.assure_created();
assert!(created.is_ok());
assert!(created2.is_ok());
assert!(created.unwrap() == true);
assert!(created2.unwrap() == true);
std::fs::remove_file("test.db").unwrap();
}
#[test]
fn test_insert_device() {
let mut device = Device::new("test", 1, false);
let repo = Repo::new("test.db");
repo.assure_created().unwrap();
let inserted = repo.add_device(&mut device);
assert!(inserted.is_ok());
assert!(device.id != 0);
assert!(device.name == "test");
assert!(device.group_id == 1);
let get_result = repo.get_device(device.id);
assert!(get_result.is_ok());
let inserted_device = get_result.unwrap();
assert!(inserted_device.is_some());
let get_group = repo.get_group(device.group_id);
assert!(get_group.is_ok());
let group = get_group.unwrap();
assert!(1 == group.len());
std::fs::remove_file("test.db").unwrap();
}
#[test]
fn test_update_device() {
let mut device = Device::new("test", 1, false);
let repo = Repo::new("test.db");
repo.assure_created().unwrap();
let inserted = repo.add_device(&mut device);
assert!(inserted.is_ok());
device.current_state = true;
let update_result = repo.update_device(&device);
assert!(update_result.is_ok());
let updated = repo.get_device(device.id);
let updated_device = updated.unwrap().unwrap();
assert!(true == updated_device.current_state);
std::fs::remove_file("test.db").unwrap();
}
#[test]
fn test_get_devices() {
let mut device1 = Device::new("test1", 1, false);
let mut device2 = Device::new("test2", 1, false);
let repo = Repo::new("test.db");
repo.assure_created().unwrap();
assert!(repo.add_device(&mut device1).is_ok());
assert!(repo.add_device(&mut device2).is_ok());
let devices = repo.get_devices().unwrap();
assert!(2 == devices.len());
}
#[test]
fn test_get_devices_in_group() {
let mut device1 = Device::new("test1", 1, false);
let mut device2 = Device::new("test2", 2, false);
let repo = Repo::new("test.db");
repo.assure_created().unwrap();
assert!(repo.add_device(&mut device1).is_ok());
assert!(repo.add_device(&mut device2).is_ok());
let group_devices = repo.get_group(1).unwrap();
assert!(1 == group_devices.len())
}
| 28.590909 | 161 | 0.565751 |
6a31a3dae4b3e56fa082104ebdf6f19c76dc3d97 | 356 | use aoc::Result;
use aoc_2015_day_11::*;
#[test]
fn part_one_answer() -> Result<()> {
let input = include_str!("../input/input.txt");
assert_eq!(part_one(input)?, "hxbxxyzz");
Ok(())
}
#[test]
fn part_two_answer() -> Result<()> {
let input = include_str!("../input/input.txt");
assert_eq!(part_two(input)?, "hxcaabcc");
Ok(())
}
| 19.777778 | 51 | 0.595506 |
5d3f435a79d05587d239a205cd6559f5ae9a0c3c | 134 | pub fn take<T>(mut vec: Vec<T>) -> Option<T> {
if !vec.is_empty() {
Some(vec.remove(0))
} else {
None
}
}
| 16.75 | 46 | 0.462687 |
1d19d0da04bfc9299f4685b423a5dc137cd19226 | 186 | // Copyright (c) 2018-2022 The MobileCoin Foundation
//! Testing helpers
#![deny(missing_docs)]
mod config;
mod server;
mod service;
pub use crate::{config::Config, server::Server};
| 15.5 | 52 | 0.72043 |
5da3029d38039b928d23102a30c90f9be54a717d | 1,636 | //! Executable for assembling SAILAR assembly files
/// SAILAR bytecode assembler
#[derive(Debug, clap::Parser)]
#[clap(version, about)]
struct Arguments {
/// Path to the SAILAR assembly file
#[clap(long, short)]
input: std::path::PathBuf,
/// Path to the file containing the assembled SAILAR binary module.
#[clap(long, short)]
output: Option<std::path::PathBuf>,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let arguments: Arguments = clap::Parser::parse();
let input = std::fs::read_to_string(&arguments.input)?;
let mut tree = None;
match sailasm::assemble(&input, &mut tree) {
Ok(module) => {
let default_output;
let output = if let Some(path) = &arguments.output {
path
} else {
default_output = arguments.input.with_extension("sail");
&default_output
};
module.write_to(std::fs::File::create(output)?).map_err(Box::from)
}
Err(errors) => {
use std::io::Write as _;
let output = std::io::stderr();
let output_handle = output.lock();
let mut buffered_output = std::io::BufWriter::new(output_handle);
for e in errors.iter() {
write!(buffered_output, "error")?;
if let Some(location) = e.location() {
write!(buffered_output, "{}", location)?;
}
writeln!(buffered_output, ": {}", e.kind())?;
}
Err(Box::from(format!("failed with {} errors", errors.len())))
}
}
}
| 32.078431 | 78 | 0.541565 |
b957ca87ebed56f6418112da9742246cb93fe78f | 5,780 | // automatically generated by the FlatBuffers compiler, do not modify
use crate::include_test1_generated::*;
extern crate core;
use self::core::mem;
use self::core::cmp::Ordering;
extern crate flatbuffers;
use self::flatbuffers::EndianScalar;
#[allow(unused_imports, dead_code)]
pub mod my_game {
use crate::include_test1_generated::*;
extern crate core;
use self::core::mem;
use self::core::cmp::Ordering;
extern crate flatbuffers;
use self::flatbuffers::EndianScalar;
#[allow(unused_imports, dead_code)]
pub mod other_name_space {
use crate::include_test1_generated::*;
extern crate core;
use self::core::mem;
use self::core::cmp::Ordering;
extern crate flatbuffers;
use self::flatbuffers::EndianScalar;
#[allow(non_camel_case_types)]
#[repr(i64)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum FromInclude {
IncludeVal = 0,
}
pub const ENUM_MIN_FROM_INCLUDE: i64 = 0;
pub const ENUM_MAX_FROM_INCLUDE: i64 = 0;
impl<'a> flatbuffers::Follow<'a> for FromInclude {
type Inner = Self;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
flatbuffers::read_scalar_at::<Self>(buf, loc)
}
}
impl flatbuffers::EndianScalar for FromInclude {
#[inline]
fn to_little_endian(self) -> Self {
let n = i64::to_le(self as i64);
let p = &n as *const i64 as *const FromInclude;
unsafe { *p }
}
#[inline]
fn from_little_endian(self) -> Self {
let n = i64::from_le(self as i64);
let p = &n as *const i64 as *const FromInclude;
unsafe { *p }
}
}
impl flatbuffers::Push for FromInclude {
type Output = FromInclude;
#[inline]
fn push(&self, dst: &mut [u8], _rest: &[u8]) {
flatbuffers::emplace_scalar::<FromInclude>(dst, *self);
}
}
#[allow(non_camel_case_types)]
pub const ENUM_VALUES_FROM_INCLUDE: [FromInclude; 1] = [
FromInclude::IncludeVal
];
#[allow(non_camel_case_types)]
pub const ENUM_NAMES_FROM_INCLUDE: [&str; 1] = [
"IncludeVal"
];
pub fn enum_name_from_include(e: FromInclude) -> &'static str {
let index = e as i64;
ENUM_NAMES_FROM_INCLUDE[index as usize]
}
// struct Unused, aligned to 4
#[repr(C, align(4))]
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Unused {
a_: i32,
} // pub struct Unused
impl flatbuffers::SafeSliceAccess for Unused {}
impl<'a> flatbuffers::Follow<'a> for Unused {
type Inner = &'a Unused;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
<&'a Unused>::follow(buf, loc)
}
}
impl<'a> flatbuffers::Follow<'a> for &'a Unused {
type Inner = &'a Unused;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
flatbuffers::follow_cast_ref::<Unused>(buf, loc)
}
}
impl<'b> flatbuffers::Push for Unused {
type Output = Unused;
#[inline]
fn push(&self, dst: &mut [u8], _rest: &[u8]) {
let src = unsafe {
self::core::slice::from_raw_parts(self as *const Unused as *const u8, Self::size())
};
dst.copy_from_slice(src);
}
}
impl<'b> flatbuffers::Push for &'b Unused {
type Output = Unused;
#[inline]
fn push(&self, dst: &mut [u8], _rest: &[u8]) {
let src = unsafe {
self::core::slice::from_raw_parts(*self as *const Unused as *const u8, Self::size())
};
dst.copy_from_slice(src);
}
}
impl Unused {
pub fn new(_a: i32) -> Self {
Unused {
a_: _a.to_little_endian(),
}
}
pub fn a(&self) -> i32 {
self.a_.from_little_endian()
}
}
pub enum TableBOffset {}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct TableB<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for TableB<'a> {
type Inner = TableB<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self { _tab: flatbuffers::Table { buf, loc } }
}
}
impl<'a> TableB<'a> {
#[inline]
pub fn init_from_table(table: flatbuffers::Table<'a>) -> Self {
TableB {
_tab: table,
}
}
#[allow(unused_mut)]
pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, S: flatbuffers::FlatBufferBuilderStorage>(
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, S>,
args: &'args TableBArgs<'args>) -> flatbuffers::WIPOffset<TableB<'bldr>> {
let mut builder = TableBBuilder::new(_fbb);
if let Some(x) = args.a { builder.add_a(x); }
builder.finish()
}
pub const VT_A: flatbuffers::VOffsetT = 4;
#[inline]
pub fn a(&self) -> Option<super::super::TableA<'a>> {
self._tab.get::<flatbuffers::ForwardsUOffset<super::super::TableA<'a>>>(TableB::VT_A, None)
}
}
pub struct TableBArgs<'a> {
pub a: Option<flatbuffers::WIPOffset<super::super::TableA<'a>>>,
}
impl<'a> Default for TableBArgs<'a> {
#[inline]
fn default() -> Self {
TableBArgs {
a: None,
}
}
}
pub struct TableBBuilder<'a: 'b, 'b, S: flatbuffers::FlatBufferBuilderStorage> {
fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, S>,
start_: flatbuffers::WIPOffset<flatbuffers::TableUnfinishedWIPOffset>,
}
impl<'a: 'b, 'b, S: flatbuffers::FlatBufferBuilderStorage> TableBBuilder<'a, 'b, S> {
#[inline]
pub fn add_a(&mut self, a: flatbuffers::WIPOffset<super::super::TableA<'b >>) {
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<super::super::TableA>>(TableB::VT_A, a);
}
#[inline]
pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, S>) -> Self {
let start = _fbb.start_table();
TableBBuilder {
fbb_: _fbb,
start_: start,
}
}
#[inline]
pub fn finish(self) -> flatbuffers::WIPOffset<TableB<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
} // pub mod OtherNameSpace
} // pub mod MyGame
| 25.462555 | 103 | 0.635467 |
fb505953b4f61a6f6cecc18f5c9bffeb1396696b | 281 | use cosmwasm_std::StdError;
use thiserror::Error;
/// ## Description
/// This enum describes collector contract errors.
#[derive(Error, Debug, PartialEq)]
pub enum ContractError {
#[error("{0}")]
Std(#[from] StdError),
#[error("Unauthorized")]
Unauthorized {},
}
| 20.071429 | 50 | 0.661922 |
188e9e2582f06f40cb74f8753ba51398e2e678af | 3,763 | // Copyright 2021. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use crate::{error::CollectiblesError, storage::StorageError};
use diesel::result::Error;
use prost::{DecodeError, EncodeError};
use serde::{Deserialize, Serialize};
use tari_utilities::hex::HexError;
#[derive(Serialize, Deserialize)]
#[serde(tag = "status")]
pub enum Status {
BadRequest {
code: u16,
message: String,
},
Unauthorized {
code: u16,
message: String,
},
NotFound {
code: u16,
message: String,
entity: String,
},
Internal {
code: u16,
message: String,
},
}
impl Status {
pub fn unauthorized() -> Self {
Self::Unauthorized {
code: 401,
message: "Unauthorized".to_string(),
}
}
pub fn internal(message: String) -> Self {
Self::Internal { code: 500, message }
}
pub fn not_found(entity: String) -> Self {
Self::NotFound {
code: 404,
message: format!("{} not found", &entity),
entity,
}
}
}
impl From<StorageError> for Status {
fn from(source: StorageError) -> Self {
match source {
StorageError::DieselError { source } => match source {
Error::NotFound => Self::NotFound {
code: 404,
message: format!("Not found: {}", source),
entity: "Unknown".to_string(),
},
_ => Self::Internal {
code: 502,
message: format!("Internal diesel storage error: {}", source),
},
},
_ => Self::Internal {
code: 501,
message: format!("Internal storage error: {}", source),
},
}
}
}
impl From<HexError> for Status {
fn from(he: HexError) -> Self {
Self::BadRequest {
code: 400,
message: format!("Bad request: {}", he),
}
}
}
impl From<DecodeError> for Status {
fn from(de: DecodeError) -> Self {
Self::Internal {
code: 502,
message: format!("Could not decode data: {}", de),
}
}
}
impl From<EncodeError> for Status {
fn from(e: EncodeError) -> Self {
Self::Internal {
code: 503,
message: format!("Could not encode data: {}", e),
}
}
}
impl From<CollectiblesError> for Status {
fn from(ce: CollectiblesError) -> Self {
Self::Internal {
code: 504,
message: format!("Error: {}", ce),
}
}
}
| 29.398438 | 119 | 0.655062 |
2610d97265aca937718dcf61c4c60d62c814730e | 6,796 | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {fuchsia_zircon as zx, std::collections::HashMap, std::ffi::c_void};
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy, Clone, Default)]
#[repr(C)]
pub struct EventId(u64);
#[cfg(test)]
impl From<u64> for EventId {
fn from(id: u64) -> Self {
Self(id)
}
}
/// A scheduler to schedule and cancel timeouts.
#[repr(C)]
pub struct Scheduler {
cookie: *mut c_void,
/// Returns the current system time in nano seconds.
now: extern "C" fn(cookie: *mut c_void) -> i64,
/// Requests to schedule an event. Returns a a unique ID used to cancel the scheduled event.
schedule: extern "C" fn(cookie: *mut c_void, deadline: i64) -> EventId,
/// Cancels a previously scheduled event.
cancel: extern "C" fn(cookie: *mut c_void, id: EventId),
}
/// A timer to schedule and cancel timeouts and retrieve triggered events.
pub struct Timer<E> {
events: HashMap<EventId, E>,
scheduler: Scheduler,
}
impl<E> Timer<E> {
pub fn triggered(&mut self, event_id: &EventId) -> Option<E> {
self.events.remove(event_id)
}
}
impl<E> Timer<E> {
pub fn new(scheduler: Scheduler) -> Self {
Self { events: HashMap::default(), scheduler }
}
pub fn now(&self) -> zx::Time {
let nanos = (self.scheduler.now)(self.scheduler.cookie);
zx::Time::from_nanos(nanos)
}
pub fn schedule_event(&mut self, deadline: zx::Time, event: E) -> EventId {
let event_id = (self.scheduler.schedule)(self.scheduler.cookie, deadline.into_nanos());
self.events.insert(event_id, event);
event_id
}
pub fn cancel_event(&mut self, event_id: EventId) {
if let Some(_) = self.events.remove(&event_id) {
(self.scheduler.cancel)(self.scheduler.cookie, event_id);
}
}
pub fn cancel_all(&mut self) {
for (event_id, _event) in &self.events {
(self.scheduler.cancel)(self.scheduler.cookie, *event_id);
}
self.events.clear();
}
#[cfg(test)]
pub fn scheduled_event_count(&self) -> usize {
self.events.len()
}
}
#[cfg(test)]
pub struct FakeScheduler {
pub next_id: u64,
pub deadlines: HashMap<EventId, i64>,
now: i64,
}
#[cfg(test)]
impl FakeScheduler {
pub extern "C" fn schedule(cookie: *mut c_void, deadline: i64) -> EventId {
let scheduler = unsafe { &mut *(cookie as *mut Self) };
scheduler.next_id += 1;
let event_id = EventId(scheduler.next_id);
scheduler.deadlines.insert(event_id, deadline);
event_id
}
pub extern "C" fn cancel(cookie: *mut c_void, id: EventId) {
let scheduler = unsafe { &mut *(cookie as *mut Self) };
scheduler.deadlines.remove(&id);
}
pub extern "C" fn now(cookie: *mut c_void) -> i64 {
unsafe { (*(cookie as *mut Self)).now }
}
pub fn new() -> Self {
Self { next_id: 0, deadlines: HashMap::new(), now: 0 }
}
pub fn set_time(&mut self, time: zx::Time) {
self.now = time.into_nanos();
}
pub fn increment_time(&mut self, duration: zx::Duration) {
self.set_time(zx::Time::from_nanos(self.now) + duration);
}
/// Evict and return ID and deadline of the earliest scheduled event
pub fn next_event(&mut self) -> Option<(EventId, i64)> {
let event =
self.deadlines.iter().min_by_key(|(_, deadline)| *deadline).map(|(id, d)| (*id, *d));
if let Some((id, _)) = event {
self.deadlines.remove(&id);
}
event
}
pub fn as_scheduler(&mut self) -> Scheduler {
Scheduler {
cookie: self as *mut Self as *mut c_void,
now: Self::now,
cancel: Self::cancel,
schedule: Self::schedule,
}
}
}
#[cfg(test)]
mod tests {
use {super::*, fuchsia_zircon::DurationNum};
#[derive(PartialEq, Eq, Debug, Hash)]
struct FooEvent(u8);
#[test]
fn schedule_cancel_event() {
let mut fake_scheduler = FakeScheduler::new();
let scheduler = fake_scheduler.as_scheduler();
// Verify event triggers no more than once.
let mut timer = Timer::<FooEvent>::new(scheduler);
let deadline = zx::Time::after(5_i64.nanos());
let event_id = timer.schedule_event(deadline, FooEvent(8));
assert_eq!(timer.triggered(&event_id), Some(FooEvent(8)));
assert_eq!(timer.triggered(&event_id), None);
// Verify event does not trigger if it was canceled.
let event_id = timer.schedule_event(deadline, FooEvent(9));
timer.cancel_event(event_id);
assert_eq!(timer.triggered(&event_id), None);
// Verify multiple events can be scheduled and canceled.
let event_id_1 = timer.schedule_event(deadline, FooEvent(8));
let event_id_2 = timer.schedule_event(deadline, FooEvent(9));
let event_id_3 = timer.schedule_event(deadline, FooEvent(10));
timer.cancel_event(event_id_2);
assert_eq!(timer.triggered(&event_id_2), None);
assert_eq!(timer.triggered(&event_id_3), Some(FooEvent(10)));
assert_eq!(timer.triggered(&event_id_1), Some(FooEvent(8)));
}
#[test]
fn cancel_all() {
let mut fake_scheduler = FakeScheduler::new();
let scheduler = fake_scheduler.as_scheduler();
let mut timer = Timer::<_>::new(scheduler);
let deadline = zx::Time::after(5_i64.nanos());
let event_id_1 = timer.schedule_event(deadline, 8);
let event_id_2 = timer.schedule_event(deadline, 9);
let event_id_3 = timer.schedule_event(deadline, 10);
timer.cancel_all();
assert_eq!(timer.triggered(&event_id_1), None);
assert_eq!(timer.triggered(&event_id_2), None);
assert_eq!(timer.triggered(&event_id_3), None);
}
#[test]
fn fake_scheduler_next_event() {
let mut fake_scheduler = FakeScheduler::new();
let scheduler = fake_scheduler.as_scheduler();
let event_id_1 = FakeScheduler::schedule(scheduler.cookie, 2i64);
let event_id_2 = FakeScheduler::schedule(scheduler.cookie, 4i64);
let event_id_3 = FakeScheduler::schedule(scheduler.cookie, 1i64);
let event_id_4 = FakeScheduler::schedule(scheduler.cookie, 3i64);
assert_eq!(fake_scheduler.next_event(), Some((event_id_3, 1i64)));
assert_eq!(fake_scheduler.next_event(), Some((event_id_1, 2i64)));
assert_eq!(fake_scheduler.next_event(), Some((event_id_4, 3i64)));
assert_eq!(fake_scheduler.next_event(), Some((event_id_2, 4i64)));
assert_eq!(fake_scheduler.next_event(), None);
}
}
| 33.810945 | 97 | 0.626545 |
2fd61fa90524ca5e4c053d5cb27248232ef33006 | 137,528 | use std::{
borrow::Borrow,
collections::{BTreeMap, VecDeque},
ffi,
mem,
ops::Range,
ptr,
slice,
};
use range_alloc::RangeAllocator;
use smallvec::SmallVec;
use spirv_cross::{hlsl, spirv, ErrorCode as SpirvErrorCode};
use winapi::{
shared::{
dxgi,
dxgi1_2,
dxgi1_4,
dxgiformat,
dxgitype,
minwindef::{FALSE, TRUE, UINT},
windef,
winerror,
},
um::{d3d12, d3dcompiler, synchapi, winbase, winnt},
Interface,
};
use auxil::spirv_cross_specialize_ast;
use hal::{
self,
buffer,
device as d,
format,
format::Aspects,
image,
memory,
memory::Requirements,
pass,
pool::CommandPoolCreateFlags,
pso,
pso::VertexInputRate,
query,
queue::{CommandQueue as _, QueueFamilyId},
window as w,
};
use crate::{
command as cmd,
conv,
descriptors_cpu,
pool::{CommandPool, CommandPoolAllocator},
resource as r,
root_constants,
root_constants::RootConstant,
window::{Surface, Swapchain},
Backend as B,
Device,
MemoryGroup,
MAX_VERTEX_BUFFERS,
NUM_HEAP_PROPERTIES,
QUEUE_FAMILIES,
};
use native::{PipelineStateSubobject, Subobject};
// Register space used for root constants.
const ROOT_CONSTANT_SPACE: u32 = 0;
const MEM_TYPE_MASK: u64 = 0x7;
const MEM_TYPE_SHIFT: u64 = 3;
const MEM_TYPE_UNIVERSAL_SHIFT: u64 = MEM_TYPE_SHIFT * MemoryGroup::Universal as u64;
const MEM_TYPE_BUFFER_SHIFT: u64 = MEM_TYPE_SHIFT * MemoryGroup::BufferOnly as u64;
const MEM_TYPE_IMAGE_SHIFT: u64 = MEM_TYPE_SHIFT * MemoryGroup::ImageOnly as u64;
const MEM_TYPE_TARGET_SHIFT: u64 = MEM_TYPE_SHIFT * MemoryGroup::TargetOnly as u64;
pub const IDENTITY_MAPPING: UINT = 0x1688; // D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING
/// Emit error during shader module creation. Used if we don't expect an error
/// but might panic due to an exception in SPIRV-Cross.
fn gen_unexpected_error(err: SpirvErrorCode) -> d::ShaderError {
let msg = match err {
SpirvErrorCode::CompilationError(msg) => msg,
SpirvErrorCode::Unhandled => "Unexpected error".into(),
};
d::ShaderError::CompilationFailed(msg)
}
/// Emit error during shader module creation. Used if we execute an query command.
fn gen_query_error(err: SpirvErrorCode) -> d::ShaderError {
let msg = match err {
SpirvErrorCode::CompilationError(msg) => msg,
SpirvErrorCode::Unhandled => "Unknown query error".into(),
};
d::ShaderError::CompilationFailed(msg)
}
#[derive(Clone, Debug)]
pub(crate) struct ViewInfo {
pub(crate) resource: native::Resource,
pub(crate) kind: image::Kind,
pub(crate) caps: image::ViewCapabilities,
pub(crate) view_kind: image::ViewKind,
pub(crate) format: dxgiformat::DXGI_FORMAT,
pub(crate) component_mapping: UINT,
pub(crate) range: image::SubresourceRange,
}
pub(crate) enum CommandSignature {
Draw,
DrawIndexed,
Dispatch,
}
/// Compile a single shader entry point from a HLSL text shader
pub(crate) fn compile_shader(
stage: pso::Stage,
shader_model: hlsl::ShaderModel,
entry: &str,
code: &[u8],
) -> Result<native::Blob, d::ShaderError> {
let stage_to_str = |stage, shader_model| {
let stage = match stage {
pso::Stage::Vertex => "vs",
pso::Stage::Fragment => "ps",
pso::Stage::Compute => "cs",
_ => unimplemented!(),
};
let model = match shader_model {
hlsl::ShaderModel::V5_0 => "5_0",
hlsl::ShaderModel::V5_1 => "5_1",
hlsl::ShaderModel::V6_0 => "6_0",
_ => unimplemented!(),
};
format!("{}_{}\0", stage, model)
};
let mut shader_data = native::Blob::null();
let mut error = native::Blob::null();
let entry = ffi::CString::new(entry).unwrap();
let hr = unsafe {
d3dcompiler::D3DCompile(
code.as_ptr() as *const _,
code.len(),
ptr::null(),
ptr::null(),
ptr::null_mut(),
entry.as_ptr() as *const _,
stage_to_str(stage, shader_model).as_ptr() as *const i8,
1,
0,
shader_data.mut_void() as *mut *mut _,
error.mut_void() as *mut *mut _,
)
};
if !winerror::SUCCEEDED(hr) {
error!("D3DCompile error {:x}", hr);
let message = unsafe {
let pointer = error.GetBufferPointer();
let size = error.GetBufferSize();
let slice = slice::from_raw_parts(pointer as *const u8, size as usize);
String::from_utf8_lossy(slice).into_owned()
};
unsafe {
error.destroy();
}
Err(d::ShaderError::CompilationFailed(message))
} else {
Ok(shader_data)
}
}
#[repr(C)]
struct GraphicsPipelineStateSubobjectStream {
root_signature: PipelineStateSubobject<*mut d3d12::ID3D12RootSignature>,
vs: PipelineStateSubobject<d3d12::D3D12_SHADER_BYTECODE>,
ps: PipelineStateSubobject<d3d12::D3D12_SHADER_BYTECODE>,
ds: PipelineStateSubobject<d3d12::D3D12_SHADER_BYTECODE>,
hs: PipelineStateSubobject<d3d12::D3D12_SHADER_BYTECODE>,
gs: PipelineStateSubobject<d3d12::D3D12_SHADER_BYTECODE>,
stream_output: PipelineStateSubobject<d3d12::D3D12_STREAM_OUTPUT_DESC>,
blend: PipelineStateSubobject<d3d12::D3D12_BLEND_DESC>,
sample_mask: PipelineStateSubobject<UINT>,
rasterizer: PipelineStateSubobject<d3d12::D3D12_RASTERIZER_DESC>,
depth_stencil: PipelineStateSubobject<d3d12::D3D12_DEPTH_STENCIL_DESC1>,
input_layout: PipelineStateSubobject<d3d12::D3D12_INPUT_LAYOUT_DESC>,
ib_strip_cut_value: PipelineStateSubobject<d3d12::D3D12_INDEX_BUFFER_STRIP_CUT_VALUE>,
primitive_topology: PipelineStateSubobject<d3d12::D3D12_PRIMITIVE_TOPOLOGY_TYPE>,
render_target_formats: PipelineStateSubobject<d3d12::D3D12_RT_FORMAT_ARRAY>,
depth_stencil_format: PipelineStateSubobject<dxgiformat::DXGI_FORMAT>,
sample_desc: PipelineStateSubobject<dxgitype::DXGI_SAMPLE_DESC>,
node_mask: PipelineStateSubobject<UINT>,
cached_pso: PipelineStateSubobject<d3d12::D3D12_CACHED_PIPELINE_STATE>,
flags: PipelineStateSubobject<d3d12::D3D12_PIPELINE_STATE_FLAGS>,
}
impl GraphicsPipelineStateSubobjectStream {
fn new(
pso_desc: &d3d12::D3D12_GRAPHICS_PIPELINE_STATE_DESC,
depth_bounds_test_enable: bool,
) -> Self {
GraphicsPipelineStateSubobjectStream {
root_signature: PipelineStateSubobject::new(
Subobject::RootSignature,
pso_desc.pRootSignature,
),
vs: PipelineStateSubobject::new(Subobject::VS, pso_desc.VS),
ps: PipelineStateSubobject::new(Subobject::PS, pso_desc.PS),
ds: PipelineStateSubobject::new(Subobject::DS, pso_desc.DS),
hs: PipelineStateSubobject::new(Subobject::HS, pso_desc.HS),
gs: PipelineStateSubobject::new(Subobject::GS, pso_desc.GS),
stream_output: PipelineStateSubobject::new(
Subobject::StreamOutput,
pso_desc.StreamOutput,
),
blend: PipelineStateSubobject::new(Subobject::Blend, pso_desc.BlendState),
sample_mask: PipelineStateSubobject::new(Subobject::SampleMask, pso_desc.SampleMask),
rasterizer: PipelineStateSubobject::new(
Subobject::Rasterizer,
pso_desc.RasterizerState,
),
depth_stencil: PipelineStateSubobject::new(
Subobject::DepthStencil1,
d3d12::D3D12_DEPTH_STENCIL_DESC1 {
DepthEnable: pso_desc.DepthStencilState.DepthEnable,
DepthWriteMask: pso_desc.DepthStencilState.DepthWriteMask,
DepthFunc: pso_desc.DepthStencilState.DepthFunc,
StencilEnable: pso_desc.DepthStencilState.StencilEnable,
StencilReadMask: pso_desc.DepthStencilState.StencilReadMask,
StencilWriteMask: pso_desc.DepthStencilState.StencilWriteMask,
FrontFace: pso_desc.DepthStencilState.FrontFace,
BackFace: pso_desc.DepthStencilState.BackFace,
DepthBoundsTestEnable: depth_bounds_test_enable as _,
},
),
input_layout: PipelineStateSubobject::new(Subobject::InputLayout, pso_desc.InputLayout),
ib_strip_cut_value: PipelineStateSubobject::new(
Subobject::IBStripCut,
pso_desc.IBStripCutValue,
),
primitive_topology: PipelineStateSubobject::new(
Subobject::PrimitiveTopology,
pso_desc.PrimitiveTopologyType,
),
render_target_formats: PipelineStateSubobject::new(
Subobject::RTFormats,
d3d12::D3D12_RT_FORMAT_ARRAY {
RTFormats: pso_desc.RTVFormats,
NumRenderTargets: pso_desc.NumRenderTargets,
},
),
depth_stencil_format: PipelineStateSubobject::new(
Subobject::DSFormat,
pso_desc.DSVFormat,
),
sample_desc: PipelineStateSubobject::new(Subobject::SampleDesc, pso_desc.SampleDesc),
node_mask: PipelineStateSubobject::new(Subobject::NodeMask, pso_desc.NodeMask),
cached_pso: PipelineStateSubobject::new(Subobject::CachedPSO, pso_desc.CachedPSO),
flags: PipelineStateSubobject::new(Subobject::Flags, pso_desc.Flags),
}
}
}
impl Device {
fn parse_spirv(raw_data: &[u32]) -> Result<spirv::Ast<hlsl::Target>, d::ShaderError> {
let module = spirv::Module::from_words(raw_data);
spirv::Ast::parse(&module).map_err(|err| {
let msg = match err {
SpirvErrorCode::CompilationError(msg) => msg,
SpirvErrorCode::Unhandled => "Unknown parsing error".into(),
};
d::ShaderError::CompilationFailed(msg)
})
}
fn patch_spirv_resources(
ast: &mut spirv::Ast<hlsl::Target>,
layout: &r::PipelineLayout,
) -> Result<(), d::ShaderError> {
// Move the descriptor sets away to yield for the root constants at "space0".
let space_offset = if layout.constants.is_empty() { 0 } else { 1 };
let shader_resources = ast.get_shader_resources().map_err(gen_query_error)?;
if space_offset != 0 {
for image in &shader_resources.separate_images {
let set = ast
.get_decoration(image.id, spirv::Decoration::DescriptorSet)
.map_err(gen_query_error)?;
ast.set_decoration(
image.id,
spirv::Decoration::DescriptorSet,
space_offset + set,
)
.map_err(gen_unexpected_error)?;
}
}
if space_offset != 0 {
for uniform_buffer in &shader_resources.uniform_buffers {
let set = ast
.get_decoration(uniform_buffer.id, spirv::Decoration::DescriptorSet)
.map_err(gen_query_error)?;
ast.set_decoration(
uniform_buffer.id,
spirv::Decoration::DescriptorSet,
space_offset + set,
)
.map_err(gen_unexpected_error)?;
}
}
for storage_buffer in &shader_resources.storage_buffers {
let set = ast
.get_decoration(storage_buffer.id, spirv::Decoration::DescriptorSet)
.map_err(gen_query_error)?;
let binding = ast
.get_decoration(storage_buffer.id, spirv::Decoration::Binding)
.map_err(gen_query_error)?;
if space_offset != 0 {
ast.set_decoration(
storage_buffer.id,
spirv::Decoration::DescriptorSet,
space_offset + set,
)
.map_err(gen_unexpected_error)?;
}
if !layout.elements[set as usize].mutable_bindings.contains(&binding) {
ast.set_decoration(
storage_buffer.id,
spirv::Decoration::NonWritable,
0,
)
.map_err(gen_unexpected_error)?
}
}
for image in &shader_resources.storage_images {
let set = ast
.get_decoration(image.id, spirv::Decoration::DescriptorSet)
.map_err(gen_query_error)?;
let binding = ast
.get_decoration(image.id, spirv::Decoration::Binding)
.map_err(gen_query_error)?;
if space_offset != 0 {
ast.set_decoration(
image.id,
spirv::Decoration::DescriptorSet,
space_offset + set,
)
.map_err(gen_unexpected_error)?;
}
if !layout.elements[set as usize].mutable_bindings.contains(&binding) {
ast.set_decoration(
image.id,
spirv::Decoration::NonWritable,
0,
)
.map_err(gen_unexpected_error)?
}
}
if space_offset != 0 {
for sampler in &shader_resources.separate_samplers {
let set = ast
.get_decoration(sampler.id, spirv::Decoration::DescriptorSet)
.map_err(gen_query_error)?;
ast.set_decoration(
sampler.id,
spirv::Decoration::DescriptorSet,
space_offset + set,
)
.map_err(gen_unexpected_error)?;
}
}
if space_offset != 0 {
for image in &shader_resources.sampled_images {
let set = ast
.get_decoration(image.id, spirv::Decoration::DescriptorSet)
.map_err(gen_query_error)?;
ast.set_decoration(
image.id,
spirv::Decoration::DescriptorSet,
space_offset + set,
)
.map_err(gen_unexpected_error)?;
}
}
if space_offset != 0 {
for input in &shader_resources.subpass_inputs {
let set = ast
.get_decoration(input.id, spirv::Decoration::DescriptorSet)
.map_err(gen_query_error)?;
ast.set_decoration(
input.id,
spirv::Decoration::DescriptorSet,
space_offset + set,
)
.map_err(gen_unexpected_error)?;
}
}
Ok(())
}
fn translate_spirv(
ast: &mut spirv::Ast<hlsl::Target>,
shader_model: hlsl::ShaderModel,
layout: &r::PipelineLayout,
stage: pso::Stage,
features: &hal::Features,
) -> Result<String, d::ShaderError> {
let mut compile_options = hlsl::CompilerOptions::default();
compile_options.shader_model = shader_model;
compile_options.vertex.invert_y = !features.contains(hal::Features::NDC_Y_UP);
let stage_flag = stage.into();
let root_constant_layout = layout
.constants
.iter()
.filter_map(|constant| {
if constant.stages.contains(stage_flag) {
Some(hlsl::RootConstant {
start: constant.range.start * 4,
end: constant.range.end * 4,
binding: constant.range.start,
space: 0,
})
} else {
None
}
})
.collect();
ast.set_compiler_options(&compile_options)
.map_err(gen_unexpected_error)?;
ast.set_root_constant_layout(root_constant_layout)
.map_err(gen_unexpected_error)?;
ast.compile().map_err(|err| {
let msg = match err {
SpirvErrorCode::CompilationError(msg) => msg,
SpirvErrorCode::Unhandled => "Unknown compile error".into(),
};
d::ShaderError::CompilationFailed(msg)
})
}
// Extract entry point from shader module on pipeline creation.
// Returns compiled shader blob and bool to indicate if the shader should be
// destroyed after pipeline creation
fn extract_entry_point(
stage: pso::Stage,
source: &pso::EntryPoint<B>,
layout: &r::PipelineLayout,
features: &hal::Features,
) -> Result<(native::Blob, bool), d::ShaderError> {
match *source.module {
r::ShaderModule::Compiled(ref shaders) => {
// TODO: do we need to check for specialization constants?
// Use precompiled shader, ignore specialization or layout.
shaders
.get(source.entry)
.map(|src| (*src, false))
.ok_or(d::ShaderError::MissingEntryPoint(source.entry.into()))
}
r::ShaderModule::Spirv(ref raw_data) => {
let mut ast = Self::parse_spirv(raw_data)?;
spirv_cross_specialize_ast(&mut ast, &source.specialization)?;
Self::patch_spirv_resources(&mut ast, layout)?;
let shader_model = hlsl::ShaderModel::V5_1;
let shader_code =
Self::translate_spirv(&mut ast, shader_model, layout, stage, features)?;
debug!("SPIRV-Cross generated shader:\n{}", shader_code);
let real_name = ast
.get_cleansed_entry_point_name(source.entry, conv::map_stage(stage))
.map_err(gen_query_error)?;
// TODO: opt: don't query *all* entry points.
let entry_points = ast.get_entry_points().map_err(gen_query_error)?;
entry_points
.iter()
.find(|entry_point| entry_point.name == real_name)
.ok_or(d::ShaderError::MissingEntryPoint(source.entry.into()))
.and_then(|entry_point| {
let stage = conv::map_execution_model(entry_point.execution_model);
let shader = compile_shader(
stage,
shader_model,
&entry_point.name,
shader_code.as_bytes(),
)?;
Ok((shader, true))
})
}
}
}
/// Create a shader module from HLSL with a single entry point
pub fn create_shader_module_from_source(
&self,
stage: pso::Stage,
hlsl_entry: &str,
entry_point: &str,
code: &[u8],
) -> Result<r::ShaderModule, d::ShaderError> {
let mut shader_map = BTreeMap::new();
let blob = compile_shader(stage, hlsl::ShaderModel::V5_1, hlsl_entry, code)?;
shader_map.insert(entry_point.into(), blob);
Ok(r::ShaderModule::Compiled(shader_map))
}
pub(crate) fn create_command_signature(
device: native::Device,
ty: CommandSignature,
) -> native::CommandSignature {
let (arg, stride) = match ty {
CommandSignature::Draw => (native::IndirectArgument::draw(), 16),
CommandSignature::DrawIndexed => (native::IndirectArgument::draw_indexed(), 20),
CommandSignature::Dispatch => (native::IndirectArgument::dispatch(), 12),
};
let (signature, hr) =
device.create_command_signature(native::RootSignature::null(), &[arg], stride, 0);
if !winerror::SUCCEEDED(hr) {
error!("error on command signature creation: {:x}", hr);
}
signature
}
pub(crate) fn create_descriptor_heap_impl(
device: native::Device,
heap_type: native::DescriptorHeapType,
shader_visible: bool,
capacity: usize,
) -> r::DescriptorHeap {
assert_ne!(capacity, 0);
let (heap, _hr) = device.create_descriptor_heap(
capacity as _,
heap_type,
if shader_visible {
native::DescriptorHeapFlags::SHADER_VISIBLE
} else {
native::DescriptorHeapFlags::empty()
},
0,
);
let descriptor_size = device.get_descriptor_increment_size(heap_type);
let cpu_handle = heap.start_cpu_descriptor();
let gpu_handle = heap.start_gpu_descriptor();
let range_allocator = RangeAllocator::new(0 .. (capacity as u64));
r::DescriptorHeap {
raw: heap,
handle_size: descriptor_size as _,
total_handles: capacity as _,
start: r::DualHandle {
cpu: cpu_handle,
gpu: gpu_handle,
size: 0,
},
range_allocator,
}
}
pub(crate) fn view_image_as_render_target_impl(
device: native::Device,
handle: d3d12::D3D12_CPU_DESCRIPTOR_HANDLE,
info: ViewInfo,
) -> Result<(), image::ViewCreationError> {
#![allow(non_snake_case)]
let mut desc = d3d12::D3D12_RENDER_TARGET_VIEW_DESC {
Format: info.format,
ViewDimension: 0,
u: unsafe { mem::zeroed() },
};
let MipSlice = info.range.levels.start as _;
let FirstArraySlice = info.range.layers.start as _;
let ArraySize = (info.range.layers.end - info.range.layers.start) as _;
let is_msaa = info.kind.num_samples() > 1;
if info.range.levels.start + 1 != info.range.levels.end {
return Err(image::ViewCreationError::Level(info.range.levels.start));
}
if info.range.layers.end > info.kind.num_layers() {
return Err(image::ViewCreationError::Layer(
image::LayerError::OutOfBounds(info.range.layers),
));
}
match info.view_kind {
image::ViewKind::D1 => {
assert_eq!(info.range.layers, 0 .. 1);
desc.ViewDimension = d3d12::D3D12_RTV_DIMENSION_TEXTURE1D;
*unsafe { desc.u.Texture1D_mut() } = d3d12::D3D12_TEX1D_RTV { MipSlice }
}
image::ViewKind::D1Array => {
desc.ViewDimension = d3d12::D3D12_RTV_DIMENSION_TEXTURE1DARRAY;
*unsafe { desc.u.Texture1DArray_mut() } = d3d12::D3D12_TEX1D_ARRAY_RTV {
MipSlice,
FirstArraySlice,
ArraySize,
}
}
image::ViewKind::D2 if is_msaa => {
assert_eq!(info.range.layers, 0 .. 1);
desc.ViewDimension = d3d12::D3D12_RTV_DIMENSION_TEXTURE2DMS;
*unsafe { desc.u.Texture2DMS_mut() } = d3d12::D3D12_TEX2DMS_RTV {
UnusedField_NothingToDefine: 0,
}
}
image::ViewKind::D2 => {
assert_eq!(info.range.layers, 0 .. 1);
desc.ViewDimension = d3d12::D3D12_RTV_DIMENSION_TEXTURE2D;
*unsafe { desc.u.Texture2D_mut() } = d3d12::D3D12_TEX2D_RTV {
MipSlice,
PlaneSlice: 0, //TODO
}
}
image::ViewKind::D2Array if is_msaa => {
desc.ViewDimension = d3d12::D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY;
*unsafe { desc.u.Texture2DMSArray_mut() } = d3d12::D3D12_TEX2DMS_ARRAY_RTV {
FirstArraySlice,
ArraySize,
}
}
image::ViewKind::D2Array => {
desc.ViewDimension = d3d12::D3D12_RTV_DIMENSION_TEXTURE2DARRAY;
*unsafe { desc.u.Texture2DArray_mut() } = d3d12::D3D12_TEX2D_ARRAY_RTV {
MipSlice,
FirstArraySlice,
ArraySize,
PlaneSlice: 0, //TODO
}
}
image::ViewKind::D3 => {
assert_eq!(info.range.layers, 0 .. 1);
desc.ViewDimension = d3d12::D3D12_RTV_DIMENSION_TEXTURE3D;
*unsafe { desc.u.Texture3D_mut() } = d3d12::D3D12_TEX3D_RTV {
MipSlice,
FirstWSlice: 0,
WSize: info.kind.extent().depth as _,
}
}
image::ViewKind::Cube | image::ViewKind::CubeArray => {
desc.ViewDimension = d3d12::D3D12_RTV_DIMENSION_TEXTURE2DARRAY;
//TODO: double-check if any *6 are needed
*unsafe { desc.u.Texture2DArray_mut() } = d3d12::D3D12_TEX2D_ARRAY_RTV {
MipSlice,
FirstArraySlice,
ArraySize,
PlaneSlice: 0, //TODO
}
}
};
unsafe {
device.CreateRenderTargetView(info.resource.as_mut_ptr(), &desc, handle);
}
Ok(())
}
fn view_image_as_render_target(
&self,
info: ViewInfo,
) -> Result<d3d12::D3D12_CPU_DESCRIPTOR_HANDLE, image::ViewCreationError> {
let handle = self.rtv_pool.lock().unwrap().alloc_handle();
Self::view_image_as_render_target_impl(self.raw, handle, info).map(|_| handle)
}
pub(crate) fn view_image_as_depth_stencil_impl(
device: native::Device,
handle: d3d12::D3D12_CPU_DESCRIPTOR_HANDLE,
info: ViewInfo,
) -> Result<(), image::ViewCreationError> {
#![allow(non_snake_case)]
let mut desc = d3d12::D3D12_DEPTH_STENCIL_VIEW_DESC {
Format: info.format,
ViewDimension: 0,
Flags: 0,
u: unsafe { mem::zeroed() },
};
let MipSlice = info.range.levels.start as _;
let FirstArraySlice = info.range.layers.start as _;
let ArraySize = (info.range.layers.end - info.range.layers.start) as _;
let is_msaa = info.kind.num_samples() > 1;
if info.range.levels.start + 1 != info.range.levels.end {
return Err(image::ViewCreationError::Level(info.range.levels.start));
}
if info.range.layers.end > info.kind.num_layers() {
return Err(image::ViewCreationError::Layer(
image::LayerError::OutOfBounds(info.range.layers),
));
}
match info.view_kind {
image::ViewKind::D1 => {
assert_eq!(info.range.layers, 0 .. 1);
desc.ViewDimension = d3d12::D3D12_DSV_DIMENSION_TEXTURE1D;
*unsafe { desc.u.Texture1D_mut() } = d3d12::D3D12_TEX1D_DSV { MipSlice }
}
image::ViewKind::D1Array => {
desc.ViewDimension = d3d12::D3D12_DSV_DIMENSION_TEXTURE1DARRAY;
*unsafe { desc.u.Texture1DArray_mut() } = d3d12::D3D12_TEX1D_ARRAY_DSV {
MipSlice,
FirstArraySlice,
ArraySize,
}
}
image::ViewKind::D2 if is_msaa => {
assert_eq!(info.range.layers, 0 .. 1);
desc.ViewDimension = d3d12::D3D12_DSV_DIMENSION_TEXTURE2DMS;
*unsafe { desc.u.Texture2DMS_mut() } = d3d12::D3D12_TEX2DMS_DSV {
UnusedField_NothingToDefine: 0,
}
}
image::ViewKind::D2 => {
assert_eq!(info.range.layers, 0 .. 1);
desc.ViewDimension = d3d12::D3D12_DSV_DIMENSION_TEXTURE2D;
*unsafe { desc.u.Texture2D_mut() } = d3d12::D3D12_TEX2D_DSV { MipSlice }
}
image::ViewKind::D2Array if is_msaa => {
desc.ViewDimension = d3d12::D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY;
*unsafe { desc.u.Texture2DMSArray_mut() } = d3d12::D3D12_TEX2DMS_ARRAY_DSV {
FirstArraySlice,
ArraySize,
}
}
image::ViewKind::D2Array => {
desc.ViewDimension = d3d12::D3D12_DSV_DIMENSION_TEXTURE2DARRAY;
*unsafe { desc.u.Texture2DArray_mut() } = d3d12::D3D12_TEX2D_ARRAY_DSV {
MipSlice,
FirstArraySlice,
ArraySize,
}
}
image::ViewKind::D3 | image::ViewKind::Cube | image::ViewKind::CubeArray => {
unimplemented!()
}
};
unsafe {
device.CreateDepthStencilView(info.resource.as_mut_ptr(), &desc, handle);
}
Ok(())
}
fn view_image_as_depth_stencil(
&self,
info: ViewInfo,
) -> Result<d3d12::D3D12_CPU_DESCRIPTOR_HANDLE, image::ViewCreationError> {
let handle = self.dsv_pool.lock().unwrap().alloc_handle();
Self::view_image_as_depth_stencil_impl(self.raw, handle, info).map(|_| handle)
}
pub(crate) fn build_image_as_shader_resource_desc(
info: &ViewInfo,
) -> Result<d3d12::D3D12_SHADER_RESOURCE_VIEW_DESC, image::ViewCreationError> {
#![allow(non_snake_case)]
let mut desc = d3d12::D3D12_SHADER_RESOURCE_VIEW_DESC {
Format: info.format,
ViewDimension: 0,
Shader4ComponentMapping: info.component_mapping,
u: unsafe { mem::zeroed() },
};
let MostDetailedMip = info.range.levels.start as _;
let MipLevels = (info.range.levels.end - info.range.levels.start) as _;
let FirstArraySlice = info.range.layers.start as _;
let ArraySize = (info.range.layers.end - info.range.layers.start) as _;
if info.range.layers.end > info.kind.num_layers() {
return Err(image::ViewCreationError::Layer(
image::LayerError::OutOfBounds(info.range.layers.clone()),
));
}
let is_msaa = info.kind.num_samples() > 1;
let is_cube = info.caps.contains(image::ViewCapabilities::KIND_CUBE);
match info.view_kind {
image::ViewKind::D1 => {
assert_eq!(info.range.layers, 0 .. 1);
desc.ViewDimension = d3d12::D3D12_SRV_DIMENSION_TEXTURE1D;
*unsafe { desc.u.Texture1D_mut() } = d3d12::D3D12_TEX1D_SRV {
MostDetailedMip,
MipLevels,
ResourceMinLODClamp: 0.0,
}
}
image::ViewKind::D1Array => {
desc.ViewDimension = d3d12::D3D12_SRV_DIMENSION_TEXTURE1DARRAY;
*unsafe { desc.u.Texture1DArray_mut() } = d3d12::D3D12_TEX1D_ARRAY_SRV {
MostDetailedMip,
MipLevels,
FirstArraySlice,
ArraySize,
ResourceMinLODClamp: 0.0,
}
}
image::ViewKind::D2 if is_msaa => {
assert_eq!(info.range.layers, 0 .. 1);
desc.ViewDimension = d3d12::D3D12_SRV_DIMENSION_TEXTURE2DMS;
*unsafe { desc.u.Texture2DMS_mut() } = d3d12::D3D12_TEX2DMS_SRV {
UnusedField_NothingToDefine: 0,
}
}
image::ViewKind::D2 => {
assert_eq!(info.range.layers, 0 .. 1);
desc.ViewDimension = d3d12::D3D12_SRV_DIMENSION_TEXTURE2D;
*unsafe { desc.u.Texture2D_mut() } = d3d12::D3D12_TEX2D_SRV {
MostDetailedMip,
MipLevels,
PlaneSlice: 0, //TODO
ResourceMinLODClamp: 0.0,
}
}
image::ViewKind::D2Array if is_msaa => {
desc.ViewDimension = d3d12::D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY;
*unsafe { desc.u.Texture2DMSArray_mut() } = d3d12::D3D12_TEX2DMS_ARRAY_SRV {
FirstArraySlice,
ArraySize,
}
}
image::ViewKind::D2Array => {
desc.ViewDimension = d3d12::D3D12_SRV_DIMENSION_TEXTURE2DARRAY;
*unsafe { desc.u.Texture2DArray_mut() } = d3d12::D3D12_TEX2D_ARRAY_SRV {
MostDetailedMip,
MipLevels,
FirstArraySlice,
ArraySize,
PlaneSlice: 0, //TODO
ResourceMinLODClamp: 0.0,
}
}
image::ViewKind::D3 => {
assert_eq!(info.range.layers, 0 .. 1);
desc.ViewDimension = d3d12::D3D12_SRV_DIMENSION_TEXTURE3D;
*unsafe { desc.u.Texture3D_mut() } = d3d12::D3D12_TEX3D_SRV {
MostDetailedMip,
MipLevels,
ResourceMinLODClamp: 0.0,
}
}
image::ViewKind::Cube if is_cube => {
desc.ViewDimension = d3d12::D3D12_SRV_DIMENSION_TEXTURECUBE;
*unsafe { desc.u.TextureCube_mut() } = d3d12::D3D12_TEXCUBE_SRV {
MostDetailedMip,
MipLevels,
ResourceMinLODClamp: 0.0,
}
}
image::ViewKind::CubeArray if is_cube => {
assert_eq!(0, ArraySize % 6);
desc.ViewDimension = d3d12::D3D12_SRV_DIMENSION_TEXTURECUBEARRAY;
*unsafe { desc.u.TextureCubeArray_mut() } = d3d12::D3D12_TEXCUBE_ARRAY_SRV {
MostDetailedMip,
MipLevels,
First2DArrayFace: FirstArraySlice,
NumCubes: ArraySize / 6,
ResourceMinLODClamp: 0.0,
}
}
image::ViewKind::Cube | image::ViewKind::CubeArray => {
error!(
"Cube views are not supported for the image, kind: {:?}",
info.kind
);
return Err(image::ViewCreationError::BadKind(info.view_kind));
}
}
Ok(desc)
}
fn view_image_as_shader_resource(
&self,
mut info: ViewInfo,
) -> Result<d3d12::D3D12_CPU_DESCRIPTOR_HANDLE, image::ViewCreationError> {
#![allow(non_snake_case)]
// Depth-stencil formats can't be used for SRVs.
info.format = match info.format {
dxgiformat::DXGI_FORMAT_D16_UNORM => dxgiformat::DXGI_FORMAT_R16_UNORM,
dxgiformat::DXGI_FORMAT_D32_FLOAT => dxgiformat::DXGI_FORMAT_R32_FLOAT,
format => format,
};
let desc = Self::build_image_as_shader_resource_desc(&info)?;
let handle = self.srv_uav_pool.lock().unwrap().alloc_handle();
unsafe {
self.raw
.CreateShaderResourceView(info.resource.as_mut_ptr(), &desc, handle);
}
Ok(handle)
}
fn view_image_as_storage(
&self,
info: ViewInfo,
) -> Result<d3d12::D3D12_CPU_DESCRIPTOR_HANDLE, image::ViewCreationError> {
#![allow(non_snake_case)]
assert_eq!(info.range.levels.start + 1, info.range.levels.end);
let mut desc = d3d12::D3D12_UNORDERED_ACCESS_VIEW_DESC {
Format: info.format,
ViewDimension: 0,
u: unsafe { mem::zeroed() },
};
let MipSlice = info.range.levels.start as _;
let FirstArraySlice = info.range.layers.start as _;
let ArraySize = (info.range.layers.end - info.range.layers.start) as _;
if info.range.layers.end > info.kind.num_layers() {
return Err(image::ViewCreationError::Layer(
image::LayerError::OutOfBounds(info.range.layers),
));
}
if info.kind.num_samples() > 1 {
error!("MSAA images can't be viewed as UAV");
return Err(image::ViewCreationError::Unsupported);
}
match info.view_kind {
image::ViewKind::D1 => {
assert_eq!(info.range.layers, 0 .. 1);
desc.ViewDimension = d3d12::D3D12_UAV_DIMENSION_TEXTURE1D;
*unsafe { desc.u.Texture1D_mut() } = d3d12::D3D12_TEX1D_UAV { MipSlice }
}
image::ViewKind::D1Array => {
desc.ViewDimension = d3d12::D3D12_UAV_DIMENSION_TEXTURE1DARRAY;
*unsafe { desc.u.Texture1DArray_mut() } = d3d12::D3D12_TEX1D_ARRAY_UAV {
MipSlice,
FirstArraySlice,
ArraySize,
}
}
image::ViewKind::D2 => {
assert_eq!(info.range.layers, 0 .. 1);
desc.ViewDimension = d3d12::D3D12_UAV_DIMENSION_TEXTURE2D;
*unsafe { desc.u.Texture2D_mut() } = d3d12::D3D12_TEX2D_UAV {
MipSlice,
PlaneSlice: 0, //TODO
}
}
image::ViewKind::D2Array => {
desc.ViewDimension = d3d12::D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
*unsafe { desc.u.Texture2DArray_mut() } = d3d12::D3D12_TEX2D_ARRAY_UAV {
MipSlice,
FirstArraySlice,
ArraySize,
PlaneSlice: 0, //TODO
}
}
image::ViewKind::D3 => {
assert_eq!(info.range.layers, 0 .. 1);
desc.ViewDimension = d3d12::D3D12_UAV_DIMENSION_TEXTURE3D;
*unsafe { desc.u.Texture3D_mut() } = d3d12::D3D12_TEX3D_UAV {
MipSlice,
FirstWSlice: 0,
WSize: info.kind.extent().depth as _,
}
}
image::ViewKind::Cube | image::ViewKind::CubeArray => {
error!("Cubic images can't be viewed as UAV");
return Err(image::ViewCreationError::Unsupported);
}
}
let handle = self.srv_uav_pool.lock().unwrap().alloc_handle();
unsafe {
self.raw.CreateUnorderedAccessView(
info.resource.as_mut_ptr(),
ptr::null_mut(),
&desc,
handle,
);
}
Ok(handle)
}
pub(crate) fn create_raw_fence(&self, signalled: bool) -> native::Fence {
let mut handle = native::Fence::null();
assert_eq!(winerror::S_OK, unsafe {
self.raw.CreateFence(
if signalled { 1 } else { 0 },
d3d12::D3D12_FENCE_FLAG_NONE,
&d3d12::ID3D12Fence::uuidof(),
handle.mut_void(),
)
});
handle
}
pub(crate) fn create_swapchain_impl(
&self,
config: &w::SwapchainConfig,
window_handle: windef::HWND,
factory: native::WeakPtr<dxgi1_4::IDXGIFactory4>,
) -> Result<
(
native::WeakPtr<dxgi1_4::IDXGISwapChain3>,
dxgiformat::DXGI_FORMAT,
),
w::CreationError,
> {
let mut swap_chain1 = native::WeakPtr::<dxgi1_2::IDXGISwapChain1>::null();
//TODO: proper error type?
let non_srgb_format = conv::map_format_nosrgb(config.format).unwrap();
// TODO: double-check values
let desc = dxgi1_2::DXGI_SWAP_CHAIN_DESC1 {
AlphaMode: dxgi1_2::DXGI_ALPHA_MODE_IGNORE,
BufferCount: config.image_count,
Width: config.extent.width,
Height: config.extent.height,
Format: non_srgb_format,
Flags: dxgi::DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT,
BufferUsage: dxgitype::DXGI_USAGE_RENDER_TARGET_OUTPUT,
SampleDesc: dxgitype::DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
Scaling: dxgi1_2::DXGI_SCALING_STRETCH,
Stereo: FALSE,
SwapEffect: dxgi::DXGI_SWAP_EFFECT_FLIP_DISCARD,
};
unsafe {
let hr = factory.CreateSwapChainForHwnd(
self.present_queue.as_mut_ptr() as *mut _,
window_handle,
&desc,
ptr::null(),
ptr::null_mut(),
swap_chain1.mut_void() as *mut *mut _,
);
if !winerror::SUCCEEDED(hr) {
error!("error on swapchain creation 0x{:x}", hr);
}
let (swap_chain3, hr3) = swap_chain1.cast::<dxgi1_4::IDXGISwapChain3>();
if !winerror::SUCCEEDED(hr3) {
error!("error on swapchain cast 0x{:x}", hr3);
}
swap_chain1.destroy();
Ok((swap_chain3, non_srgb_format))
}
}
pub(crate) fn wrap_swapchain(
&self,
inner: native::WeakPtr<dxgi1_4::IDXGISwapChain3>,
config: &w::SwapchainConfig,
) -> Swapchain {
let waitable = unsafe {
inner.SetMaximumFrameLatency(config.image_count);
inner.GetFrameLatencyWaitableObject()
};
let rtv_desc = d3d12::D3D12_RENDER_TARGET_VIEW_DESC {
Format: conv::map_format(config.format).unwrap(),
ViewDimension: d3d12::D3D12_RTV_DIMENSION_TEXTURE2D,
..unsafe { mem::zeroed() }
};
let rtv_heap = Device::create_descriptor_heap_impl(
self.raw,
native::DescriptorHeapType::Rtv,
false,
config.image_count as _,
);
let mut resources = vec![native::Resource::null(); config.image_count as usize];
for (i, res) in resources.iter_mut().enumerate() {
let rtv_handle = rtv_heap.at(i as _, 0).cpu;
unsafe {
inner.GetBuffer(i as _, &d3d12::ID3D12Resource::uuidof(), res.mut_void());
self.raw
.CreateRenderTargetView(res.as_mut_ptr(), &rtv_desc, rtv_handle);
}
}
Swapchain {
inner,
frame_queue: VecDeque::new(),
rtv_heap,
resources,
waitable,
}
}
}
impl d::Device<B> for Device {
unsafe fn allocate_memory(
&self,
mem_type: hal::MemoryTypeId,
size: u64,
) -> Result<r::Memory, d::AllocationError> {
let mem_type = mem_type.0;
let mem_base_id = mem_type % NUM_HEAP_PROPERTIES;
let heap_property = &self.heap_properties[mem_base_id];
let properties = d3d12::D3D12_HEAP_PROPERTIES {
Type: d3d12::D3D12_HEAP_TYPE_CUSTOM,
CPUPageProperty: heap_property.page_property,
MemoryPoolPreference: heap_property.memory_pool,
CreationNodeMask: 0,
VisibleNodeMask: 0,
};
// Exposed memory types are grouped according to their capabilities.
// See `MemoryGroup` for more details.
let mem_group = mem_type / NUM_HEAP_PROPERTIES;
let desc = d3d12::D3D12_HEAP_DESC {
SizeInBytes: size,
Properties: properties,
Alignment: d3d12::D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT as _, // TODO: not always..?
Flags: match mem_group {
0 => d3d12::D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES,
1 => d3d12::D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS,
2 => d3d12::D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES,
3 => d3d12::D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES,
_ => unreachable!(),
},
};
let mut heap = native::Heap::null();
let hr = self
.raw
.clone()
.CreateHeap(&desc, &d3d12::ID3D12Heap::uuidof(), heap.mut_void());
if hr == winerror::E_OUTOFMEMORY {
return Err(d::OutOfMemory::Device.into());
}
assert_eq!(winerror::S_OK, hr);
// The first memory heap of each group corresponds to the default heap, which is can never
// be mapped.
// Devices supporting heap tier 1 can only created buffers on mem group 1 (ALLOW_ONLY_BUFFERS).
// Devices supporting heap tier 2 always expose only mem group 0 and don't have any further restrictions.
let is_mapable = mem_base_id != 0
&& (mem_group == MemoryGroup::Universal as _
|| mem_group == MemoryGroup::BufferOnly as _);
// Create a buffer resource covering the whole memory slice to be able to map the whole memory.
let resource = if is_mapable {
let mut resource = native::Resource::null();
let desc = d3d12::D3D12_RESOURCE_DESC {
Dimension: d3d12::D3D12_RESOURCE_DIMENSION_BUFFER,
Alignment: 0,
Width: size,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
Format: dxgiformat::DXGI_FORMAT_UNKNOWN,
SampleDesc: dxgitype::DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
Layout: d3d12::D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
Flags: d3d12::D3D12_RESOURCE_FLAG_NONE,
};
assert_eq!(
winerror::S_OK,
self.raw.clone().CreatePlacedResource(
heap.as_mut_ptr(),
0,
&desc,
d3d12::D3D12_RESOURCE_STATE_COMMON,
ptr::null(),
&d3d12::ID3D12Resource::uuidof(),
resource.mut_void(),
)
);
Some(resource)
} else {
None
};
Ok(r::Memory {
heap,
type_id: mem_type,
size,
resource,
})
}
unsafe fn create_command_pool(
&self,
family: QueueFamilyId,
create_flags: CommandPoolCreateFlags,
) -> Result<CommandPool, d::OutOfMemory> {
let list_type = QUEUE_FAMILIES[family.0].native_type();
let allocator = if create_flags.contains(CommandPoolCreateFlags::RESET_INDIVIDUAL) {
// Allocators are created per individual ID3D12GraphicsCommandList
CommandPoolAllocator::Individual(Vec::new())
} else {
let (command_allocator, hr) = self.raw.create_command_allocator(list_type);
// TODO: error handling
if !winerror::SUCCEEDED(hr) {
error!("error on command allocator creation: {:x}", hr);
}
CommandPoolAllocator::Shared(command_allocator)
};
Ok(CommandPool {
allocator,
device: self.raw,
list_type,
shared: self.shared.clone(),
create_flags,
})
}
unsafe fn destroy_command_pool(&self, pool: CommandPool) {
pool.destroy();
}
unsafe fn create_render_pass<'a, IA, IS, ID>(
&self,
attachments: IA,
subpasses: IS,
dependencies: ID,
) -> Result<r::RenderPass, d::OutOfMemory>
where
IA: IntoIterator,
IA::Item: Borrow<pass::Attachment>,
IS: IntoIterator,
IS::Item: Borrow<pass::SubpassDesc<'a>>,
ID: IntoIterator,
ID::Item: Borrow<pass::SubpassDependency>,
{
#[derive(Copy, Clone, Debug, PartialEq)]
enum SubState {
New(d3d12::D3D12_RESOURCE_STATES),
// Color attachment which will be resolved at the end of the subpass
Resolve(d3d12::D3D12_RESOURCE_STATES),
Preserve,
Undefined,
}
/// Temporary information about every sub-pass
struct SubInfo<'a> {
desc: pass::SubpassDesc<'a>,
/// States before the render-pass (in self.start)
/// and after the render-pass (in self.end).
external_dependencies: Range<image::Access>,
/// Counts the number of dependencies that need to be resolved
/// before starting this subpass.
unresolved_dependencies: u16,
}
struct AttachmentInfo {
sub_states: Vec<SubState>,
last_state: d3d12::D3D12_RESOURCE_STATES,
barrier_start_index: usize,
}
let attachments = attachments
.into_iter()
.map(|attachment| attachment.borrow().clone())
.collect::<SmallVec<[_; 5]>>();
let mut sub_infos = subpasses
.into_iter()
.map(|desc| SubInfo {
desc: desc.borrow().clone(),
external_dependencies: image::Access::empty() .. image::Access::empty(),
unresolved_dependencies: 0,
})
.collect::<SmallVec<[_; 1]>>();
let dependencies = dependencies.into_iter().collect::<SmallVec<[_; 2]>>();
let mut att_infos = (0 .. attachments.len())
.map(|_| AttachmentInfo {
sub_states: vec![SubState::Undefined; sub_infos.len()],
last_state: d3d12::D3D12_RESOURCE_STATE_COMMON, // is to be overwritten
barrier_start_index: 0,
})
.collect::<SmallVec<[_; 5]>>();
for dep in &dependencies {
let dep = dep.borrow();
match dep.passes {
Range {
start: None,
end: None,
} => {
error!("Unexpected external-external dependency!");
}
Range {
start: None,
end: Some(sid),
} => {
sub_infos[sid as usize].external_dependencies.start |= dep.accesses.start;
}
Range {
start: Some(sid),
end: None,
} => {
sub_infos[sid as usize].external_dependencies.end |= dep.accesses.end;
}
Range {
start: Some(from_sid),
end: Some(sid),
} => {
//Note: self-dependencies are ignored
if from_sid != sid {
sub_infos[sid as usize].unresolved_dependencies += 1;
}
}
}
}
// Fill out subpass known layouts
for (sid, sub_info) in sub_infos.iter().enumerate() {
let sub = &sub_info.desc;
for (i, &(id, _layout)) in sub.colors.iter().enumerate() {
let target_state = d3d12::D3D12_RESOURCE_STATE_RENDER_TARGET;
let state = match sub.resolves.get(i) {
Some(_) => SubState::Resolve(target_state),
None => SubState::New(target_state),
};
let old = mem::replace(&mut att_infos[id].sub_states[sid], state);
debug_assert_eq!(SubState::Undefined, old);
}
for &(id, layout) in sub.depth_stencil {
let state = SubState::New(match layout {
image::Layout::DepthStencilAttachmentOptimal => {
d3d12::D3D12_RESOURCE_STATE_DEPTH_WRITE
}
image::Layout::DepthStencilReadOnlyOptimal => {
d3d12::D3D12_RESOURCE_STATE_DEPTH_READ
}
image::Layout::General => d3d12::D3D12_RESOURCE_STATE_DEPTH_WRITE,
_ => {
error!("Unexpected depth/stencil layout: {:?}", layout);
d3d12::D3D12_RESOURCE_STATE_COMMON
}
});
let old = mem::replace(&mut att_infos[id].sub_states[sid], state);
debug_assert_eq!(SubState::Undefined, old);
}
for &(id, _layout) in sub.inputs {
let state = SubState::New(d3d12::D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
let old = mem::replace(&mut att_infos[id].sub_states[sid], state);
debug_assert_eq!(SubState::Undefined, old);
}
for &(id, _layout) in sub.resolves {
let state = SubState::New(d3d12::D3D12_RESOURCE_STATE_RESOLVE_DEST);
let old = mem::replace(&mut att_infos[id].sub_states[sid], state);
debug_assert_eq!(SubState::Undefined, old);
}
for &id in sub.preserves {
let old = mem::replace(&mut att_infos[id].sub_states[sid], SubState::Preserve);
debug_assert_eq!(SubState::Undefined, old);
}
}
let mut rp = r::RenderPass {
attachments: attachments.iter().cloned().collect(),
subpasses: Vec::new(),
post_barriers: Vec::new(),
};
while let Some(sid) = sub_infos
.iter()
.position(|si| si.unresolved_dependencies == 0)
{
for dep in &dependencies {
let dep = dep.borrow();
if dep.passes.start != dep.passes.end
&& dep.passes.start == Some(sid as pass::SubpassId)
{
if let Some(other) = dep.passes.end {
sub_infos[other as usize].unresolved_dependencies -= 1;
}
}
}
let si = &mut sub_infos[sid];
si.unresolved_dependencies = !0; // mark as done
// Subpass barriers
let mut pre_barriers = Vec::new();
let mut post_barriers = Vec::new();
for (att_id, (ai, att)) in att_infos.iter_mut().zip(attachments.iter()).enumerate() {
// Attachment wasn't used before, figure out the initial state
if ai.barrier_start_index == 0 {
//Note: the external dependencies are provided for all attachments that are
// first used in this sub-pass, so they may contain more states than we expect
// for this particular attachment.
ai.last_state = conv::map_image_resource_state(
si.external_dependencies.start,
att.layouts.start,
);
}
// Barrier from previous subpass to current or following subpasses.
match ai.sub_states[sid] {
SubState::Preserve => {
ai.barrier_start_index = rp.subpasses.len() + 1;
}
SubState::New(state) if state != ai.last_state => {
let barrier = r::BarrierDesc::new(att_id, ai.last_state .. state);
match rp.subpasses.get_mut(ai.barrier_start_index) {
Some(past_subpass) => {
let split = barrier.split();
past_subpass.pre_barriers.push(split.start);
pre_barriers.push(split.end);
}
None => pre_barriers.push(barrier),
}
ai.last_state = state;
ai.barrier_start_index = rp.subpasses.len() + 1;
}
SubState::Resolve(state) => {
// 1. Standard pre barrier to update state from previous pass into desired substate.
if state != ai.last_state {
let barrier = r::BarrierDesc::new(att_id, ai.last_state .. state);
match rp.subpasses.get_mut(ai.barrier_start_index) {
Some(past_subpass) => {
let split = barrier.split();
past_subpass.pre_barriers.push(split.start);
pre_barriers.push(split.end);
}
None => pre_barriers.push(barrier),
}
}
// 2. Post Barrier at the end of the subpass into RESOLVE_SOURCE.
let resolve_state = d3d12::D3D12_RESOURCE_STATE_RESOLVE_SOURCE;
let barrier = r::BarrierDesc::new(att_id, state .. resolve_state);
post_barriers.push(barrier);
ai.last_state = resolve_state;
ai.barrier_start_index = rp.subpasses.len() + 1;
}
SubState::Undefined | SubState::New(_) => {}
};
}
rp.subpasses.push(r::SubpassDesc {
color_attachments: si.desc.colors.iter().cloned().collect(),
depth_stencil_attachment: si.desc.depth_stencil.cloned(),
input_attachments: si.desc.inputs.iter().cloned().collect(),
resolve_attachments: si.desc.resolves.iter().cloned().collect(),
pre_barriers,
post_barriers,
});
}
// if this fails, our graph has cycles
assert_eq!(rp.subpasses.len(), sub_infos.len());
assert!(sub_infos.iter().all(|si| si.unresolved_dependencies == !0));
// take care of the post-pass transitions at the end of the renderpass.
for (att_id, (ai, att)) in att_infos.iter().zip(attachments.iter()).enumerate() {
let state_dst = if ai.barrier_start_index == 0 {
// attachment wasn't used in any sub-pass?
continue;
} else {
let si = &sub_infos[ai.barrier_start_index - 1];
conv::map_image_resource_state(si.external_dependencies.end, att.layouts.end)
};
if state_dst == ai.last_state {
continue;
}
let barrier = r::BarrierDesc::new(att_id, ai.last_state .. state_dst);
match rp.subpasses.get_mut(ai.barrier_start_index) {
Some(past_subpass) => {
let split = barrier.split();
past_subpass.pre_barriers.push(split.start);
rp.post_barriers.push(split.end);
}
None => rp.post_barriers.push(barrier),
}
}
Ok(rp)
}
unsafe fn create_pipeline_layout<IS, IR>(
&self,
sets: IS,
push_constant_ranges: IR,
) -> Result<r::PipelineLayout, d::OutOfMemory>
where
IS: IntoIterator,
IS::Item: Borrow<r::DescriptorSetLayout>,
IR: IntoIterator,
IR::Item: Borrow<(pso::ShaderStageFlags, Range<u32>)>,
{
// Pipeline layouts are implemented as RootSignature for D3D12.
//
// Push Constants are implemented as root constants.
//
// Each descriptor set layout will be one table entry of the root signature.
// We have the additional restriction that SRV/CBV/UAV and samplers need to be
// separated, so each set layout will actually occupy up to 2 entries!
//
// Dynamic uniform buffers are implemented as root descriptors.
// This allows to handle the dynamic offsets properly, which would not be feasible
// with a combination of root constant and descriptor table.
//
// Root signature layout:
// Root Constants: Register: Offest/4, Space: 0
// ...
// DescriptorTable0: Space: 1 (+1) (SrvCbvUav)
// Root Descriptors
// DescriptorTable0: Space: 2 (+1) (Sampler)
// DescriptorTable1: Space: 3 (+1) (SrvCbvUav)
// ...
let sets = sets.into_iter().collect::<Vec<_>>();
let mut root_offset = 0;
let root_constants = root_constants::split(push_constant_ranges)
.iter()
.map(|constant| {
assert!(constant.range.start <= constant.range.end);
root_offset += (constant.range.end - constant.range.start) as usize;
RootConstant {
stages: constant.stages,
range: constant.range.start .. constant.range.end,
}
})
.collect::<Vec<_>>();
info!(
"Creating a pipeline layout with {} sets and {} root constants",
sets.len(),
root_constants.len()
);
// Number of elements in the root signature.
// Guarantees that no re-allocation is done, and our pointers are valid
let mut parameters = Vec::with_capacity(root_constants.len() + sets.len() * 2);
// Convert root signature descriptions into root signature parameters.
for root_constant in root_constants.iter() {
debug!(
"\tRoot constant set={} range {:?}",
ROOT_CONSTANT_SPACE, root_constant.range
);
parameters.push(native::RootParameter::constants(
conv::map_shader_visibility(root_constant.stages),
native::Binding {
register: root_constant.range.start as _,
space: ROOT_CONSTANT_SPACE,
},
(root_constant.range.end - root_constant.range.start) as _,
));
}
// Offest of `spaceN` for descriptor tables. Root constants will be in
// `space0`.
// This has to match `patch_spirv_resources` logic.
let root_space_offset = if !root_constants.is_empty() { 1 } else { 0 };
// Collect the whole number of bindings we will create upfront.
// It allows us to preallocate enough storage to avoid reallocation,
// which could cause invalid pointers.
let total = sets
.iter()
.map(|desc_set| {
let mut sum = 0;
for binding in desc_set.borrow().bindings.iter() {
let content = r::DescriptorContent::from(binding.ty);
if !content.is_dynamic() {
sum += content.bits().count_ones() as usize;
}
}
sum
})
.sum();
let mut ranges = Vec::with_capacity(total);
let elements = sets
.iter()
.enumerate()
.map(|(i, set)| {
let set = set.borrow();
let space = (root_space_offset + i) as u32;
let mut table_type = r::SetTableTypes::empty();
let root_table_offset = root_offset;
//TODO: split between sampler and non-sampler tables
let visibility = conv::map_shader_visibility(
set.bindings
.iter()
.fold(pso::ShaderStageFlags::empty(), |u, bind| {
u | bind.stage_flags
}),
);
for bind in set.bindings.iter() {
debug!("\tRange {:?} at space={}", bind, space);
}
let describe = |bind: &pso::DescriptorSetLayoutBinding, ty| {
native::DescriptorRange::new(
ty,
bind.count as _,
native::Binding {
register: bind.binding as _,
space,
},
d3d12::D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND,
)
};
let mut descriptors = Vec::new();
let mut mutable_bindings = auxil::FastHashSet::default();
let mut range_base = ranges.len();
for bind in set.bindings.iter() {
let content = r::DescriptorContent::from(bind.ty);
if content.is_dynamic() {
// Root Descriptor
let binding = native::Binding {
register: bind.binding as _,
space,
};
if content.contains(r::DescriptorContent::CBV) {
descriptors.push(r::RootDescriptor {
offset: root_offset,
});
parameters
.push(native::RootParameter::cbv_descriptor(visibility, binding));
root_offset += 2;
} else {
// SRV and UAV not implemented so far
unimplemented!()
}
} else {
// Descriptor table ranges
if content.contains(r::DescriptorContent::CBV) {
ranges.push(describe(bind, native::DescriptorRangeType::CBV));
}
if content.contains(r::DescriptorContent::SRV) {
ranges.push(describe(bind, native::DescriptorRangeType::SRV));
}
if content.contains(r::DescriptorContent::UAV) {
ranges.push(describe(bind, native::DescriptorRangeType::UAV));
mutable_bindings.insert(bind.binding);
}
}
}
if ranges.len() > range_base {
parameters.push(native::RootParameter::descriptor_table(
visibility,
&ranges[range_base ..],
));
table_type |= r::SRV_CBV_UAV;
root_offset += 1;
}
range_base = ranges.len();
for bind in set.bindings.iter() {
let content = r::DescriptorContent::from(bind.ty);
if content.contains(r::DescriptorContent::SAMPLER) {
ranges.push(describe(bind, native::DescriptorRangeType::Sampler));
}
}
if ranges.len() > range_base {
parameters.push(native::RootParameter::descriptor_table(
visibility,
&ranges[range_base ..],
));
table_type |= r::SAMPLERS;
root_offset += 1;
}
r::RootElement {
table: r::RootTable {
ty: table_type,
offset: root_table_offset as _,
},
descriptors,
mutable_bindings,
}
})
.collect();
// Ensure that we didn't reallocate!
debug_assert_eq!(ranges.len(), total);
// TODO: error handling
let (signature_raw, error) = match self.library.serialize_root_signature(
native::RootSignatureVersion::V1_0,
¶meters,
&[],
native::RootSignatureFlags::ALLOW_IA_INPUT_LAYOUT,
) {
Ok((pair, hr)) if winerror::SUCCEEDED(hr) => pair,
Ok((_, hr)) => panic!("Can't serialize root signature: {:?}", hr),
Err(e) => panic!("Can't find serialization function: {:?}", e),
};
if !error.is_null() {
error!(
"Root signature serialization error: {:?}",
error.as_c_str().to_str().unwrap()
);
error.destroy();
}
// TODO: error handling
let (signature, _hr) = self.raw.create_root_signature(signature_raw, 0);
signature_raw.destroy();
Ok(r::PipelineLayout {
raw: signature,
constants: root_constants,
elements,
num_parameter_slots: parameters.len(),
})
}
unsafe fn create_pipeline_cache(&self, _data: Option<&[u8]>) -> Result<(), d::OutOfMemory> {
Ok(())
}
unsafe fn get_pipeline_cache_data(&self, _cache: &()) -> Result<Vec<u8>, d::OutOfMemory> {
//empty
Ok(Vec::new())
}
unsafe fn destroy_pipeline_cache(&self, _: ()) {
//empty
}
unsafe fn merge_pipeline_caches<I>(&self, _: &(), _: I) -> Result<(), d::OutOfMemory>
where
I: IntoIterator,
I::Item: Borrow<()>,
{
//empty
Ok(())
}
unsafe fn create_graphics_pipeline<'a>(
&self,
desc: &pso::GraphicsPipelineDesc<'a, B>,
_cache: Option<&()>,
) -> Result<r::GraphicsPipeline, pso::CreationError> {
enum ShaderBc {
Owned(native::Blob),
Borrowed(native::Blob),
None,
}
let features = &self.features;
impl ShaderBc {
pub fn shader(&self) -> native::Shader {
match *self {
ShaderBc::Owned(ref bc) | ShaderBc::Borrowed(ref bc) => {
native::Shader::from_blob(*bc)
}
ShaderBc::None => native::Shader::null(),
}
}
}
let build_shader = |stage: pso::Stage, source: Option<&pso::EntryPoint<'a, B>>| {
let source = match source {
Some(src) => src,
None => return Ok(ShaderBc::None),
};
match Self::extract_entry_point(stage, source, desc.layout, features) {
Ok((shader, true)) => Ok(ShaderBc::Owned(shader)),
Ok((shader, false)) => Ok(ShaderBc::Borrowed(shader)),
Err(err) => Err(pso::CreationError::Shader(err)),
}
};
let vs = build_shader(pso::Stage::Vertex, Some(&desc.shaders.vertex))?;
let ps = build_shader(pso::Stage::Fragment, desc.shaders.fragment.as_ref())?;
let gs = build_shader(pso::Stage::Geometry, desc.shaders.geometry.as_ref())?;
let ds = build_shader(pso::Stage::Domain, desc.shaders.domain.as_ref())?;
let hs = build_shader(pso::Stage::Hull, desc.shaders.hull.as_ref())?;
// Rebind vertex buffers, see native.rs for more details.
let mut vertex_bindings = [None; MAX_VERTEX_BUFFERS];
let mut vertex_strides = [0; MAX_VERTEX_BUFFERS];
for buffer in &desc.vertex_buffers {
vertex_strides[buffer.binding as usize] = buffer.stride;
}
// Fill in identity mapping where we don't need to adjust anything.
for attrib in &desc.attributes {
let binding = attrib.binding as usize;
let stride = vertex_strides[attrib.binding as usize];
if attrib.element.offset < stride {
vertex_bindings[binding] = Some(r::VertexBinding {
stride: vertex_strides[attrib.binding as usize],
offset: 0,
mapped_binding: binding,
});
}
}
// Define input element descriptions
let input_element_descs = desc
.attributes
.iter()
.filter_map(|attrib| {
let buffer_desc = match desc
.vertex_buffers
.iter()
.find(|buffer_desc| buffer_desc.binding == attrib.binding)
{
Some(buffer_desc) => buffer_desc,
None => {
error!(
"Couldn't find associated vertex buffer description {:?}",
attrib.binding
);
return Some(Err(pso::CreationError::Other));
}
};
let (slot_class, step_rate) = match buffer_desc.rate {
VertexInputRate::Vertex => {
(d3d12::D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0)
}
VertexInputRate::Instance(divisor) => {
(d3d12::D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, divisor)
}
};
let format = attrib.element.format;
// Check if we need to add a new remapping in-case the offset is
// higher than the vertex stride.
// In this case we rebase the attribute to zero offset.
let binding = attrib.binding as usize;
let stride = vertex_strides[binding];
let offset = attrib.element.offset;
let (input_slot, offset) = if stride <= offset {
// Number of input attributes may not exceed bindings, see limits.
// We will always find at least one free binding.
let mapping = vertex_bindings.iter().position(Option::is_none).unwrap();
vertex_bindings[mapping] = Some(r::VertexBinding {
stride: vertex_strides[binding],
offset: offset,
mapped_binding: binding,
});
(mapping, 0)
} else {
(binding, offset)
};
Some(Ok(d3d12::D3D12_INPUT_ELEMENT_DESC {
SemanticName: "TEXCOORD\0".as_ptr() as *const _, // Semantic name used by SPIRV-Cross
SemanticIndex: attrib.location,
Format: match conv::map_format(format) {
Some(fm) => fm,
None => {
error!("Unable to find DXGI format for {:?}", format);
return Some(Err(pso::CreationError::Other));
}
},
InputSlot: input_slot as _,
AlignedByteOffset: offset,
InputSlotClass: slot_class,
InstanceDataStepRate: step_rate as _,
}))
})
.collect::<Result<Vec<_>, _>>()?;
// TODO: check maximum number of rtvs
// Get associated subpass information
let pass = {
let subpass = &desc.subpass;
match subpass.main_pass.subpasses.get(subpass.index as usize) {
Some(subpass) => subpass,
None => return Err(pso::CreationError::InvalidSubpass(subpass.index)),
}
};
// Get color attachment formats from subpass
let (rtvs, num_rtvs) = {
let mut rtvs = [dxgiformat::DXGI_FORMAT_UNKNOWN; 8];
let mut num_rtvs = 0;
for (rtv, target) in rtvs.iter_mut().zip(pass.color_attachments.iter()) {
let format = desc.subpass.main_pass.attachments[target.0].format;
*rtv = format
.and_then(conv::map_format)
.unwrap_or(dxgiformat::DXGI_FORMAT_UNKNOWN);
num_rtvs += 1;
}
(rtvs, num_rtvs)
};
let sample_desc = dxgitype::DXGI_SAMPLE_DESC {
Count: match desc.multisampling {
Some(ref ms) => ms.rasterization_samples as _,
None => 1,
},
Quality: 0,
};
// Setup pipeline description
let pso_desc = d3d12::D3D12_GRAPHICS_PIPELINE_STATE_DESC {
pRootSignature: desc.layout.raw.as_mut_ptr(),
VS: *vs.shader(),
PS: *ps.shader(),
GS: *gs.shader(),
DS: *ds.shader(),
HS: *hs.shader(),
StreamOutput: d3d12::D3D12_STREAM_OUTPUT_DESC {
pSODeclaration: ptr::null(),
NumEntries: 0,
pBufferStrides: ptr::null(),
NumStrides: 0,
RasterizedStream: 0,
},
BlendState: d3d12::D3D12_BLEND_DESC {
AlphaToCoverageEnable: desc.multisampling.as_ref().map_or(FALSE, |ms| {
if ms.alpha_coverage {
TRUE
} else {
FALSE
}
}),
IndependentBlendEnable: TRUE,
RenderTarget: conv::map_render_targets(&desc.blender.targets),
},
SampleMask: UINT::max_value(),
RasterizerState: conv::map_rasterizer(&desc.rasterizer),
DepthStencilState: conv::map_depth_stencil(&desc.depth_stencil),
InputLayout: d3d12::D3D12_INPUT_LAYOUT_DESC {
pInputElementDescs: if input_element_descs.is_empty() {
ptr::null()
} else {
input_element_descs.as_ptr()
},
NumElements: input_element_descs.len() as u32,
},
IBStripCutValue: d3d12::D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, // TODO
PrimitiveTopologyType: conv::map_topology_type(desc.input_assembler.primitive),
NumRenderTargets: num_rtvs,
RTVFormats: rtvs,
DSVFormat: pass
.depth_stencil_attachment
.and_then(|att_ref| {
desc.subpass.main_pass.attachments[att_ref.0]
.format
.and_then(|f| conv::map_format_dsv(f.base_format().0))
})
.unwrap_or(dxgiformat::DXGI_FORMAT_UNKNOWN),
SampleDesc: sample_desc,
NodeMask: 0,
CachedPSO: d3d12::D3D12_CACHED_PIPELINE_STATE {
pCachedBlob: ptr::null(),
CachedBlobSizeInBytes: 0,
},
Flags: d3d12::D3D12_PIPELINE_STATE_FLAG_NONE,
};
let topology = conv::map_topology(&desc.input_assembler);
// Create PSO
let mut pipeline = native::PipelineState::null();
let hr = if desc.depth_stencil.depth_bounds {
// The DepthBoundsTestEnable option isn't available in the original D3D12_GRAPHICS_PIPELINE_STATE_DESC struct.
// Instead, we must use the newer subobject stream method.
let (device2, hr) = self.raw.cast::<d3d12::ID3D12Device2>();
if winerror::SUCCEEDED(hr) {
let mut pss_stream = GraphicsPipelineStateSubobjectStream::new(&pso_desc, true);
let pss_desc = d3d12::D3D12_PIPELINE_STATE_STREAM_DESC {
SizeInBytes: mem::size_of_val(&pss_stream),
pPipelineStateSubobjectStream: &mut pss_stream as *mut _ as _,
};
device2.CreatePipelineState(
&pss_desc,
&d3d12::ID3D12PipelineState::uuidof(),
pipeline.mut_void(),
)
} else {
hr
}
} else {
self.raw.clone().CreateGraphicsPipelineState(
&pso_desc,
&d3d12::ID3D12PipelineState::uuidof(),
pipeline.mut_void(),
)
};
let destroy_shader = |shader: ShaderBc| {
if let ShaderBc::Owned(bc) = shader {
bc.destroy();
}
};
destroy_shader(vs);
destroy_shader(ps);
destroy_shader(gs);
destroy_shader(hs);
destroy_shader(ds);
if winerror::SUCCEEDED(hr) {
let mut baked_states = desc.baked_states.clone();
if !desc.depth_stencil.depth_bounds {
baked_states.depth_bounds = None;
}
Ok(r::GraphicsPipeline {
raw: pipeline,
signature: desc.layout.raw,
num_parameter_slots: desc.layout.num_parameter_slots,
topology,
constants: desc.layout.constants.clone(),
vertex_bindings,
baked_states,
})
} else {
Err(pso::CreationError::Other)
}
}
unsafe fn create_compute_pipeline<'a>(
&self,
desc: &pso::ComputePipelineDesc<'a, B>,
_cache: Option<&()>,
) -> Result<r::ComputePipeline, pso::CreationError> {
let (cs, cs_destroy) = Self::extract_entry_point(
pso::Stage::Compute,
&desc.shader,
desc.layout,
&self.features,
)
.map_err(|err| pso::CreationError::Shader(err))?;
let (pipeline, hr) = self.raw.create_compute_pipeline_state(
desc.layout.raw,
native::Shader::from_blob(cs),
0,
native::CachedPSO::null(),
native::PipelineStateFlags::empty(),
);
if cs_destroy {
cs.destroy();
}
if winerror::SUCCEEDED(hr) {
Ok(r::ComputePipeline {
raw: pipeline,
signature: desc.layout.raw,
num_parameter_slots: desc.layout.num_parameter_slots,
constants: desc.layout.constants.clone(),
})
} else {
Err(pso::CreationError::Other)
}
}
unsafe fn create_framebuffer<I>(
&self,
_renderpass: &r::RenderPass,
attachments: I,
extent: image::Extent,
) -> Result<r::Framebuffer, d::OutOfMemory>
where
I: IntoIterator,
I::Item: Borrow<r::ImageView>,
{
Ok(r::Framebuffer {
attachments: attachments.into_iter().map(|att| *att.borrow()).collect(),
layers: extent.depth as _,
})
}
unsafe fn create_shader_module(
&self,
raw_data: &[u32],
) -> Result<r::ShaderModule, d::ShaderError> {
Ok(r::ShaderModule::Spirv(raw_data.into()))
}
unsafe fn create_buffer(
&self,
mut size: u64,
usage: buffer::Usage,
) -> Result<r::Buffer, buffer::CreationError> {
if usage.contains(buffer::Usage::UNIFORM) {
// Constant buffer view sizes need to be aligned.
// Coupled with the offset alignment we can enforce an aligned CBV size
// on descriptor updates.
size = (size + 255) & !255;
}
if usage.contains(buffer::Usage::TRANSFER_DST) {
// minimum of 1 word for the clear UAV
size = size.max(4);
}
let type_mask_shift = if self.private_caps.heterogeneous_resource_heaps {
MEM_TYPE_UNIVERSAL_SHIFT
} else {
MEM_TYPE_BUFFER_SHIFT
};
let requirements = memory::Requirements {
size,
alignment: d3d12::D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT as u64,
type_mask: MEM_TYPE_MASK << type_mask_shift,
};
Ok(r::Buffer::Unbound(r::BufferUnbound {
requirements,
usage,
}))
}
unsafe fn get_buffer_requirements(&self, buffer: &r::Buffer) -> Requirements {
match buffer {
r::Buffer::Unbound(b) => b.requirements,
r::Buffer::Bound(b) => b.requirements,
}
}
unsafe fn bind_buffer_memory(
&self,
memory: &r::Memory,
offset: u64,
buffer: &mut r::Buffer,
) -> Result<(), d::BindError> {
let buffer_unbound = *buffer.expect_unbound();
if buffer_unbound.requirements.type_mask & (1 << memory.type_id) == 0 {
error!(
"Bind memory failure: supported mask 0x{:x}, given id {}",
buffer_unbound.requirements.type_mask, memory.type_id
);
return Err(d::BindError::WrongMemory);
}
if offset + buffer_unbound.requirements.size > memory.size {
return Err(d::BindError::OutOfBounds);
}
let mut resource = native::Resource::null();
let desc = d3d12::D3D12_RESOURCE_DESC {
Dimension: d3d12::D3D12_RESOURCE_DIMENSION_BUFFER,
Alignment: 0,
Width: buffer_unbound.requirements.size,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
Format: dxgiformat::DXGI_FORMAT_UNKNOWN,
SampleDesc: dxgitype::DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
Layout: d3d12::D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
Flags: conv::map_buffer_flags(buffer_unbound.usage),
};
assert_eq!(
winerror::S_OK,
self.raw.clone().CreatePlacedResource(
memory.heap.as_mut_ptr(),
offset,
&desc,
d3d12::D3D12_RESOURCE_STATE_COMMON,
ptr::null(),
&d3d12::ID3D12Resource::uuidof(),
resource.mut_void(),
)
);
let clear_uav = if buffer_unbound.usage.contains(buffer::Usage::TRANSFER_DST) {
let handle = self.srv_uav_pool.lock().unwrap().alloc_handle();
let mut view_desc = d3d12::D3D12_UNORDERED_ACCESS_VIEW_DESC {
Format: dxgiformat::DXGI_FORMAT_R32_TYPELESS,
ViewDimension: d3d12::D3D12_UAV_DIMENSION_BUFFER,
u: mem::zeroed(),
};
*view_desc.u.Buffer_mut() = d3d12::D3D12_BUFFER_UAV {
FirstElement: 0,
NumElements: (buffer_unbound.requirements.size / 4) as _,
StructureByteStride: 0,
CounterOffsetInBytes: 0,
Flags: d3d12::D3D12_BUFFER_UAV_FLAG_RAW,
};
self.raw.CreateUnorderedAccessView(
resource.as_mut_ptr(),
ptr::null_mut(),
&view_desc,
handle,
);
Some(handle)
} else {
None
};
*buffer = r::Buffer::Bound(r::BufferBound {
resource,
requirements: buffer_unbound.requirements,
clear_uav,
});
Ok(())
}
unsafe fn create_buffer_view(
&self,
buffer: &r::Buffer,
format: Option<format::Format>,
sub: buffer::SubRange,
) -> Result<r::BufferView, buffer::ViewCreationError> {
let buffer = buffer.expect_bound();
let buffer_features = {
let idx = format.map(|fmt| fmt as usize).unwrap_or(0);
self.format_properties.get(idx).properties.buffer_features
};
let (format, format_desc) = match format.and_then(conv::map_format) {
Some(fmt) => (fmt, format.unwrap().surface_desc()),
None => return Err(buffer::ViewCreationError::UnsupportedFormat(format)),
};
let start = sub.offset;
let size = sub.size.unwrap_or(buffer.requirements.size - start);
let bytes_per_texel = (format_desc.bits / 8) as u64;
// Check if it adheres to the texel buffer offset limit
assert_eq!(start % bytes_per_texel, 0);
let first_element = start / bytes_per_texel;
let num_elements = size / bytes_per_texel; // rounds down to next smaller size
let handle_srv = if buffer_features.contains(format::BufferFeature::UNIFORM_TEXEL) {
let mut desc = d3d12::D3D12_SHADER_RESOURCE_VIEW_DESC {
Format: format,
ViewDimension: d3d12::D3D12_SRV_DIMENSION_BUFFER,
Shader4ComponentMapping: IDENTITY_MAPPING,
u: mem::zeroed(),
};
*desc.u.Buffer_mut() = d3d12::D3D12_BUFFER_SRV {
FirstElement: first_element,
NumElements: num_elements as _,
StructureByteStride: bytes_per_texel as _,
Flags: d3d12::D3D12_BUFFER_SRV_FLAG_NONE,
};
let handle = self.srv_uav_pool.lock().unwrap().alloc_handle();
self.raw
.clone()
.CreateShaderResourceView(buffer.resource.as_mut_ptr(), &desc, handle);
handle
} else {
d3d12::D3D12_CPU_DESCRIPTOR_HANDLE { ptr: 0 }
};
let handle_uav = if buffer_features.intersects(
format::BufferFeature::STORAGE_TEXEL | format::BufferFeature::STORAGE_TEXEL_ATOMIC,
) {
let mut desc = d3d12::D3D12_UNORDERED_ACCESS_VIEW_DESC {
Format: format,
ViewDimension: d3d12::D3D12_UAV_DIMENSION_BUFFER,
u: mem::zeroed(),
};
*desc.u.Buffer_mut() = d3d12::D3D12_BUFFER_UAV {
FirstElement: first_element,
NumElements: num_elements as _,
StructureByteStride: bytes_per_texel as _,
Flags: d3d12::D3D12_BUFFER_UAV_FLAG_NONE,
CounterOffsetInBytes: 0,
};
let handle = self.srv_uav_pool.lock().unwrap().alloc_handle();
self.raw.clone().CreateUnorderedAccessView(
buffer.resource.as_mut_ptr(),
ptr::null_mut(),
&desc,
handle,
);
handle
} else {
d3d12::D3D12_CPU_DESCRIPTOR_HANDLE { ptr: 0 }
};
return Ok(r::BufferView {
handle_srv,
handle_uav,
});
}
unsafe fn create_image(
&self,
kind: image::Kind,
mip_levels: image::Level,
format: format::Format,
tiling: image::Tiling,
usage: image::Usage,
view_caps: image::ViewCapabilities,
) -> Result<r::Image, image::CreationError> {
assert!(mip_levels <= kind.num_levels());
let base_format = format.base_format();
let format_desc = base_format.0.desc();
let bytes_per_block = (format_desc.bits / 8) as _;
let block_dim = format_desc.dim;
let extent = kind.extent();
let format_info = self.format_properties.get(format as usize);
let (layout, features) = match tiling {
image::Tiling::Optimal => (
d3d12::D3D12_TEXTURE_LAYOUT_UNKNOWN,
format_info.properties.optimal_tiling,
),
image::Tiling::Linear => (
d3d12::D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
format_info.properties.linear_tiling,
),
};
if format_info.sample_count_mask & kind.num_samples() == 0 {
return Err(image::CreationError::Samples(kind.num_samples()));
}
let desc = d3d12::D3D12_RESOURCE_DESC {
Dimension: match kind {
image::Kind::D1(..) => d3d12::D3D12_RESOURCE_DIMENSION_TEXTURE1D,
image::Kind::D2(..) => d3d12::D3D12_RESOURCE_DIMENSION_TEXTURE2D,
image::Kind::D3(..) => d3d12::D3D12_RESOURCE_DIMENSION_TEXTURE3D,
},
Alignment: 0,
Width: extent.width as _,
Height: extent.height as _,
DepthOrArraySize: if extent.depth > 1 {
extent.depth as _
} else {
kind.num_layers() as _
},
MipLevels: mip_levels as _,
Format: match conv::map_surface_type(base_format.0) {
Some(format) => format,
None => return Err(image::CreationError::Format(format)),
},
SampleDesc: dxgitype::DXGI_SAMPLE_DESC {
Count: kind.num_samples() as _,
Quality: 0,
},
Layout: layout,
Flags: conv::map_image_flags(usage, features),
};
let alloc_info = self.raw.clone().GetResourceAllocationInfo(0, 1, &desc);
// Image usages which require RT/DS heap due to internal implementation.
let target_usage = image::Usage::COLOR_ATTACHMENT
| image::Usage::DEPTH_STENCIL_ATTACHMENT
| image::Usage::TRANSFER_DST;
let type_mask_shift = if self.private_caps.heterogeneous_resource_heaps {
MEM_TYPE_UNIVERSAL_SHIFT
} else if usage.intersects(target_usage) {
MEM_TYPE_TARGET_SHIFT
} else {
MEM_TYPE_IMAGE_SHIFT
};
Ok(r::Image::Unbound(r::ImageUnbound {
view_format: conv::map_format(format),
dsv_format: conv::map_format_dsv(base_format.0),
desc,
requirements: memory::Requirements {
size: alloc_info.SizeInBytes,
alignment: alloc_info.Alignment,
type_mask: MEM_TYPE_MASK << type_mask_shift,
},
format,
kind,
usage,
tiling,
view_caps,
bytes_per_block,
block_dim,
}))
}
unsafe fn get_image_requirements(&self, image: &r::Image) -> Requirements {
match image {
r::Image::Bound(i) => i.requirements,
r::Image::Unbound(i) => i.requirements,
}
}
unsafe fn get_image_subresource_footprint(
&self,
image: &r::Image,
sub: image::Subresource,
) -> image::SubresourceFootprint {
let mut num_rows = 0;
let mut total_bytes = 0;
let _desc = match image {
r::Image::Bound(i) => i.descriptor,
r::Image::Unbound(i) => i.desc,
};
let footprint = {
let mut footprint = mem::zeroed();
self.raw.GetCopyableFootprints(
image.get_desc(),
image.calc_subresource(sub.level as _, sub.layer as _, 0),
1,
0,
&mut footprint,
&mut num_rows,
ptr::null_mut(), // row size in bytes
&mut total_bytes,
);
footprint
};
let depth_pitch = (footprint.Footprint.RowPitch * num_rows) as buffer::Offset;
let array_pitch = footprint.Footprint.Depth as buffer::Offset * depth_pitch;
image::SubresourceFootprint {
slice: footprint.Offset .. footprint.Offset + total_bytes,
row_pitch: footprint.Footprint.RowPitch as _,
depth_pitch,
array_pitch,
}
}
unsafe fn bind_image_memory(
&self,
memory: &r::Memory,
offset: u64,
image: &mut r::Image,
) -> Result<(), d::BindError> {
use self::image::Usage;
let image_unbound = *image.expect_unbound();
if image_unbound.requirements.type_mask & (1 << memory.type_id) == 0 {
error!(
"Bind memory failure: supported mask 0x{:x}, given id {}",
image_unbound.requirements.type_mask, memory.type_id
);
return Err(d::BindError::WrongMemory);
}
if offset + image_unbound.requirements.size > memory.size {
return Err(d::BindError::OutOfBounds);
}
let mut resource = native::Resource::null();
let num_layers = image_unbound.kind.num_layers();
assert_eq!(
winerror::S_OK,
self.raw.clone().CreatePlacedResource(
memory.heap.as_mut_ptr(),
offset,
&image_unbound.desc,
d3d12::D3D12_RESOURCE_STATE_COMMON,
ptr::null(),
&d3d12::ID3D12Resource::uuidof(),
resource.mut_void(),
)
);
let info = ViewInfo {
resource,
kind: image_unbound.kind,
caps: image::ViewCapabilities::empty(),
view_kind: match image_unbound.kind {
image::Kind::D1(..) => image::ViewKind::D1Array,
image::Kind::D2(..) => image::ViewKind::D2Array,
image::Kind::D3(..) => image::ViewKind::D3,
},
format: image_unbound.desc.Format,
component_mapping: IDENTITY_MAPPING,
range: image::SubresourceRange {
aspects: Aspects::empty(),
levels: 0 .. 0,
layers: 0 .. 0,
},
};
//TODO: the clear_Xv is incomplete. We should support clearing images created without XXX_ATTACHMENT usage.
// for this, we need to check the format and force the `RENDER_TARGET` flag behind the user's back
// if the format supports being rendered into, allowing us to create clear_Xv
let format_properties = self
.format_properties
.get(image_unbound.format as usize)
.properties;
let props = match image_unbound.tiling {
image::Tiling::Optimal => format_properties.optimal_tiling,
image::Tiling::Linear => format_properties.linear_tiling,
};
let can_clear_color = image_unbound
.usage
.intersects(Usage::TRANSFER_DST | Usage::COLOR_ATTACHMENT)
&& props.contains(format::ImageFeature::COLOR_ATTACHMENT);
let can_clear_depth = image_unbound
.usage
.intersects(Usage::TRANSFER_DST | Usage::DEPTH_STENCIL_ATTACHMENT)
&& props.contains(format::ImageFeature::DEPTH_STENCIL_ATTACHMENT);
let aspects = image_unbound.format.surface_desc().aspects;
*image = r::Image::Bound(r::ImageBound {
resource: resource,
place: r::Place::Heap {
raw: memory.heap.clone(),
offset,
},
surface_type: image_unbound.format.base_format().0,
kind: image_unbound.kind,
usage: image_unbound.usage,
default_view_format: image_unbound.view_format,
view_caps: image_unbound.view_caps,
descriptor: image_unbound.desc,
bytes_per_block: image_unbound.bytes_per_block,
block_dim: image_unbound.block_dim,
clear_cv: if aspects.contains(Aspects::COLOR) && can_clear_color {
let format = image_unbound.view_format.unwrap();
(0 .. num_layers)
.map(|layer| {
self.view_image_as_render_target(ViewInfo {
format,
range: image::SubresourceRange {
aspects: Aspects::COLOR,
levels: 0 .. 1, //TODO?
layers: layer .. layer + 1,
},
..info.clone()
})
.unwrap()
})
.collect()
} else {
Vec::new()
},
clear_dv: if aspects.contains(Aspects::DEPTH) && can_clear_depth {
let format = image_unbound.dsv_format.unwrap();
(0 .. num_layers)
.map(|layer| {
self.view_image_as_depth_stencil(ViewInfo {
format,
range: image::SubresourceRange {
aspects: Aspects::DEPTH,
levels: 0 .. 1, //TODO?
layers: layer .. layer + 1,
},
..info.clone()
})
.unwrap()
})
.collect()
} else {
Vec::new()
},
clear_sv: if aspects.contains(Aspects::STENCIL) && can_clear_depth {
let format = image_unbound.dsv_format.unwrap();
(0 .. num_layers)
.map(|layer| {
self.view_image_as_depth_stencil(ViewInfo {
format,
range: image::SubresourceRange {
aspects: Aspects::STENCIL,
levels: 0 .. 1, //TODO?
layers: layer .. layer + 1,
},
..info.clone()
})
.unwrap()
})
.collect()
} else {
Vec::new()
},
requirements: image_unbound.requirements,
});
Ok(())
}
unsafe fn create_image_view(
&self,
image: &r::Image,
view_kind: image::ViewKind,
format: format::Format,
swizzle: format::Swizzle,
range: image::SubresourceRange,
) -> Result<r::ImageView, image::ViewCreationError> {
let image = image.expect_bound();
let is_array = image.kind.num_layers() > 1;
let mip_levels = (range.levels.start, range.levels.end);
let layers = (range.layers.start, range.layers.end);
let info = ViewInfo {
resource: image.resource,
kind: image.kind,
caps: image.view_caps,
// D3D12 doesn't allow looking at a single slice of an array as a non-array
view_kind: if is_array && view_kind == image::ViewKind::D2 {
image::ViewKind::D2Array
} else if is_array && view_kind == image::ViewKind::D1 {
image::ViewKind::D1Array
} else {
view_kind
},
format: conv::map_format(format).ok_or(image::ViewCreationError::BadFormat(format))?,
component_mapping: conv::map_swizzle(swizzle),
range,
};
//Note: we allow RTV/DSV/SRV/UAV views to fail to be created here,
// because we don't know if the user will even need to use them.
Ok(r::ImageView {
resource: image.resource,
handle_srv: if image
.usage
.intersects(image::Usage::SAMPLED | image::Usage::INPUT_ATTACHMENT)
{
self.view_image_as_shader_resource(info.clone()).ok()
} else {
None
},
handle_rtv: if image.usage.contains(image::Usage::COLOR_ATTACHMENT) {
self.view_image_as_render_target(info.clone()).ok()
} else {
None
},
handle_uav: if image.usage.contains(image::Usage::STORAGE) {
self.view_image_as_storage(info.clone()).ok()
} else {
None
},
handle_dsv: if image.usage.contains(image::Usage::DEPTH_STENCIL_ATTACHMENT) {
match conv::map_format_dsv(format.base_format().0) {
Some(dsv_format) => self
.view_image_as_depth_stencil(ViewInfo {
format: dsv_format,
..info
})
.ok(),
None => None,
}
} else {
None
},
dxgi_format: image.default_view_format.unwrap(),
num_levels: image.descriptor.MipLevels as image::Level,
mip_levels,
layers,
kind: info.kind,
})
}
unsafe fn create_sampler(
&self,
info: &image::SamplerDesc,
) -> Result<r::Sampler, d::AllocationError> {
assert!(info.normalized);
let handle = self.sampler_pool.lock().unwrap().alloc_handle();
let op = match info.comparison {
Some(_) => d3d12::D3D12_FILTER_REDUCTION_TYPE_COMPARISON,
None => d3d12::D3D12_FILTER_REDUCTION_TYPE_STANDARD,
};
self.raw.create_sampler(
handle,
conv::map_filter(
info.mag_filter,
info.min_filter,
info.mip_filter,
op,
info.anisotropy_clamp,
),
[
conv::map_wrap(info.wrap_mode.0),
conv::map_wrap(info.wrap_mode.1),
conv::map_wrap(info.wrap_mode.2),
],
info.lod_bias.0,
info.anisotropy_clamp.map_or(0, |aniso| aniso as u32),
conv::map_comparison(info.comparison.unwrap_or(pso::Comparison::Always)),
info.border.into(),
info.lod_range.start.0 .. info.lod_range.end.0,
);
Ok(r::Sampler { handle })
}
unsafe fn create_descriptor_pool<I>(
&self,
max_sets: usize,
descriptor_pools: I,
_flags: pso::DescriptorPoolCreateFlags,
) -> Result<r::DescriptorPool, d::OutOfMemory>
where
I: IntoIterator,
I::Item: Borrow<pso::DescriptorRangeDesc>,
{
// Descriptor pools are implemented as slices of the global descriptor heaps.
// A descriptor pool will occupy a contiguous space in each heap (CBV/SRV/UAV and Sampler) depending
// on the total requested amount of descriptors.
let mut num_srv_cbv_uav = 0;
let mut num_samplers = 0;
let descriptor_pools = descriptor_pools
.into_iter()
.map(|desc| *desc.borrow())
.collect::<Vec<_>>();
info!("create_descriptor_pool with {} max sets", max_sets);
for desc in &descriptor_pools {
let content = r::DescriptorContent::from(desc.ty);
debug!("\tcontent {:?}", content);
if content.contains(r::DescriptorContent::CBV) {
num_srv_cbv_uav += desc.count;
}
if content.contains(r::DescriptorContent::SRV) {
num_srv_cbv_uav += desc.count;
}
if content.contains(r::DescriptorContent::UAV) {
num_srv_cbv_uav += desc.count;
}
if content.contains(r::DescriptorContent::SAMPLER) {
num_samplers += desc.count;
}
}
info!(
"total {} views and {} samplers",
num_srv_cbv_uav, num_samplers
);
// Allocate slices of the global GPU descriptor heaps.
let heap_srv_cbv_uav = {
let mut heap_srv_cbv_uav = self.heap_srv_cbv_uav.lock().unwrap();
let range = match num_srv_cbv_uav {
0 => 0 .. 0,
_ => heap_srv_cbv_uav
.range_allocator
.allocate_range(num_srv_cbv_uav as _)
.unwrap(), // TODO: error/resize
};
r::DescriptorHeapSlice {
heap: heap_srv_cbv_uav.raw.clone(),
handle_size: heap_srv_cbv_uav.handle_size as _,
range_allocator: RangeAllocator::new(range),
start: heap_srv_cbv_uav.start,
}
};
let heap_sampler = {
let mut heap_sampler = self.heap_sampler.lock().unwrap();
let range = match num_samplers {
0 => 0 .. 0,
_ => heap_sampler
.range_allocator
.allocate_range(num_samplers as _)
.unwrap(), // TODO: error/resize
};
r::DescriptorHeapSlice {
heap: heap_sampler.raw.clone(),
handle_size: heap_sampler.handle_size as _,
range_allocator: RangeAllocator::new(range),
start: heap_sampler.start,
}
};
Ok(r::DescriptorPool {
heap_srv_cbv_uav,
heap_sampler,
pools: descriptor_pools,
max_size: max_sets as _,
})
}
unsafe fn create_descriptor_set_layout<I, J>(
&self,
bindings: I,
_immutable_samplers: J,
) -> Result<r::DescriptorSetLayout, d::OutOfMemory>
where
I: IntoIterator,
I::Item: Borrow<pso::DescriptorSetLayoutBinding>,
J: IntoIterator,
J::Item: Borrow<r::Sampler>,
{
Ok(r::DescriptorSetLayout {
bindings: bindings.into_iter().map(|b| b.borrow().clone()).collect(),
})
}
unsafe fn write_descriptor_sets<'a, I, J>(&self, write_iter: I)
where
I: IntoIterator<Item = pso::DescriptorSetWrite<'a, B, J>>,
J: IntoIterator,
J::Item: Borrow<pso::Descriptor<'a, B>>,
{
let mut descriptor_update_pools = self.descriptor_update_pools.lock().unwrap();
let mut update_pool_index = 0;
//TODO: combine destination ranges
let mut dst_samplers = Vec::new();
let mut dst_views = Vec::new();
let mut src_samplers = Vec::new();
let mut src_views = Vec::new();
let mut num_samplers = Vec::new();
let mut num_views = Vec::new();
debug!("write_descriptor_sets");
for write in write_iter {
let mut offset = write.array_offset as u64;
let mut target_binding = write.binding as usize;
let mut bind_info = &write.set.binding_infos[target_binding];
debug!(
"\t{:?} binding {} array offset {}",
bind_info, target_binding, offset
);
for descriptor in write.descriptors {
// spill over the writes onto the next binding
while offset >= bind_info.count {
assert_eq!(offset, bind_info.count);
target_binding += 1;
bind_info = &write.set.binding_infos[target_binding];
offset = 0;
}
let mut src_cbv = None;
let mut src_srv = None;
let mut src_uav = None;
let mut src_sampler = None;
match *descriptor.borrow() {
pso::Descriptor::Buffer(buffer, ref sub) => {
let buffer = buffer.expect_bound();
if bind_info.content.is_dynamic() {
// Root Descriptor
let buffer_address = (*buffer.resource).GetGPUVirtualAddress();
// Descriptor sets need to be externally synchronized according to specification
let dynamic_descriptors = &mut *bind_info.dynamic_descriptors.get();
dynamic_descriptors[offset as usize].gpu_buffer_location =
buffer_address + sub.offset;
} else {
// Descriptor table
if update_pool_index == descriptor_update_pools.len() {
let max_size = 1u64 << 12; //arbitrary
descriptor_update_pools.push(descriptors_cpu::HeapLinear::new(
self.raw,
native::DescriptorHeapType::CbvSrvUav,
max_size as _,
));
}
let mut heap = descriptor_update_pools.pop().unwrap();
let size = sub.size_to(buffer.requirements.size);
if bind_info.content.contains(r::DescriptorContent::CBV) {
// Making the size field of buffer requirements for uniform
// buffers a multiple of 256 and setting the required offset
// alignment to 256 allows us to patch the size here.
// We can always enforce the size to be aligned to 256 for
// CBVs without going out-of-bounds.
let desc = d3d12::D3D12_CONSTANT_BUFFER_VIEW_DESC {
BufferLocation: (*buffer.resource).GetGPUVirtualAddress()
+ sub.offset,
SizeInBytes: ((size + 0xFF) & !0xFF) as _,
};
let handle = heap.alloc_handle();
self.raw.CreateConstantBufferView(&desc, handle);
src_cbv = Some(handle);
}
if bind_info.content.contains(r::DescriptorContent::SRV) {
assert_eq!(size % 4, 0);
let mut desc = d3d12::D3D12_SHADER_RESOURCE_VIEW_DESC {
Format: dxgiformat::DXGI_FORMAT_R32_TYPELESS,
Shader4ComponentMapping: IDENTITY_MAPPING,
ViewDimension: d3d12::D3D12_SRV_DIMENSION_BUFFER,
u: mem::zeroed(),
};
*desc.u.Buffer_mut() = d3d12::D3D12_BUFFER_SRV {
FirstElement: sub.offset as _,
NumElements: (size / 4) as _,
StructureByteStride: 0,
Flags: d3d12::D3D12_BUFFER_SRV_FLAG_RAW,
};
let handle = heap.alloc_handle();
self.raw.CreateShaderResourceView(
buffer.resource.as_mut_ptr(),
&desc,
handle,
);
src_srv = Some(handle);
}
if bind_info.content.contains(r::DescriptorContent::UAV) {
assert_eq!(size % 4, 0);
let mut desc = d3d12::D3D12_UNORDERED_ACCESS_VIEW_DESC {
Format: dxgiformat::DXGI_FORMAT_R32_TYPELESS,
ViewDimension: d3d12::D3D12_UAV_DIMENSION_BUFFER,
u: mem::zeroed(),
};
*desc.u.Buffer_mut() = d3d12::D3D12_BUFFER_UAV {
FirstElement: sub.offset as _,
NumElements: (size / 4) as _,
StructureByteStride: 0,
CounterOffsetInBytes: 0,
Flags: d3d12::D3D12_BUFFER_UAV_FLAG_RAW,
};
if heap.is_full() {
// pool is full, move to the next one
update_pool_index += 1;
let max_size = 1u64 << 12; //arbitrary
let full_heap = mem::replace(
&mut heap,
descriptors_cpu::HeapLinear::new(
self.raw,
native::DescriptorHeapType::CbvSrvUav,
max_size as _,
),
);
descriptor_update_pools.push(full_heap);
}
let handle = heap.alloc_handle();
self.raw.CreateUnorderedAccessView(
buffer.resource.as_mut_ptr(),
ptr::null_mut(),
&desc,
handle,
);
src_uav = Some(handle);
}
// always leave this block of code prepared
if heap.is_full() {
// pool is full, move to the next one
update_pool_index += 1;
}
descriptor_update_pools.push(heap);
}
}
pso::Descriptor::Image(image, _layout) => {
if bind_info.content.contains(r::DescriptorContent::SRV) {
src_srv = image.handle_srv;
}
if bind_info.content.contains(r::DescriptorContent::UAV) {
src_uav = image.handle_uav;
}
}
pso::Descriptor::CombinedImageSampler(image, _layout, sampler) => {
src_srv = image.handle_srv;
src_sampler = Some(sampler.handle);
}
pso::Descriptor::Sampler(sampler) => {
src_sampler = Some(sampler.handle);
}
pso::Descriptor::TexelBuffer(buffer_view) => {
if bind_info.content.contains(r::DescriptorContent::SRV) {
let handle = buffer_view.handle_srv;
src_srv = Some(handle);
if handle.ptr == 0 {
error!("SRV handle of the storage texel buffer is zero (not supported by specified format).");
}
}
if bind_info.content.contains(r::DescriptorContent::UAV) {
let handle = buffer_view.handle_uav;
src_uav = Some(handle);
if handle.ptr == 0 {
error!("UAV handle of the storage texel buffer is zero (not supported by specified format).");
}
}
}
}
if let Some(handle) = src_cbv {
trace!("\tcbv offset {}", offset);
src_views.push(handle);
dst_views.push(bind_info.view_range.as_ref().unwrap().at(offset));
num_views.push(1);
}
if let Some(handle) = src_srv {
trace!("\tsrv offset {}", offset);
src_views.push(handle);
dst_views.push(bind_info.view_range.as_ref().unwrap().at(offset));
num_views.push(1);
}
if let Some(handle) = src_uav {
let uav_offset = if bind_info.content.contains(r::DescriptorContent::SRV) {
bind_info.count + offset
} else {
offset
};
trace!("\tuav offset {}", uav_offset);
src_views.push(handle);
dst_views.push(bind_info.view_range.as_ref().unwrap().at(uav_offset));
num_views.push(1);
}
if let Some(handle) = src_sampler {
trace!("\tsampler offset {}", offset);
src_samplers.push(handle);
dst_samplers.push(bind_info.sampler_range.as_ref().unwrap().at(offset));
num_samplers.push(1);
}
offset += 1;
}
}
if !num_views.is_empty() {
self.raw.clone().CopyDescriptors(
dst_views.len() as u32,
dst_views.as_ptr(),
num_views.as_ptr(),
src_views.len() as u32,
src_views.as_ptr(),
num_views.as_ptr(),
d3d12::D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
);
}
if !num_samplers.is_empty() {
self.raw.clone().CopyDescriptors(
dst_samplers.len() as u32,
dst_samplers.as_ptr(),
num_samplers.as_ptr(),
src_samplers.len() as u32,
src_samplers.as_ptr(),
num_samplers.as_ptr(),
d3d12::D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER,
);
}
// reset the temporary CPU-size descriptor pools
for buffer_desc_pool in descriptor_update_pools.iter_mut() {
buffer_desc_pool.clear();
}
}
unsafe fn copy_descriptor_sets<'a, I>(&self, copy_iter: I)
where
I: IntoIterator,
I::Item: Borrow<pso::DescriptorSetCopy<'a, B>>,
{
let mut dst_samplers = Vec::new();
let mut dst_views = Vec::new();
let mut src_samplers = Vec::new();
let mut src_views = Vec::new();
let mut num_samplers = Vec::new();
let mut num_views = Vec::new();
for copy_wrap in copy_iter {
let copy = copy_wrap.borrow();
let src_info = ©.src_set.binding_infos[copy.src_binding as usize];
let dst_info = ©.dst_set.binding_infos[copy.dst_binding as usize];
if let (Some(src_range), Some(dst_range)) =
(src_info.view_range.as_ref(), dst_info.view_range.as_ref())
{
assert!(copy.src_array_offset + copy.count <= src_range.count as usize);
assert!(copy.dst_array_offset + copy.count <= dst_range.count as usize);
src_views.push(src_range.at(copy.src_array_offset as _));
dst_views.push(dst_range.at(copy.dst_array_offset as _));
num_views.push(copy.count as u32);
if (src_info.content & dst_info.content)
.contains(r::DescriptorContent::SRV | r::DescriptorContent::UAV)
{
assert!(
src_info.count as usize + copy.src_array_offset + copy.count
<= src_range.count as usize
);
assert!(
dst_info.count as usize + copy.dst_array_offset + copy.count
<= dst_range.count as usize
);
src_views.push(src_range.at(src_info.count + copy.src_array_offset as u64));
dst_views.push(dst_range.at(dst_info.count + copy.dst_array_offset as u64));
num_views.push(copy.count as u32);
}
}
if let (Some(src_range), Some(dst_range)) = (
src_info.sampler_range.as_ref(),
dst_info.sampler_range.as_ref(),
) {
assert!(copy.src_array_offset + copy.count <= src_range.count as usize);
assert!(copy.dst_array_offset + copy.count <= dst_range.count as usize);
src_samplers.push(src_range.at(copy.src_array_offset as _));
dst_samplers.push(dst_range.at(copy.dst_array_offset as _));
num_samplers.push(copy.count as u32);
}
}
if !num_views.is_empty() {
self.raw.clone().CopyDescriptors(
dst_views.len() as u32,
dst_views.as_ptr(),
num_views.as_ptr(),
src_views.len() as u32,
src_views.as_ptr(),
num_views.as_ptr(),
d3d12::D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
);
}
if !num_samplers.is_empty() {
self.raw.clone().CopyDescriptors(
dst_samplers.len() as u32,
dst_samplers.as_ptr(),
num_samplers.as_ptr(),
src_samplers.len() as u32,
src_samplers.as_ptr(),
num_samplers.as_ptr(),
d3d12::D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER,
);
}
}
unsafe fn map_memory(
&self,
memory: &r::Memory,
segment: memory::Segment,
) -> Result<*mut u8, d::MapError> {
let mem = memory
.resource
.expect("Memory not created with a memory type exposing `CPU_VISIBLE`");
let mut ptr = ptr::null_mut();
assert_eq!(
winerror::S_OK,
(*mem).Map(0, &d3d12::D3D12_RANGE { Begin: 0, End: 0 }, &mut ptr)
);
ptr = ptr.offset(segment.offset as isize);
Ok(ptr as *mut _)
}
unsafe fn unmap_memory(&self, memory: &r::Memory) {
if let Some(mem) = memory.resource {
(*mem).Unmap(0, &d3d12::D3D12_RANGE { Begin: 0, End: 0 });
}
}
unsafe fn flush_mapped_memory_ranges<'a, I>(&self, ranges: I) -> Result<(), d::OutOfMemory>
where
I: IntoIterator,
I::Item: Borrow<(&'a r::Memory, memory::Segment)>,
{
for range in ranges {
let &(ref memory, ref segment) = range.borrow();
if let Some(mem) = memory.resource {
// map and immediately unmap, hoping that dx12 drivers internally cache
// currently mapped buffers.
assert_eq!(
winerror::S_OK,
(*mem).Map(0, &d3d12::D3D12_RANGE { Begin: 0, End: 0 }, ptr::null_mut())
);
let start = segment.offset;
let end = segment.size.map_or(memory.size, |s| start + s); // TODO: only need to be end of current mapping
(*mem).Unmap(
0,
&d3d12::D3D12_RANGE {
Begin: start as _,
End: end as _,
},
);
}
}
Ok(())
}
unsafe fn invalidate_mapped_memory_ranges<'a, I>(&self, ranges: I) -> Result<(), d::OutOfMemory>
where
I: IntoIterator,
I::Item: Borrow<(&'a r::Memory, memory::Segment)>,
{
for range in ranges {
let &(ref memory, ref segment) = range.borrow();
if let Some(mem) = memory.resource {
let start = segment.offset;
let end = segment.size.map_or(memory.size, |s| start + s); // TODO: only need to be end of current mapping
// map and immediately unmap, hoping that dx12 drivers internally cache
// currently mapped buffers.
assert_eq!(
winerror::S_OK,
(*mem).Map(
0,
&d3d12::D3D12_RANGE {
Begin: start as _,
End: end as _,
},
ptr::null_mut(),
)
);
(*mem).Unmap(0, &d3d12::D3D12_RANGE { Begin: 0, End: 0 });
}
}
Ok(())
}
fn create_semaphore(&self) -> Result<r::Semaphore, d::OutOfMemory> {
let fence = self.create_fence(false)?;
Ok(r::Semaphore { raw: fence.raw })
}
fn create_fence(&self, signalled: bool) -> Result<r::Fence, d::OutOfMemory> {
Ok(r::Fence {
raw: self.create_raw_fence(signalled),
})
}
unsafe fn reset_fence(&self, fence: &r::Fence) -> Result<(), d::OutOfMemory> {
assert_eq!(winerror::S_OK, fence.raw.signal(0));
Ok(())
}
unsafe fn wait_for_fences<I>(
&self,
fences: I,
wait: d::WaitFor,
timeout_ns: u64,
) -> Result<bool, d::OomOrDeviceLost>
where
I: IntoIterator,
I::Item: Borrow<r::Fence>,
{
let fences = fences.into_iter().collect::<Vec<_>>();
let mut events = self.events.lock().unwrap();
for _ in events.len() .. fences.len() {
events.push(native::Event::create(false, false));
}
for (&event, fence) in events.iter().zip(fences.iter()) {
synchapi::ResetEvent(event.0);
assert_eq!(
winerror::S_OK,
fence.borrow().raw.set_event_on_completion(event, 1)
);
}
let all = match wait {
d::WaitFor::Any => FALSE,
d::WaitFor::All => TRUE,
};
let hr = {
// This block handles overflow when converting to u32 and always rounds up
// The Vulkan specification allows to wait more than specified
let timeout_ms = {
if timeout_ns > (<u32>::max_value() as u64) * 1_000_000 {
<u32>::max_value()
} else {
((timeout_ns + 999_999) / 1_000_000) as u32
}
};
synchapi::WaitForMultipleObjects(
fences.len() as u32,
events.as_ptr() as *const _,
all,
timeout_ms,
)
};
const WAIT_OBJECT_LAST: u32 = winbase::WAIT_OBJECT_0 + winnt::MAXIMUM_WAIT_OBJECTS;
const WAIT_ABANDONED_LAST: u32 = winbase::WAIT_ABANDONED_0 + winnt::MAXIMUM_WAIT_OBJECTS;
match hr {
winbase::WAIT_FAILED => Err(d::OomOrDeviceLost::DeviceLost(d::DeviceLost)),
winbase::WAIT_OBJECT_0 ..= WAIT_OBJECT_LAST => Ok(true),
winbase::WAIT_ABANDONED_0 ..= WAIT_ABANDONED_LAST => Ok(true), //TODO?
winerror::WAIT_TIMEOUT => Ok(false),
_ => panic!("Unexpected wait status 0x{:X}", hr),
}
}
unsafe fn get_fence_status(&self, fence: &r::Fence) -> Result<bool, d::DeviceLost> {
match fence.raw.GetCompletedValue() {
0 => Ok(false),
1 => Ok(true),
_ => Err(d::DeviceLost),
}
}
fn create_event(&self) -> Result<(), d::OutOfMemory> {
unimplemented!()
}
unsafe fn get_event_status(&self, _event: &()) -> Result<bool, d::OomOrDeviceLost> {
unimplemented!()
}
unsafe fn set_event(&self, _event: &()) -> Result<(), d::OutOfMemory> {
unimplemented!()
}
unsafe fn reset_event(&self, _event: &()) -> Result<(), d::OutOfMemory> {
unimplemented!()
}
unsafe fn free_memory(&self, memory: r::Memory) {
memory.heap.destroy();
if let Some(buffer) = memory.resource {
buffer.destroy();
}
}
unsafe fn create_query_pool(
&self,
query_ty: query::Type,
count: query::Id,
) -> Result<r::QueryPool, query::CreationError> {
let heap_ty = match query_ty {
query::Type::Occlusion => native::QueryHeapType::Occlusion,
query::Type::PipelineStatistics(_) => native::QueryHeapType::PipelineStatistics,
query::Type::Timestamp => native::QueryHeapType::Timestamp,
};
let (query_heap, hr) = self.raw.create_query_heap(heap_ty, count, 0);
assert_eq!(winerror::S_OK, hr);
Ok(r::QueryPool {
raw: query_heap,
ty: heap_ty,
})
}
unsafe fn destroy_query_pool(&self, pool: r::QueryPool) {
pool.raw.destroy();
}
unsafe fn get_query_pool_results(
&self,
_pool: &r::QueryPool,
_queries: Range<query::Id>,
_data: &mut [u8],
_stride: buffer::Offset,
_flags: query::ResultFlags,
) -> Result<bool, d::OomOrDeviceLost> {
unimplemented!()
}
unsafe fn destroy_shader_module(&self, shader_lib: r::ShaderModule) {
if let r::ShaderModule::Compiled(shaders) = shader_lib {
for (_, blob) in shaders {
blob.destroy();
}
}
}
unsafe fn destroy_render_pass(&self, _rp: r::RenderPass) {
// Just drop
}
unsafe fn destroy_pipeline_layout(&self, layout: r::PipelineLayout) {
layout.raw.destroy();
}
unsafe fn destroy_graphics_pipeline(&self, pipeline: r::GraphicsPipeline) {
pipeline.raw.destroy();
}
unsafe fn destroy_compute_pipeline(&self, pipeline: r::ComputePipeline) {
pipeline.raw.destroy();
}
unsafe fn destroy_framebuffer(&self, _fb: r::Framebuffer) {
// Just drop
}
unsafe fn destroy_buffer(&self, buffer: r::Buffer) {
match buffer {
r::Buffer::Bound(buffer) => {
buffer.resource.destroy();
}
r::Buffer::Unbound(_) => {}
}
}
unsafe fn destroy_buffer_view(&self, _view: r::BufferView) {
// empty
}
unsafe fn destroy_image(&self, image: r::Image) {
match image {
r::Image::Bound(image) => {
image.resource.destroy();
}
r::Image::Unbound(_) => {}
}
}
unsafe fn destroy_image_view(&self, _view: r::ImageView) {
// Just drop
}
unsafe fn destroy_sampler(&self, _sampler: r::Sampler) {
// Just drop
}
unsafe fn destroy_descriptor_pool(&self, _pool: r::DescriptorPool) {
// Just drop
// Allocated descriptor sets don't need to be freed beforehand.
}
unsafe fn destroy_descriptor_set_layout(&self, _layout: r::DescriptorSetLayout) {
// Just drop
}
unsafe fn destroy_fence(&self, fence: r::Fence) {
fence.raw.destroy();
}
unsafe fn destroy_semaphore(&self, semaphore: r::Semaphore) {
semaphore.raw.destroy();
}
unsafe fn destroy_event(&self, _event: ()) {
unimplemented!()
}
unsafe fn create_swapchain(
&self,
surface: &mut Surface,
config: w::SwapchainConfig,
old_swapchain: Option<Swapchain>,
) -> Result<(Swapchain, Vec<r::Image>), w::CreationError> {
if let Some(old_swapchain) = old_swapchain {
self.destroy_swapchain(old_swapchain);
}
let (swap_chain3, non_srgb_format) =
self.create_swapchain_impl(&config, surface.wnd_handle, surface.factory)?;
let swapchain = self.wrap_swapchain(swap_chain3, &config);
let mut images = Vec::with_capacity(config.image_count as usize);
for (i, &resource) in swapchain.resources.iter().enumerate() {
let rtv_handle = swapchain.rtv_heap.at(i as _, 0).cpu;
let surface_type = config.format.base_format().0;
let format_desc = surface_type.desc();
let bytes_per_block = (format_desc.bits / 8) as _;
let block_dim = format_desc.dim;
let kind = image::Kind::D2(config.extent.width, config.extent.height, 1, 1);
images.push(r::Image::Bound(r::ImageBound {
resource,
place: r::Place::SwapChain,
surface_type,
kind,
usage: config.image_usage,
default_view_format: Some(non_srgb_format),
view_caps: image::ViewCapabilities::empty(),
descriptor: d3d12::D3D12_RESOURCE_DESC {
Dimension: d3d12::D3D12_RESOURCE_DIMENSION_TEXTURE2D,
Alignment: 0,
Width: config.extent.width as _,
Height: config.extent.height as _,
DepthOrArraySize: 1,
MipLevels: 1,
Format: non_srgb_format,
SampleDesc: dxgitype::DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
Layout: d3d12::D3D12_TEXTURE_LAYOUT_UNKNOWN,
Flags: 0,
},
bytes_per_block,
block_dim,
clear_cv: vec![rtv_handle],
clear_dv: Vec::new(),
clear_sv: Vec::new(),
// Dummy values, image is already bound
requirements: memory::Requirements {
alignment: 1,
size: 1,
type_mask: MEM_TYPE_MASK,
},
}));
}
Ok((swapchain, images))
}
unsafe fn destroy_swapchain(&self, swapchain: Swapchain) {
let inner = swapchain.release_resources();
inner.destroy();
}
fn wait_idle(&self) -> Result<(), d::OutOfMemory> {
for queue in &self.queues {
queue.wait_idle()?;
}
Ok(())
}
unsafe fn set_image_name(&self, _image: &mut r::Image, _name: &str) {
// TODO
}
unsafe fn set_buffer_name(&self, _buffer: &mut r::Buffer, _name: &str) {
// TODO
}
unsafe fn set_command_buffer_name(
&self,
_command_buffer: &mut cmd::CommandBuffer,
_name: &str,
) {
// TODO
}
unsafe fn set_semaphore_name(&self, _semaphore: &mut r::Semaphore, _name: &str) {
// TODO
}
unsafe fn set_fence_name(&self, _fence: &mut r::Fence, _name: &str) {
// TODO
}
unsafe fn set_framebuffer_name(&self, _framebuffer: &mut r::Framebuffer, _name: &str) {
// TODO
}
unsafe fn set_render_pass_name(&self, _render_pass: &mut r::RenderPass, _name: &str) {
// TODO
}
unsafe fn set_descriptor_set_name(&self, _descriptor_set: &mut r::DescriptorSet, _name: &str) {
// TODO
}
unsafe fn set_descriptor_set_layout_name(
&self,
_descriptor_set_layout: &mut r::DescriptorSetLayout,
_name: &str,
) {
// TODO
}
}
#[test]
fn test_identity_mapping() {
assert_eq!(conv::map_swizzle(format::Swizzle::NO), IDENTITY_MAPPING);
}
| 38.50168 | 126 | 0.515684 |
5bf12c54c4a203b8f47796a10e723f21a282a299 | 79,868 | //! The Rust abstract syntax tree module.
//!
//! This module contains common structures forming the language AST.
//! Two main entities in the module are [`Item`] (which represents an AST element with
//! additional metadata), and [`ItemKind`] (which represents a concrete type and contains
//! information specific to the type of the item).
//!
//! Other module items that worth mentioning:
//! - [`Ty`] and [`TyKind`]: A parsed Rust type.
//! - [`Expr`] and [`ExprKind`]: A parsed Rust expression.
//! - [`Pat`] and [`PatKind`]: A parsed Rust pattern. Patterns are often dual to expressions.
//! - [`Stmt`] and [`StmtKind`]: An executable action that does not return a value.
//! - [`FnDecl`], [`FnHeader`] and [`Param`]: Metadata associated with a function declaration.
//! - [`Generics`], [`GenericParam`], [`WhereClause`]: Metadata associated with generic parameters.
//! - [`EnumDef`] and [`Variant`]: Enum declaration.
//! - [`Lit`] and [`LitKind`]: Literal expressions.
//! - [`MacroDef`], [`MacStmtStyle`], [`Mac`], [`MacDelimeter`]: Macro definition and invocation.
//! - [`Attribute`]: Metadata associated with item.
//! - [`UnOp`], [`UnOpKind`], [`BinOp`], [`BinOpKind`]: Unary and binary operators.
pub use GenericArgs::*;
pub use UnsafeSource::*;
pub use crate::util::parser::ExprPrecedence;
pub use syntax_pos::symbol::{Ident, Symbol as Name};
use crate::ptr::P;
use crate::source_map::{dummy_spanned, respan, Spanned};
use crate::token::{self, DelimToken};
use crate::tokenstream::TokenStream;
use syntax_pos::symbol::{kw, sym, Symbol};
use syntax_pos::{Span, DUMMY_SP, ExpnId};
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_data_structures::sync::Lrc;
use rustc_data_structures::thin_vec::ThinVec;
use rustc_index::vec::Idx;
use rustc_serialize::{self, Decoder, Encoder};
use rustc_macros::HashStable_Generic;
use std::fmt;
#[cfg(test)]
mod tests;
/// A "Label" is an identifier of some point in sources,
/// e.g. in the following code:
///
/// ```rust
/// 'outer: loop {
/// break 'outer;
/// }
/// ```
///
/// `'outer` is a label.
#[derive(Clone, RustcEncodable, RustcDecodable, Copy, HashStable_Generic)]
pub struct Label {
pub ident: Ident,
}
impl fmt::Debug for Label {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "label({:?})", self.ident)
}
}
/// A "Lifetime" is an annotation of the scope in which variable
/// can be used, e.g. `'a` in `&'a i32`.
#[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
pub struct Lifetime {
pub id: NodeId,
pub ident: Ident,
}
impl fmt::Debug for Lifetime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"lifetime({}: {})",
self.id,
self
)
}
}
impl fmt::Display for Lifetime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.ident.name)
}
}
/// A "Path" is essentially Rust's notion of a name.
///
/// It's represented as a sequence of identifiers,
/// along with a bunch of supporting information.
///
/// E.g., `std::cmp::PartialEq`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Path {
pub span: Span,
/// The segments in the path: the things separated by `::`.
/// Global paths begin with `kw::PathRoot`.
pub segments: Vec<PathSegment>,
}
impl PartialEq<Symbol> for Path {
fn eq(&self, symbol: &Symbol) -> bool {
self.segments.len() == 1 && {
self.segments[0].ident.name == *symbol
}
}
}
impl<CTX> HashStable<CTX> for Path {
fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) {
self.segments.len().hash_stable(hcx, hasher);
for segment in &self.segments {
segment.ident.name.hash_stable(hcx, hasher);
}
}
}
impl Path {
// Convert a span and an identifier to the corresponding
// one-segment path.
pub fn from_ident(ident: Ident) -> Path {
Path {
segments: vec![PathSegment::from_ident(ident)],
span: ident.span,
}
}
pub fn is_global(&self) -> bool {
!self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot
}
}
/// A segment of a path: an identifier, an optional lifetime, and a set of types.
///
/// E.g., `std`, `String` or `Box<T>`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct PathSegment {
/// The identifier portion of this path segment.
pub ident: Ident,
pub id: NodeId,
/// Type/lifetime parameters attached to this path. They come in
/// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`.
/// `None` means that no parameter list is supplied (`Path`),
/// `Some` means that parameter list is supplied (`Path<X, Y>`)
/// but it can be empty (`Path<>`).
/// `P` is used as a size optimization for the common case with no parameters.
pub args: Option<P<GenericArgs>>,
}
impl PathSegment {
pub fn from_ident(ident: Ident) -> Self {
PathSegment { ident, id: DUMMY_NODE_ID, args: None }
}
pub fn path_root(span: Span) -> Self {
PathSegment::from_ident(Ident::new(kw::PathRoot, span))
}
}
/// The arguments of a path segment.
///
/// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum GenericArgs {
/// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`.
AngleBracketed(AngleBracketedArgs),
/// The `(A, B)` and `C` in `Foo(A, B) -> C`.
Parenthesized(ParenthesizedArgs),
}
impl GenericArgs {
pub fn is_parenthesized(&self) -> bool {
match *self {
Parenthesized(..) => true,
_ => false,
}
}
pub fn is_angle_bracketed(&self) -> bool {
match *self {
AngleBracketed(..) => true,
_ => false,
}
}
pub fn span(&self) -> Span {
match *self {
AngleBracketed(ref data) => data.span,
Parenthesized(ref data) => data.span,
}
}
}
/// Concrete argument in the sequence of generic args.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum GenericArg {
/// `'a` in `Foo<'a>`
Lifetime(Lifetime),
/// `Bar` in `Foo<Bar>`
Type(P<Ty>),
/// `1` in `Foo<1>`
Const(AnonConst),
}
impl GenericArg {
pub fn span(&self) -> Span {
match self {
GenericArg::Lifetime(lt) => lt.ident.span,
GenericArg::Type(ty) => ty.span,
GenericArg::Const(ct) => ct.value.span,
}
}
}
/// A path like `Foo<'a, T>`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
pub struct AngleBracketedArgs {
/// The overall span.
pub span: Span,
/// The arguments for this path segment.
pub args: Vec<GenericArg>,
/// Constraints on associated types, if any.
/// E.g., `Foo<A = Bar, B: Baz>`.
pub constraints: Vec<AssocTyConstraint>,
}
impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs {
fn into(self) -> Option<P<GenericArgs>> {
Some(P(GenericArgs::AngleBracketed(self)))
}
}
impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs {
fn into(self) -> Option<P<GenericArgs>> {
Some(P(GenericArgs::Parenthesized(self)))
}
}
/// A path like `Foo(A, B) -> C`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct ParenthesizedArgs {
/// Overall span
pub span: Span,
/// `(A, B)`
pub inputs: Vec<P<Ty>>,
/// `C`
pub output: Option<P<Ty>>,
}
impl ParenthesizedArgs {
pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
AngleBracketedArgs {
span: self.span,
args: self.inputs.iter().cloned().map(|input| GenericArg::Type(input)).collect(),
constraints: vec![],
}
}
}
// hack to ensure that we don't try to access the private parts of `NodeId` in this module
mod node_id_inner {
use rustc_index::vec::Idx;
rustc_index::newtype_index! {
pub struct NodeId {
ENCODABLE = custom
DEBUG_FORMAT = "NodeId({})"
}
}
}
pub use node_id_inner::NodeId;
impl NodeId {
pub fn placeholder_from_expn_id(expn_id: ExpnId) -> Self {
NodeId::from_u32(expn_id.as_u32())
}
pub fn placeholder_to_expn_id(self) -> ExpnId {
ExpnId::from_u32(self.as_u32())
}
}
impl fmt::Display for NodeId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.as_u32(), f)
}
}
impl rustc_serialize::UseSpecializedEncodable for NodeId {
fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_u32(self.as_u32())
}
}
impl rustc_serialize::UseSpecializedDecodable for NodeId {
fn default_decode<D: Decoder>(d: &mut D) -> Result<NodeId, D::Error> {
d.read_u32().map(NodeId::from_u32)
}
}
/// `NodeId` used to represent the root of the crate.
pub const CRATE_NODE_ID: NodeId = NodeId::from_u32_const(0);
/// When parsing and doing expansions, we initially give all AST nodes this AST
/// node value. Then later, in the renumber pass, we renumber them to have
/// small, positive ids.
pub const DUMMY_NODE_ID: NodeId = NodeId::MAX;
/// A modifier on a bound, currently this is only used for `?Sized`, where the
/// modifier is `Maybe`. Negative bounds should also be handled here.
#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
pub enum TraitBoundModifier {
None,
Maybe,
}
/// The AST represents all type param bounds as types.
/// `typeck::collect::compute_bounds` matches these against
/// the "special" built-in traits (see `middle::lang_items`) and
/// detects `Copy`, `Send` and `Sync`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum GenericBound {
Trait(PolyTraitRef, TraitBoundModifier),
Outlives(Lifetime),
}
impl GenericBound {
pub fn span(&self) -> Span {
match self {
&GenericBound::Trait(ref t, ..) => t.span,
&GenericBound::Outlives(ref l) => l.ident.span,
}
}
}
pub type GenericBounds = Vec<GenericBound>;
/// Specifies the enforced ordering for generic parameters. In the future,
/// if we wanted to relax this order, we could override `PartialEq` and
/// `PartialOrd`, to allow the kinds to be unordered.
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub enum ParamKindOrd {
Lifetime,
Type,
Const,
}
impl fmt::Display for ParamKindOrd {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParamKindOrd::Lifetime => "lifetime".fmt(f),
ParamKindOrd::Type => "type".fmt(f),
ParamKindOrd::Const => "const".fmt(f),
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum GenericParamKind {
/// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
Lifetime,
Type { default: Option<P<Ty>> },
Const { ty: P<Ty> },
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct GenericParam {
pub id: NodeId,
pub ident: Ident,
pub attrs: ThinVec<Attribute>,
pub bounds: GenericBounds,
pub is_placeholder: bool,
pub kind: GenericParamKind,
}
/// Represents lifetime, type and const parameters attached to a declaration of
/// a function, enum, trait, etc.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Generics {
pub params: Vec<GenericParam>,
pub where_clause: WhereClause,
pub span: Span,
}
impl Default for Generics {
/// Creates an instance of `Generics`.
fn default() -> Generics {
Generics {
params: Vec::new(),
where_clause: WhereClause {
predicates: Vec::new(),
span: DUMMY_SP,
},
span: DUMMY_SP,
}
}
}
/// A where-clause in a definition.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct WhereClause {
pub predicates: Vec<WherePredicate>,
pub span: Span,
}
/// A single predicate in a where-clause.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum WherePredicate {
/// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`).
BoundPredicate(WhereBoundPredicate),
/// A lifetime predicate (e.g., `'a: 'b + 'c`).
RegionPredicate(WhereRegionPredicate),
/// An equality predicate (unsupported).
EqPredicate(WhereEqPredicate),
}
impl WherePredicate {
pub fn span(&self) -> Span {
match self {
&WherePredicate::BoundPredicate(ref p) => p.span,
&WherePredicate::RegionPredicate(ref p) => p.span,
&WherePredicate::EqPredicate(ref p) => p.span,
}
}
}
/// A type bound.
///
/// E.g., `for<'c> Foo: Send + Clone + 'c`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct WhereBoundPredicate {
pub span: Span,
/// Any generics from a `for` binding.
pub bound_generic_params: Vec<GenericParam>,
/// The type being bounded.
pub bounded_ty: P<Ty>,
/// Trait and lifetime bounds (`Clone + Send + 'static`).
pub bounds: GenericBounds,
}
/// A lifetime predicate.
///
/// E.g., `'a: 'b + 'c`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct WhereRegionPredicate {
pub span: Span,
pub lifetime: Lifetime,
pub bounds: GenericBounds,
}
/// An equality predicate (unsupported).
///
/// E.g., `T = int`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct WhereEqPredicate {
pub id: NodeId,
pub span: Span,
pub lhs_ty: P<Ty>,
pub rhs_ty: P<Ty>,
}
/// The set of `MetaItem`s that define the compilation environment of the crate,
/// used to drive conditional compilation.
pub type CrateConfig = FxHashSet<(Name, Option<Symbol>)>;
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Crate {
pub module: Mod,
pub attrs: Vec<Attribute>,
pub span: Span,
}
/// Possible values inside of compile-time attribute lists.
///
/// E.g., the '..' in `#[name(..)]`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub enum NestedMetaItem {
/// A full MetaItem, for recursive meta items.
MetaItem(MetaItem),
/// A literal.
///
/// E.g., `"foo"`, `64`, `true`.
Literal(Lit),
}
/// A spanned compile-time attribute item.
///
/// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub struct MetaItem {
pub path: Path,
pub kind: MetaItemKind,
pub span: Span,
}
/// A compile-time attribute item.
///
/// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub enum MetaItemKind {
/// Word meta item.
///
/// E.g., `test` as in `#[test]`.
Word,
/// List meta item.
///
/// E.g., `derive(..)` as in `#[derive(..)]`.
List(Vec<NestedMetaItem>),
/// Name value meta item.
///
/// E.g., `feature = "foo"` as in `#[feature = "foo"]`.
NameValue(Lit),
}
/// A block (`{ .. }`).
///
/// E.g., `{ .. }` as in `fn foo() { .. }`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Block {
/// The statements in the block.
pub stmts: Vec<Stmt>,
pub id: NodeId,
/// Distinguishes between `unsafe { ... }` and `{ ... }`.
pub rules: BlockCheckMode,
pub span: Span,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Pat {
pub id: NodeId,
pub kind: PatKind,
pub span: Span,
}
impl Pat {
/// Attempt reparsing the pattern as a type.
/// This is intended for use by diagnostics.
pub fn to_ty(&self) -> Option<P<Ty>> {
let kind = match &self.kind {
// In a type expression `_` is an inference variable.
PatKind::Wild => TyKind::Infer,
// An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`.
PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None) => {
TyKind::Path(None, Path::from_ident(*ident))
}
PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
PatKind::Mac(mac) => TyKind::Mac(mac.clone()),
// `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type.
PatKind::Ref(pat, mutbl) => pat
.to_ty()
.map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
// A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array,
// when `P` can be reparsed as a type `T`.
PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?,
// A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)`
// assuming `T0` to `Tn` are all syntactically valid as types.
PatKind::Tuple(pats) => {
let mut tys = Vec::with_capacity(pats.len());
// FIXME(#48994) - could just be collected into an Option<Vec>
for pat in pats {
tys.push(pat.to_ty()?);
}
TyKind::Tup(tys)
}
_ => return None,
};
Some(P(Ty {
kind,
id: self.id,
span: self.span,
}))
}
/// Walk top-down and call `it` in each place where a pattern occurs
/// starting with the root pattern `walk` is called on. If `it` returns
/// false then we will descend no further but siblings will be processed.
pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) {
if !it(self) {
return;
}
match &self.kind {
// Walk into the pattern associated with `Ident` (if any).
PatKind::Ident(_, _, Some(p)) => p.walk(it),
// Walk into each field of struct.
PatKind::Struct(_, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)),
// Sequence of patterns.
PatKind::TupleStruct(_, s)
| PatKind::Tuple(s)
| PatKind::Slice(s)
| PatKind::Or(s) => s.iter().for_each(|p| p.walk(it)),
// Trivial wrappers over inner patterns.
PatKind::Box(s)
| PatKind::Ref(s, _)
| PatKind::Paren(s) => s.walk(it),
// These patterns do not contain subpatterns, skip.
PatKind::Wild
| PatKind::Rest
| PatKind::Lit(_)
| PatKind::Range(..)
| PatKind::Ident(..)
| PatKind::Path(..)
| PatKind::Mac(_) => {},
}
}
/// Is this a `..` pattern?
pub fn is_rest(&self) -> bool {
match self.kind {
PatKind::Rest => true,
_ => false,
}
}
}
/// A single field in a struct pattern
///
/// Patterns like the fields of Foo `{ x, ref y, ref mut z }`
/// are treated the same as` x: x, y: ref y, z: ref mut z`,
/// except is_shorthand is true
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct FieldPat {
/// The identifier for the field
pub ident: Ident,
/// The pattern the field is destructured to
pub pat: P<Pat>,
pub is_shorthand: bool,
pub attrs: ThinVec<Attribute>,
pub id: NodeId,
pub span: Span,
pub is_placeholder: bool,
}
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
pub enum BindingMode {
ByRef(Mutability),
ByValue(Mutability),
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum RangeEnd {
Included(RangeSyntax),
Excluded,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum RangeSyntax {
/// `...`
DotDotDot,
/// `..=`
DotDotEq,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum PatKind {
/// Represents a wildcard pattern (`_`).
Wild,
/// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`),
/// or a unit struct/variant pattern, or a const pattern (in the last two cases the third
/// field must be `None`). Disambiguation cannot be done with parser alone, so it happens
/// during name resolution.
Ident(BindingMode, Ident, Option<P<Pat>>),
/// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`).
/// The `bool` is `true` in the presence of a `..`.
Struct(Path, Vec<FieldPat>, /* recovered */ bool),
/// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
TupleStruct(Path, Vec<P<Pat>>),
/// An or-pattern `A | B | C`.
/// Invariant: `pats.len() >= 2`.
Or(Vec<P<Pat>>),
/// A possibly qualified path pattern.
/// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
/// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can
/// only legally refer to associated constants.
Path(Option<QSelf>, Path),
/// A tuple pattern (`(a, b)`).
Tuple(Vec<P<Pat>>),
/// A `box` pattern.
Box(P<Pat>),
/// A reference pattern (e.g., `&mut (a, b)`).
Ref(P<Pat>, Mutability),
/// A literal.
Lit(P<Expr>),
/// A range pattern (e.g., `1...2`, `1..=2` or `1..2`).
Range(P<Expr>, P<Expr>, Spanned<RangeEnd>),
/// A slice pattern `[a, b, c]`.
Slice(Vec<P<Pat>>),
/// A rest pattern `..`.
///
/// Syntactically it is valid anywhere.
///
/// Semantically however, it only has meaning immediately inside:
/// - a slice pattern: `[a, .., b]`,
/// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`,
/// - a tuple pattern: `(a, .., b)`,
/// - a tuple struct/variant pattern: `$path(a, .., b)`.
///
/// In all of these cases, an additional restriction applies,
/// only one rest pattern may occur in the pattern sequences.
Rest,
/// Parentheses in patterns used for grouping (i.e., `(PAT)`).
Paren(P<Pat>),
/// A macro pattern; pre-expansion.
Mac(Mac),
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
pub enum Mutability {
Mutable,
Immutable,
}
impl Mutability {
/// Returns `MutMutable` only if both `self` and `other` are mutable.
pub fn and(self, other: Self) -> Self {
match self {
Mutability::Mutable => other,
Mutability::Immutable => Mutability::Immutable,
}
}
pub fn invert(self) -> Self {
match self {
Mutability::Mutable => Mutability::Immutable,
Mutability::Immutable => Mutability::Mutable,
}
}
pub fn prefix_str(&self) -> &'static str {
match self {
Mutability::Mutable => "mut ",
Mutability::Immutable => "",
}
}
}
/// The kind of borrow in an `AddrOf` expression,
/// e.g., `&place` or `&raw const place`.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[derive(RustcEncodable, RustcDecodable, HashStable_Generic)]
pub enum BorrowKind {
/// A raw borrow, `&raw const $expr` or `&raw mut $expr`.
/// The resulting type is either `*const T` or `*mut T`
/// where `T = typeof($expr)`.
Ref,
/// A normal borrow, `&$expr` or `&mut $expr`.
/// The resulting type is either `&'a T` or `&'a mut T`
/// where `T = typeof($expr)` and `'a` is some lifetime.
Raw,
}
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
pub enum BinOpKind {
/// The `+` operator (addition)
Add,
/// The `-` operator (subtraction)
Sub,
/// The `*` operator (multiplication)
Mul,
/// The `/` operator (division)
Div,
/// The `%` operator (modulus)
Rem,
/// The `&&` operator (logical and)
And,
/// The `||` operator (logical or)
Or,
/// The `^` operator (bitwise xor)
BitXor,
/// The `&` operator (bitwise and)
BitAnd,
/// The `|` operator (bitwise or)
BitOr,
/// The `<<` operator (shift left)
Shl,
/// The `>>` operator (shift right)
Shr,
/// The `==` operator (equality)
Eq,
/// The `<` operator (less than)
Lt,
/// The `<=` operator (less than or equal to)
Le,
/// The `!=` operator (not equal to)
Ne,
/// The `>=` operator (greater than or equal to)
Ge,
/// The `>` operator (greater than)
Gt,
}
impl BinOpKind {
pub fn to_string(&self) -> &'static str {
use BinOpKind::*;
match *self {
Add => "+",
Sub => "-",
Mul => "*",
Div => "/",
Rem => "%",
And => "&&",
Or => "||",
BitXor => "^",
BitAnd => "&",
BitOr => "|",
Shl => "<<",
Shr => ">>",
Eq => "==",
Lt => "<",
Le => "<=",
Ne => "!=",
Ge => ">=",
Gt => ">",
}
}
pub fn lazy(&self) -> bool {
match *self {
BinOpKind::And | BinOpKind::Or => true,
_ => false,
}
}
pub fn is_shift(&self) -> bool {
match *self {
BinOpKind::Shl | BinOpKind::Shr => true,
_ => false,
}
}
pub fn is_comparison(&self) -> bool {
use BinOpKind::*;
// Note for developers: please keep this as is;
// we want compilation to fail if another variant is added.
match *self {
Eq | Lt | Le | Ne | Gt | Ge => true,
And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false,
}
}
/// Returns `true` if the binary operator takes its arguments by value
pub fn is_by_value(&self) -> bool {
!self.is_comparison()
}
}
pub type BinOp = Spanned<BinOpKind>;
/// Unary operator.
///
/// Note that `&data` is not an operator, it's an `AddrOf` expression.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
pub enum UnOp {
/// The `*` operator for dereferencing
Deref,
/// The `!` operator for logical inversion
Not,
/// The `-` operator for negation
Neg,
}
impl UnOp {
/// Returns `true` if the unary operator takes its argument by value
pub fn is_by_value(u: UnOp) -> bool {
match u {
UnOp::Neg | UnOp::Not => true,
_ => false,
}
}
pub fn to_string(op: UnOp) -> &'static str {
match op {
UnOp::Deref => "*",
UnOp::Not => "!",
UnOp::Neg => "-",
}
}
}
/// A statement
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Stmt {
pub id: NodeId,
pub kind: StmtKind,
pub span: Span,
}
impl Stmt {
pub fn add_trailing_semicolon(mut self) -> Self {
self.kind = match self.kind {
StmtKind::Expr(expr) => StmtKind::Semi(expr),
StmtKind::Mac(mac) => {
StmtKind::Mac(mac.map(|(mac, _style, attrs)| (mac, MacStmtStyle::Semicolon, attrs)))
}
kind => kind,
};
self
}
pub fn is_item(&self) -> bool {
match self.kind {
StmtKind::Item(_) => true,
_ => false,
}
}
pub fn is_expr(&self) -> bool {
match self.kind {
StmtKind::Expr(_) => true,
_ => false,
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum StmtKind {
/// A local (let) binding.
Local(P<Local>),
/// An item definition.
Item(P<Item>),
/// Expr without trailing semi-colon.
Expr(P<Expr>),
/// Expr with a trailing semi-colon.
Semi(P<Expr>),
/// Macro.
Mac(P<(Mac, MacStmtStyle, ThinVec<Attribute>)>),
}
#[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
pub enum MacStmtStyle {
/// The macro statement had a trailing semicolon (e.g., `foo! { ... };`
/// `foo!(...);`, `foo![...];`).
Semicolon,
/// The macro statement had braces (e.g., `foo! { ... }`).
Braces,
/// The macro statement had parentheses or brackets and no semicolon (e.g.,
/// `foo!(...)`). All of these will end up being converted into macro
/// expressions.
NoBraces,
}
/// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Local {
pub id: NodeId,
pub pat: P<Pat>,
pub ty: Option<P<Ty>>,
/// Initializer expression to set the value, if any.
pub init: Option<P<Expr>>,
pub span: Span,
pub attrs: ThinVec<Attribute>,
}
/// An arm of a 'match'.
///
/// E.g., `0..=10 => { println!("match!") }` as in
///
/// ```
/// match 123 {
/// 0..=10 => { println!("match!") },
/// _ => { println!("no match!") },
/// }
/// ```
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Arm {
pub attrs: Vec<Attribute>,
/// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }`
pub pat: P<Pat>,
/// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }`
pub guard: Option<P<Expr>>,
/// Match arm body.
pub body: P<Expr>,
pub span: Span,
pub id: NodeId,
pub is_placeholder: bool,
}
/// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Field {
pub attrs: ThinVec<Attribute>,
pub id: NodeId,
pub span: Span,
pub ident: Ident,
pub expr: P<Expr>,
pub is_shorthand: bool,
pub is_placeholder: bool,
}
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
pub enum BlockCheckMode {
Default,
Unsafe(UnsafeSource),
}
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
pub enum UnsafeSource {
CompilerGenerated,
UserProvided,
}
/// A constant (expression) that's not an item or associated item,
/// but needs its own `DefId` for type-checking, const-eval, etc.
/// These are usually found nested inside types (e.g., array lengths)
/// or expressions (e.g., repeat counts), and also used to define
/// explicit discriminant values for enum variants.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct AnonConst {
pub id: NodeId,
pub value: P<Expr>,
}
/// An expression.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Expr {
pub id: NodeId,
pub kind: ExprKind,
pub span: Span,
pub attrs: ThinVec<Attribute>,
}
// `Expr` is used a lot. Make sure it doesn't unintentionally get bigger.
#[cfg(target_arch = "x86_64")]
rustc_data_structures::static_assert_size!(Expr, 96);
impl Expr {
/// Returns `true` if this expression would be valid somewhere that expects a value;
/// for example, an `if` condition.
pub fn returns(&self) -> bool {
if let ExprKind::Block(ref block, _) = self.kind {
match block.stmts.last().map(|last_stmt| &last_stmt.kind) {
// Implicit return
Some(&StmtKind::Expr(_)) => true,
Some(&StmtKind::Semi(ref expr)) => {
if let ExprKind::Ret(_) = expr.kind {
// Last statement is explicit return.
true
} else {
false
}
}
// This is a block that doesn't end in either an implicit or explicit return.
_ => false,
}
} else {
// This is not a block, it is a value.
true
}
}
pub fn to_bound(&self) -> Option<GenericBound> {
match &self.kind {
ExprKind::Path(None, path) => Some(GenericBound::Trait(
PolyTraitRef::new(Vec::new(), path.clone(), self.span),
TraitBoundModifier::None,
)),
_ => None,
}
}
/// Attempts to reparse as `Ty` (for diagnostic purposes).
pub fn to_ty(&self) -> Option<P<Ty>> {
let kind = match &self.kind {
// Trivial conversions.
ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()),
ExprKind::Mac(mac) => TyKind::Mac(mac.clone()),
ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?,
ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => expr
.to_ty()
.map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))?,
ExprKind::Repeat(expr, expr_len) => {
expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))?
}
ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?,
ExprKind::Tup(exprs) => {
let tys = exprs
.iter()
.map(|expr| expr.to_ty())
.collect::<Option<Vec<_>>>()?;
TyKind::Tup(tys)
}
// If binary operator is `Add` and both `lhs` and `rhs` are trait bounds,
// then type of result is trait object.
// Othewise we don't assume the result type.
ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => {
if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) {
TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None)
} else {
return None;
}
}
// This expression doesn't look like a type syntactically.
_ => return None,
};
Some(P(Ty {
kind,
id: self.id,
span: self.span,
}))
}
pub fn precedence(&self) -> ExprPrecedence {
match self.kind {
ExprKind::Box(_) => ExprPrecedence::Box,
ExprKind::Array(_) => ExprPrecedence::Array,
ExprKind::Call(..) => ExprPrecedence::Call,
ExprKind::MethodCall(..) => ExprPrecedence::MethodCall,
ExprKind::Tup(_) => ExprPrecedence::Tup,
ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node),
ExprKind::Unary(..) => ExprPrecedence::Unary,
ExprKind::Lit(_) => ExprPrecedence::Lit,
ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast,
ExprKind::Let(..) => ExprPrecedence::Let,
ExprKind::If(..) => ExprPrecedence::If,
ExprKind::While(..) => ExprPrecedence::While,
ExprKind::ForLoop(..) => ExprPrecedence::ForLoop,
ExprKind::Loop(..) => ExprPrecedence::Loop,
ExprKind::Match(..) => ExprPrecedence::Match,
ExprKind::Closure(..) => ExprPrecedence::Closure,
ExprKind::Block(..) => ExprPrecedence::Block,
ExprKind::TryBlock(..) => ExprPrecedence::TryBlock,
ExprKind::Async(..) => ExprPrecedence::Async,
ExprKind::Await(..) => ExprPrecedence::Await,
ExprKind::Assign(..) => ExprPrecedence::Assign,
ExprKind::AssignOp(..) => ExprPrecedence::AssignOp,
ExprKind::Field(..) => ExprPrecedence::Field,
ExprKind::Index(..) => ExprPrecedence::Index,
ExprKind::Range(..) => ExprPrecedence::Range,
ExprKind::Path(..) => ExprPrecedence::Path,
ExprKind::AddrOf(..) => ExprPrecedence::AddrOf,
ExprKind::Break(..) => ExprPrecedence::Break,
ExprKind::Continue(..) => ExprPrecedence::Continue,
ExprKind::Ret(..) => ExprPrecedence::Ret,
ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm,
ExprKind::Mac(..) => ExprPrecedence::Mac,
ExprKind::Struct(..) => ExprPrecedence::Struct,
ExprKind::Repeat(..) => ExprPrecedence::Repeat,
ExprKind::Paren(..) => ExprPrecedence::Paren,
ExprKind::Try(..) => ExprPrecedence::Try,
ExprKind::Yield(..) => ExprPrecedence::Yield,
ExprKind::Err => ExprPrecedence::Err,
}
}
}
/// Limit types of a range (inclusive or exclusive)
#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
pub enum RangeLimits {
/// Inclusive at the beginning, exclusive at the end
HalfOpen,
/// Inclusive at the beginning and end
Closed,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum ExprKind {
/// A `box x` expression.
Box(P<Expr>),
/// An array (`[a, b, c, d]`)
Array(Vec<P<Expr>>),
/// A function call
///
/// The first field resolves to the function itself,
/// and the second field is the list of arguments.
/// This also represents calling the constructor of
/// tuple-like ADTs such as tuple structs and enum variants.
Call(P<Expr>, Vec<P<Expr>>),
/// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`)
///
/// The `PathSegment` represents the method name and its generic arguments
/// (within the angle brackets).
/// The first element of the vector of an `Expr` is the expression that evaluates
/// to the object on which the method is being called on (the receiver),
/// and the remaining elements are the rest of the arguments.
/// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as
/// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`.
MethodCall(PathSegment, Vec<P<Expr>>),
/// A tuple (e.g., `(a, b, c, d)`).
Tup(Vec<P<Expr>>),
/// A binary operation (e.g., `a + b`, `a * b`).
Binary(BinOp, P<Expr>, P<Expr>),
/// A unary operation (e.g., `!x`, `*x`).
Unary(UnOp, P<Expr>),
/// A literal (e.g., `1`, `"foo"`).
Lit(Lit),
/// A cast (e.g., `foo as f64`).
Cast(P<Expr>, P<Ty>),
/// A type ascription (e.g., `42: usize`).
Type(P<Expr>, P<Ty>),
/// A `let pat = expr` expression that is only semantically allowed in the condition
/// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`).
Let(P<Pat>, P<Expr>),
/// An `if` block, with an optional `else` block.
///
/// `if expr { block } else { expr }`
If(P<Expr>, P<Block>, Option<P<Expr>>),
/// A while loop, with an optional label.
///
/// `'label: while expr { block }`
While(P<Expr>, P<Block>, Option<Label>),
/// A `for` loop, with an optional label.
///
/// `'label: for pat in expr { block }`
///
/// This is desugared to a combination of `loop` and `match` expressions.
ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>),
/// Conditionless loop (can be exited with `break`, `continue`, or `return`).
///
/// `'label: loop { block }`
Loop(P<Block>, Option<Label>),
/// A `match` block.
Match(P<Expr>, Vec<Arm>),
/// A closure (e.g., `move |a, b, c| a + b + c`).
///
/// The final span is the span of the argument block `|...|`.
Closure(CaptureBy, IsAsync, Movability, P<FnDecl>, P<Expr>, Span),
/// A block (`'label: { ... }`).
Block(P<Block>, Option<Label>),
/// An async block (`async move { ... }`).
///
/// The `NodeId` is the `NodeId` for the closure that results from
/// desugaring an async block, just like the NodeId field in the
/// `IsAsync` enum. This is necessary in order to create a def for the
/// closure which can be used as a parent of any child defs. Defs
/// created during lowering cannot be made the parent of any other
/// preexisting defs.
Async(CaptureBy, NodeId, P<Block>),
/// An await expression (`my_future.await`).
Await(P<Expr>),
/// A try block (`try { ... }`).
TryBlock(P<Block>),
/// An assignment (`a = foo()`).
Assign(P<Expr>, P<Expr>),
/// An assignment with an operator.
///
/// E.g., `a += 1`.
AssignOp(BinOp, P<Expr>, P<Expr>),
/// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
Field(P<Expr>, Ident),
/// An indexing operation (e.g., `foo[2]`).
Index(P<Expr>, P<Expr>),
/// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`).
Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits),
/// Variable reference, possibly containing `::` and/or type
/// parameters (e.g., `foo::bar::<baz>`).
///
/// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`).
Path(Option<QSelf>, Path),
/// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`).
AddrOf(BorrowKind, Mutability, P<Expr>),
/// A `break`, with an optional label to break, and an optional expression.
Break(Option<Label>, Option<P<Expr>>),
/// A `continue`, with an optional label.
Continue(Option<Label>),
/// A `return`, with an optional value to be returned.
Ret(Option<P<Expr>>),
/// Output of the `asm!()` macro.
InlineAsm(P<InlineAsm>),
/// A macro invocation; pre-expansion.
Mac(Mac),
/// A struct literal expression.
///
/// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. base}`,
/// where `base` is the `Option<Expr>`.
Struct(Path, Vec<Field>, Option<P<Expr>>),
/// An array literal constructed from one repeated element.
///
/// E.g., `[1; 5]`. The expression is the element to be
/// repeated; the constant is the number of times to repeat it.
Repeat(P<Expr>, AnonConst),
/// No-op: used solely so we can pretty-print faithfully.
Paren(P<Expr>),
/// A try expression (`expr?`).
Try(P<Expr>),
/// A `yield`, with an optional value to be yielded.
Yield(Option<P<Expr>>),
/// Placeholder for an expression that wasn't syntactically well formed in some way.
Err,
}
/// The explicit `Self` type in a "qualified path". The actual
/// path, including the trait and the associated item, is stored
/// separately. `position` represents the index of the associated
/// item qualified with this `Self` type.
///
/// ```ignore (only-for-syntax-highlight)
/// <Vec<T> as a::b::Trait>::AssociatedItem
/// ^~~~~ ~~~~~~~~~~~~~~^
/// ty position = 3
///
/// <Vec<T>>::AssociatedItem
/// ^~~~~ ^
/// ty position = 0
/// ```
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct QSelf {
pub ty: P<Ty>,
/// The span of `a::b::Trait` in a path like `<Vec<T> as
/// a::b::Trait>::AssociatedItem`; in the case where `position ==
/// 0`, this is an empty span.
pub path_span: Span,
pub position: usize,
}
/// A capture clause used in closures and `async` blocks.
#[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub enum CaptureBy {
/// `move |x| y + x`.
Value,
/// `move` keyword was not specified.
Ref,
}
/// The movability of a generator / closure literal:
/// whether a generator contains self-references, causing it to be `!Unpin`.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
pub enum Movability {
/// May contain self-references, `!Unpin`.
Static,
/// Must not contain self-references, `Unpin`.
Movable,
}
/// Represents a macro invocation. The `Path` indicates which macro
/// is being invoked, and the vector of token-trees contains the source
/// of the macro invocation.
///
/// N.B., the additional ident for a `macro_rules`-style macro is actually
/// stored in the enclosing item.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Mac {
pub path: Path,
pub delim: MacDelimiter,
pub tts: TokenStream,
pub span: Span,
pub prior_type_ascription: Option<(Span, bool)>,
}
#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)]
pub enum MacDelimiter {
Parenthesis,
Bracket,
Brace,
}
impl Mac {
pub fn stream(&self) -> TokenStream {
self.tts.clone()
}
}
impl MacDelimiter {
crate fn to_token(self) -> DelimToken {
match self {
MacDelimiter::Parenthesis => DelimToken::Paren,
MacDelimiter::Bracket => DelimToken::Bracket,
MacDelimiter::Brace => DelimToken::Brace,
}
}
}
/// Represents a macro definition.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct MacroDef {
pub tokens: TokenStream,
/// `true` if macro was defined with `macro_rules`.
pub legacy: bool,
}
impl MacroDef {
pub fn stream(&self) -> TokenStream {
self.tokens.clone().into()
}
}
// Clippy uses Hash and PartialEq
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, PartialEq, HashStable_Generic)]
pub enum StrStyle {
/// A regular string, like `"foo"`.
Cooked,
/// A raw string, like `r##"foo"##`.
///
/// The value is the number of `#` symbols used.
Raw(u16),
}
/// An AST literal.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub struct Lit {
/// The original literal token as written in source code.
pub token: token::Lit,
/// The "semantic" representation of the literal lowered from the original tokens.
/// Strings are unescaped, hexadecimal forms are eliminated, etc.
/// FIXME: Remove this and only create the semantic representation during lowering to HIR.
pub kind: LitKind,
pub span: Span,
}
/// Same as `Lit`, but restricted to string literals.
#[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
pub struct StrLit {
/// The original literal token as written in source code.
pub style: StrStyle,
pub symbol: Symbol,
pub suffix: Option<Symbol>,
pub span: Span,
/// The unescaped "semantic" representation of the literal lowered from the original token.
/// FIXME: Remove this and only create the semantic representation during lowering to HIR.
pub symbol_unescaped: Symbol,
}
impl StrLit {
crate fn as_lit(&self) -> Lit {
let token_kind = match self.style {
StrStyle::Cooked => token::Str,
StrStyle::Raw(n) => token::StrRaw(n),
};
Lit {
token: token::Lit::new(token_kind, self.symbol, self.suffix),
span: self.span,
kind: LitKind::Str(self.symbol_unescaped, self.style),
}
}
}
// Clippy uses Hash and PartialEq
/// Type of the integer literal based on provided suffix.
#[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
pub enum LitIntType {
/// e.g. `42_i32`.
Signed(IntTy),
/// e.g. `42_u32`.
Unsigned(UintTy),
/// e.g. `42`.
Unsuffixed,
}
/// Type of the float literal based on provided suffix.
#[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
pub enum LitFloatType {
/// A float literal with a suffix (`1f32` or `1E10f32`).
Suffixed(FloatTy),
/// A float literal without a suffix (`1.0 or 1.0E10`).
Unsuffixed,
}
/// Literal kind.
///
/// E.g., `"foo"`, `42`, `12.34`, or `bool`.
// Clippy uses Hash and PartialEq
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Hash, PartialEq, HashStable_Generic)]
pub enum LitKind {
/// A string literal (`"foo"`).
Str(Symbol, StrStyle),
/// A byte string (`b"foo"`).
ByteStr(Lrc<Vec<u8>>),
/// A byte char (`b'f'`).
Byte(u8),
/// A character literal (`'a'`).
Char(char),
/// An integer literal (`1`).
Int(u128, LitIntType),
/// A float literal (`1f64` or `1E10f64`).
Float(Symbol, LitFloatType),
/// A boolean literal.
Bool(bool),
/// Placeholder for a literal that wasn't well-formed in some way.
Err(Symbol),
}
impl LitKind {
/// Returns `true` if this literal is a string.
pub fn is_str(&self) -> bool {
match *self {
LitKind::Str(..) => true,
_ => false,
}
}
/// Returns `true` if this literal is byte literal string.
pub fn is_bytestr(&self) -> bool {
match self {
LitKind::ByteStr(_) => true,
_ => false,
}
}
/// Returns `true` if this is a numeric literal.
pub fn is_numeric(&self) -> bool {
match *self {
LitKind::Int(..) | LitKind::Float(..) => true,
_ => false,
}
}
/// Returns `true` if this literal has no suffix.
/// Note: this will return true for literals with prefixes such as raw strings and byte strings.
pub fn is_unsuffixed(&self) -> bool {
!self.is_suffixed()
}
/// Returns `true` if this literal has a suffix.
pub fn is_suffixed(&self) -> bool {
match *self {
// suffixed variants
LitKind::Int(_, LitIntType::Signed(..))
| LitKind::Int(_, LitIntType::Unsigned(..))
| LitKind::Float(_, LitFloatType::Suffixed(..)) => true,
// unsuffixed variants
LitKind::Str(..)
| LitKind::ByteStr(..)
| LitKind::Byte(..)
| LitKind::Char(..)
| LitKind::Int(_, LitIntType::Unsuffixed)
| LitKind::Float(_, LitFloatType::Unsuffixed)
| LitKind::Bool(..)
| LitKind::Err(..) => false,
}
}
}
// N.B., If you change this, you'll probably want to change the corresponding
// type structure in `middle/ty.rs` as well.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct MutTy {
pub ty: P<Ty>,
pub mutbl: Mutability,
}
/// Represents a function's signature in a trait declaration,
/// trait implementation, or free function.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct FnSig {
pub header: FnHeader,
pub decl: P<FnDecl>,
}
/// Represents an item declaration within a trait declaration,
/// possibly including a default implementation. A trait item is
/// either required (meaning it doesn't have an implementation, just a
/// signature) or provided (meaning it has a default implementation).
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct TraitItem {
pub attrs: Vec<Attribute>,
pub id: NodeId,
pub span: Span,
pub vis: Visibility,
pub ident: Ident,
pub generics: Generics,
pub kind: TraitItemKind,
/// See `Item::tokens` for what this is.
pub tokens: Option<TokenStream>,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum TraitItemKind {
Const(P<Ty>, Option<P<Expr>>),
Method(FnSig, Option<P<Block>>),
Type(GenericBounds, Option<P<Ty>>),
Macro(Mac),
}
/// Represents anything within an `impl` block.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct ImplItem {
pub attrs: Vec<Attribute>,
pub id: NodeId,
pub span: Span,
pub vis: Visibility,
pub ident: Ident,
pub defaultness: Defaultness,
pub generics: Generics,
pub kind: ImplItemKind,
/// See `Item::tokens` for what this is.
pub tokens: Option<TokenStream>,
}
/// Represents various kinds of content within an `impl`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum ImplItemKind {
Const(P<Ty>, P<Expr>),
Method(FnSig, P<Block>),
TyAlias(P<Ty>),
Macro(Mac),
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic,
RustcEncodable, RustcDecodable, Debug)]
pub enum FloatTy {
F32,
F64,
}
impl FloatTy {
pub fn name_str(self) -> &'static str {
match self {
FloatTy::F32 => "f32",
FloatTy::F64 => "f64",
}
}
pub fn name(self) -> Symbol {
match self {
FloatTy::F32 => sym::f32,
FloatTy::F64 => sym::f64,
}
}
pub fn bit_width(self) -> usize {
match self {
FloatTy::F32 => 32,
FloatTy::F64 => 64,
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic,
RustcEncodable, RustcDecodable, Debug)]
pub enum IntTy {
Isize,
I8,
I16,
I32,
I64,
I128,
}
impl IntTy {
pub fn name_str(&self) -> &'static str {
match *self {
IntTy::Isize => "isize",
IntTy::I8 => "i8",
IntTy::I16 => "i16",
IntTy::I32 => "i32",
IntTy::I64 => "i64",
IntTy::I128 => "i128",
}
}
pub fn name(&self) -> Symbol {
match *self {
IntTy::Isize => sym::isize,
IntTy::I8 => sym::i8,
IntTy::I16 => sym::i16,
IntTy::I32 => sym::i32,
IntTy::I64 => sym::i64,
IntTy::I128 => sym::i128,
}
}
pub fn val_to_string(&self, val: i128) -> String {
// Cast to a `u128` so we can correctly print `INT128_MIN`. All integral types
// are parsed as `u128`, so we wouldn't want to print an extra negative
// sign.
format!("{}{}", val as u128, self.name_str())
}
pub fn bit_width(&self) -> Option<usize> {
Some(match *self {
IntTy::Isize => return None,
IntTy::I8 => 8,
IntTy::I16 => 16,
IntTy::I32 => 32,
IntTy::I64 => 64,
IntTy::I128 => 128,
})
}
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable_Generic,
RustcEncodable, RustcDecodable, Copy, Debug)]
pub enum UintTy {
Usize,
U8,
U16,
U32,
U64,
U128,
}
impl UintTy {
pub fn name_str(&self) -> &'static str {
match *self {
UintTy::Usize => "usize",
UintTy::U8 => "u8",
UintTy::U16 => "u16",
UintTy::U32 => "u32",
UintTy::U64 => "u64",
UintTy::U128 => "u128",
}
}
pub fn name(&self) -> Symbol {
match *self {
UintTy::Usize => sym::usize,
UintTy::U8 => sym::u8,
UintTy::U16 => sym::u16,
UintTy::U32 => sym::u32,
UintTy::U64 => sym::u64,
UintTy::U128 => sym::u128,
}
}
pub fn val_to_string(&self, val: u128) -> String {
format!("{}{}", val, self.name_str())
}
pub fn bit_width(&self) -> Option<usize> {
Some(match *self {
UintTy::Usize => return None,
UintTy::U8 => 8,
UintTy::U16 => 16,
UintTy::U32 => 32,
UintTy::U64 => 64,
UintTy::U128 => 128,
})
}
}
/// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
/// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`).
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct AssocTyConstraint {
pub id: NodeId,
pub ident: Ident,
pub kind: AssocTyConstraintKind,
pub span: Span,
}
/// The kinds of an `AssocTyConstraint`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum AssocTyConstraintKind {
/// E.g., `A = Bar` in `Foo<A = Bar>`.
Equality {
ty: P<Ty>,
},
/// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`.
Bound {
bounds: GenericBounds,
},
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Ty {
pub id: NodeId,
pub kind: TyKind,
pub span: Span,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct BareFnTy {
pub unsafety: Unsafety,
pub ext: Extern,
pub generic_params: Vec<GenericParam>,
pub decl: P<FnDecl>,
}
/// The various kinds of type recognized by the compiler.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum TyKind {
/// A variable-length slice (`[T]`).
Slice(P<Ty>),
/// A fixed length array (`[T; n]`).
Array(P<Ty>, AnonConst),
/// A raw pointer (`*const T` or `*mut T`).
Ptr(MutTy),
/// A reference (`&'a T` or `&'a mut T`).
Rptr(Option<Lifetime>, MutTy),
/// A bare function (e.g., `fn(usize) -> bool`).
BareFn(P<BareFnTy>),
/// The never type (`!`).
Never,
/// A tuple (`(A, B, C, D,...)`).
Tup(Vec<P<Ty>>),
/// A path (`module::module::...::Type`), optionally
/// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
///
/// Type parameters are stored in the `Path` itself.
Path(Option<QSelf>, Path),
/// A trait object type `Bound1 + Bound2 + Bound3`
/// where `Bound` is a trait or a lifetime.
TraitObject(GenericBounds, TraitObjectSyntax),
/// An `impl Bound1 + Bound2 + Bound3` type
/// where `Bound` is a trait or a lifetime.
///
/// The `NodeId` exists to prevent lowering from having to
/// generate `NodeId`s on the fly, which would complicate
/// the generation of opaque `type Foo = impl Trait` items significantly.
ImplTrait(NodeId, GenericBounds),
/// No-op; kept solely so that we can pretty-print faithfully.
Paren(P<Ty>),
/// Unused for now.
Typeof(AnonConst),
/// This means the type should be inferred instead of it having been
/// specified. This can appear anywhere in a type.
Infer,
/// Inferred type of a `self` or `&self` argument in a method.
ImplicitSelf,
/// A macro in the type position.
Mac(Mac),
/// Placeholder for a kind that has failed to be defined.
Err,
/// Placeholder for a `va_list`.
CVarArgs,
}
impl TyKind {
pub fn is_implicit_self(&self) -> bool {
if let TyKind::ImplicitSelf = *self {
true
} else {
false
}
}
pub fn is_unit(&self) -> bool {
if let TyKind::Tup(ref tys) = *self {
tys.is_empty()
} else {
false
}
}
/// HACK(type_alias_impl_trait, Centril): A temporary crutch used
/// in lowering to avoid making larger changes there and beyond.
pub fn opaque_top_hack(&self) -> Option<&GenericBounds> {
match self {
Self::ImplTrait(_, bounds) => Some(bounds),
_ => None,
}
}
}
/// Syntax used to declare a trait object.
#[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)]
pub enum TraitObjectSyntax {
Dyn,
None,
}
/// Inline assembly dialect.
///
/// E.g., `"intel"` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
pub enum AsmDialect {
Att,
Intel,
}
/// Inline assembly.
///
/// E.g., `"={eax}"(result)` as in `asm!("mov eax, 2" : "={eax}"(result) : : : "intel")`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct InlineAsmOutput {
pub constraint: Symbol,
pub expr: P<Expr>,
pub is_rw: bool,
pub is_indirect: bool,
}
/// Inline assembly.
///
/// E.g., `asm!("NOP");`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct InlineAsm {
pub asm: Symbol,
pub asm_str_style: StrStyle,
pub outputs: Vec<InlineAsmOutput>,
pub inputs: Vec<(Symbol, P<Expr>)>,
pub clobbers: Vec<Symbol>,
pub volatile: bool,
pub alignstack: bool,
pub dialect: AsmDialect,
}
/// A parameter in a function header.
///
/// E.g., `bar: usize` as in `fn foo(bar: usize)`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Param {
pub attrs: ThinVec<Attribute>,
pub ty: P<Ty>,
pub pat: P<Pat>,
pub id: NodeId,
pub span: Span,
pub is_placeholder: bool,
}
/// Alternative representation for `Arg`s describing `self` parameter of methods.
///
/// E.g., `&mut self` as in `fn foo(&mut self)`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum SelfKind {
/// `self`, `mut self`
Value(Mutability),
/// `&'lt self`, `&'lt mut self`
Region(Option<Lifetime>, Mutability),
/// `self: TYPE`, `mut self: TYPE`
Explicit(P<Ty>, Mutability),
}
pub type ExplicitSelf = Spanned<SelfKind>;
impl Param {
/// Attempts to cast parameter to `ExplicitSelf`.
pub fn to_self(&self) -> Option<ExplicitSelf> {
if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind {
if ident.name == kw::SelfLower {
return match self.ty.kind {
TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))),
TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => {
Some(respan(self.pat.span, SelfKind::Region(lt, mutbl)))
}
_ => Some(respan(
self.pat.span.to(self.ty.span),
SelfKind::Explicit(self.ty.clone(), mutbl),
)),
};
}
}
None
}
/// Returns `true` if parameter is `self`.
pub fn is_self(&self) -> bool {
if let PatKind::Ident(_, ident, _) = self.pat.kind {
ident.name == kw::SelfLower
} else {
false
}
}
/// Builds a `Param` object from `ExplicitSelf`.
pub fn from_self(attrs: ThinVec<Attribute>, eself: ExplicitSelf, eself_ident: Ident) -> Param {
let span = eself.span.to(eself_ident.span);
let infer_ty = P(Ty {
id: DUMMY_NODE_ID,
kind: TyKind::ImplicitSelf,
span,
});
let param = |mutbl, ty| Param {
attrs,
pat: P(Pat {
id: DUMMY_NODE_ID,
kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None),
span,
}),
span,
ty,
id: DUMMY_NODE_ID,
is_placeholder: false
};
match eself.node {
SelfKind::Explicit(ty, mutbl) => param(mutbl, ty),
SelfKind::Value(mutbl) => param(mutbl, infer_ty),
SelfKind::Region(lt, mutbl) => param(
Mutability::Immutable,
P(Ty {
id: DUMMY_NODE_ID,
kind: TyKind::Rptr(
lt,
MutTy {
ty: infer_ty,
mutbl,
},
),
span,
}),
),
}
}
}
/// A signature (not the body) of a function declaration.
///
/// E.g., `fn foo(bar: baz)`.
///
/// Please note that it's different from `FnHeader` structure
/// which contains metadata about function safety, asyncness, constness and ABI.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct FnDecl {
pub inputs: Vec<Param>,
pub output: FunctionRetTy,
}
impl FnDecl {
pub fn get_self(&self) -> Option<ExplicitSelf> {
self.inputs.get(0).and_then(Param::to_self)
}
pub fn has_self(&self) -> bool {
self.inputs.get(0).map_or(false, Param::is_self)
}
pub fn c_variadic(&self) -> bool {
self.inputs.last().map_or(false, |arg| match arg.ty.kind {
TyKind::CVarArgs => true,
_ => false,
})
}
}
/// Is the trait definition an auto trait?
#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub enum IsAuto {
Yes,
No,
}
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub enum Unsafety {
Unsafe,
Normal,
}
impl Unsafety {
pub fn prefix_str(&self) -> &'static str {
match self {
Unsafety::Unsafe => "unsafe ",
Unsafety::Normal => "",
}
}
}
impl fmt::Display for Unsafety {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(
match *self {
Unsafety::Normal => "normal",
Unsafety::Unsafe => "unsafe",
},
f,
)
}
}
#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum IsAsync {
Async {
closure_id: NodeId,
return_impl_trait_id: NodeId,
},
NotAsync,
}
impl IsAsync {
pub fn is_async(self) -> bool {
if let IsAsync::Async { .. } = self {
true
} else {
false
}
}
/// In ths case this is an `async` return, the `NodeId` for the generated `impl Trait` item.
pub fn opt_return_id(self) -> Option<NodeId> {
match self {
IsAsync::Async {
return_impl_trait_id,
..
} => Some(return_impl_trait_id),
IsAsync::NotAsync => None,
}
}
}
#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub enum Constness {
Const,
NotConst,
}
/// Item defaultness.
/// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532).
#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub enum Defaultness {
Default,
Final,
}
#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)]
pub enum ImplPolarity {
/// `impl Trait for Type`
Positive,
/// `impl !Trait for Type`
Negative,
}
impl fmt::Debug for ImplPolarity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
ImplPolarity::Positive => "positive".fmt(f),
ImplPolarity::Negative => "negative".fmt(f),
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum FunctionRetTy {
/// Returns type is not specified.
///
/// Functions default to `()` and closures default to inference.
/// Span points to where return type would be inserted.
Default(Span),
/// Everything else.
Ty(P<Ty>),
}
impl FunctionRetTy {
pub fn span(&self) -> Span {
match *self {
FunctionRetTy::Default(span) => span,
FunctionRetTy::Ty(ref ty) => ty.span,
}
}
}
/// Module declaration.
///
/// E.g., `mod foo;` or `mod foo { .. }`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Mod {
/// A span from the first token past `{` to the last token until `}`.
/// For `mod foo;`, the inner span ranges from the first token
/// to the last token in the external file.
pub inner: Span,
pub items: Vec<P<Item>>,
/// `true` for `mod foo { .. }`; `false` for `mod foo;`.
pub inline: bool,
}
/// Foreign module declaration.
///
/// E.g., `extern { .. }` or `extern C { .. }`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct ForeignMod {
pub abi: Option<StrLit>,
pub items: Vec<ForeignItem>,
}
/// Global inline assembly.
///
/// Also known as "module-level assembly" or "file-scoped assembly".
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy)]
pub struct GlobalAsm {
pub asm: Symbol,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct EnumDef {
pub variants: Vec<Variant>,
}
/// Enum variant.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Variant {
/// Attributes of the variant.
pub attrs: Vec<Attribute>,
/// Id of the variant (not the constructor, see `VariantData::ctor_id()`).
pub id: NodeId,
/// Span
pub span: Span,
/// The visibility of the variant. Syntactically accepted but not semantically.
pub vis: Visibility,
/// Name of the variant.
pub ident: Ident,
/// Fields and constructor id of the variant.
pub data: VariantData,
/// Explicit discriminant, e.g., `Foo = 1`.
pub disr_expr: Option<AnonConst>,
/// Is a macro placeholder
pub is_placeholder: bool,
}
/// Part of `use` item to the right of its prefix.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum UseTreeKind {
/// `use prefix` or `use prefix as rename`
///
/// The extra `NodeId`s are for HIR lowering, when additional statements are created for each
/// namespace.
Simple(Option<Ident>, NodeId, NodeId),
/// `use prefix::{...}`
Nested(Vec<(UseTree, NodeId)>),
/// `use prefix::*`
Glob,
}
/// A tree of paths sharing common prefixes.
/// Used in `use` items both at top-level and inside of braces in import groups.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct UseTree {
pub prefix: Path,
pub kind: UseTreeKind,
pub span: Span,
}
impl UseTree {
pub fn ident(&self) -> Ident {
match self.kind {
UseTreeKind::Simple(Some(rename), ..) => rename,
UseTreeKind::Simple(None, ..) => {
self.prefix
.segments
.last()
.expect("empty prefix in a simple import")
.ident
}
_ => panic!("`UseTree::ident` can only be used on a simple import"),
}
}
}
/// Distinguishes between `Attribute`s that decorate items and Attributes that
/// are contained as statements within items. These two cases need to be
/// distinguished for pretty-printing.
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
pub enum AttrStyle {
Outer,
Inner,
}
#[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, Copy)]
pub struct AttrId(pub usize);
impl Idx for AttrId {
fn new(idx: usize) -> Self {
AttrId(idx)
}
fn index(self) -> usize {
self.0
}
}
impl rustc_serialize::Encodable for AttrId {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_unit()
}
}
impl rustc_serialize::Decodable for AttrId {
fn decode<D: Decoder>(d: &mut D) -> Result<AttrId, D::Error> {
d.read_nil().map(|_| crate::attr::mk_attr_id())
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub struct AttrItem {
pub path: Path,
pub tokens: TokenStream,
}
/// Metadata associated with an item.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Attribute {
pub kind: AttrKind,
pub id: AttrId,
/// Denotes if the attribute decorates the following construct (outer)
/// or the construct this attribute is contained within (inner).
pub style: AttrStyle,
pub span: Span,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum AttrKind {
/// A normal attribute.
Normal(AttrItem),
/// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`).
/// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal`
/// variant (which is much less compact and thus more expensive).
///
/// Note: `self.has_name(sym::doc)` and `self.check_name(sym::doc)` succeed
/// for this variant, but this may change in the future.
/// ```
DocComment(Symbol),
}
/// `TraitRef`s appear in impls.
///
/// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all
/// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl.
/// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the
/// same as the impl's `NodeId`).
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct TraitRef {
pub path: Path,
pub ref_id: NodeId,
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct PolyTraitRef {
/// The `'a` in `<'a> Foo<&'a T>`.
pub bound_generic_params: Vec<GenericParam>,
/// The `Foo<&'a T>` in `<'a> Foo<&'a T>`.
pub trait_ref: TraitRef,
pub span: Span,
}
impl PolyTraitRef {
pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self {
PolyTraitRef {
bound_generic_params: generic_params,
trait_ref: TraitRef {
path,
ref_id: DUMMY_NODE_ID,
},
span,
}
}
}
#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)]
pub enum CrateSugar {
/// Source is `pub(crate)`.
PubCrate,
/// Source is (just) `crate`.
JustCrate,
}
pub type Visibility = Spanned<VisibilityKind>;
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum VisibilityKind {
Public,
Crate(CrateSugar),
Restricted { path: P<Path>, id: NodeId },
Inherited,
}
impl VisibilityKind {
pub fn is_pub(&self) -> bool {
if let VisibilityKind::Public = *self {
true
} else {
false
}
}
}
/// Field of a struct.
///
/// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct StructField {
pub attrs: Vec<Attribute>,
pub id: NodeId,
pub span: Span,
pub vis: Visibility,
pub ident: Option<Ident>,
pub ty: P<Ty>,
pub is_placeholder: bool,
}
/// Fields and constructor ids of enum variants and structs.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum VariantData {
/// Struct variant.
///
/// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`.
Struct(Vec<StructField>, bool),
/// Tuple variant.
///
/// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`.
Tuple(Vec<StructField>, NodeId),
/// Unit variant.
///
/// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`.
Unit(NodeId),
}
impl VariantData {
/// Return the fields of this variant.
pub fn fields(&self) -> &[StructField] {
match *self {
VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields,
_ => &[],
}
}
/// Return the `NodeId` of this variant's constructor, if it has one.
pub fn ctor_id(&self) -> Option<NodeId> {
match *self {
VariantData::Struct(..) => None,
VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id),
}
}
}
/// An item.
///
/// The name might be a dummy name in case of anonymous items.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Item {
pub attrs: Vec<Attribute>,
pub id: NodeId,
pub span: Span,
pub vis: Visibility,
pub ident: Ident,
pub kind: ItemKind,
/// Original tokens this item was parsed from. This isn't necessarily
/// available for all items, although over time more and more items should
/// have this be `Some`. Right now this is primarily used for procedural
/// macros, notably custom attributes.
///
/// Note that the tokens here do not include the outer attributes, but will
/// include inner attributes.
pub tokens: Option<TokenStream>,
}
impl Item {
/// Return the span that encompasses the attributes.
pub fn span_with_attributes(&self) -> Span {
self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
}
}
/// `extern` qualifier on a function item or function type.
#[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
pub enum Extern {
None,
Implicit,
Explicit(StrLit),
}
impl Extern {
pub fn from_abi(abi: Option<StrLit>) -> Extern {
abi.map_or(Extern::Implicit, Extern::Explicit)
}
}
/// A function header.
///
/// All the information between the visibility and the name of the function is
/// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
#[derive(Clone, Copy, RustcEncodable, RustcDecodable, Debug)]
pub struct FnHeader {
pub unsafety: Unsafety,
pub asyncness: Spanned<IsAsync>,
pub constness: Spanned<Constness>,
pub ext: Extern,
}
impl Default for FnHeader {
fn default() -> FnHeader {
FnHeader {
unsafety: Unsafety::Normal,
asyncness: dummy_spanned(IsAsync::NotAsync),
constness: dummy_spanned(Constness::NotConst),
ext: Extern::None,
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum ItemKind {
/// An `extern crate` item, with the optional *original* crate name if the crate was renamed.
///
/// E.g., `extern crate foo` or `extern crate foo_bar as foo`.
ExternCrate(Option<Name>),
/// A use declaration item (`use`).
///
/// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`.
Use(P<UseTree>),
/// A static item (`static`).
///
/// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`.
Static(P<Ty>, Mutability, P<Expr>),
/// A constant item (`const`).
///
/// E.g., `const FOO: i32 = 42;`.
Const(P<Ty>, P<Expr>),
/// A function declaration (`fn`).
///
/// E.g., `fn foo(bar: usize) -> usize { .. }`.
Fn(FnSig, Generics, P<Block>),
/// A module declaration (`mod`).
///
/// E.g., `mod foo;` or `mod foo { .. }`.
Mod(Mod),
/// An external module (`extern`).
///
/// E.g., `extern {}` or `extern "C" {}`.
ForeignMod(ForeignMod),
/// Module-level inline assembly (from `global_asm!()`).
GlobalAsm(P<GlobalAsm>),
/// A type alias (`type`).
///
/// E.g., `type Foo = Bar<u8>;`.
TyAlias(P<Ty>, Generics),
/// An enum definition (`enum`).
///
/// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
Enum(EnumDef, Generics),
/// A struct definition (`struct`).
///
/// E.g., `struct Foo<A> { x: A }`.
Struct(VariantData, Generics),
/// A union definition (`union`).
///
/// E.g., `union Foo<A, B> { x: A, y: B }`.
Union(VariantData, Generics),
/// A trait declaration (`trait`).
///
/// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec<TraitItem>),
/// Trait alias
///
/// E.g., `trait Foo = Bar + Quux;`.
TraitAlias(Generics, GenericBounds),
/// An implementation.
///
/// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
Impl(
Unsafety,
ImplPolarity,
Defaultness,
Generics,
Option<TraitRef>, // (optional) trait this impl implements
P<Ty>, // self
Vec<ImplItem>,
),
/// A macro invocation.
///
/// E.g., `foo!(..)`.
Mac(Mac),
/// A macro definition.
MacroDef(MacroDef),
}
impl ItemKind {
pub fn descriptive_variant(&self) -> &str {
match *self {
ItemKind::ExternCrate(..) => "extern crate",
ItemKind::Use(..) => "use",
ItemKind::Static(..) => "static item",
ItemKind::Const(..) => "constant item",
ItemKind::Fn(..) => "function",
ItemKind::Mod(..) => "module",
ItemKind::ForeignMod(..) => "foreign module",
ItemKind::GlobalAsm(..) => "global asm",
ItemKind::TyAlias(..) => "type alias",
ItemKind::Enum(..) => "enum",
ItemKind::Struct(..) => "struct",
ItemKind::Union(..) => "union",
ItemKind::Trait(..) => "trait",
ItemKind::TraitAlias(..) => "trait alias",
ItemKind::Mac(..) | ItemKind::MacroDef(..) | ItemKind::Impl(..) => "item",
}
}
}
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct ForeignItem {
pub attrs: Vec<Attribute>,
pub id: NodeId,
pub span: Span,
pub vis: Visibility,
pub ident: Ident,
pub kind: ForeignItemKind,
}
/// An item within an `extern` block.
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub enum ForeignItemKind {
/// A foreign function.
Fn(P<FnDecl>, Generics),
/// A foreign static item (`static ext: u8`).
Static(P<Ty>, Mutability),
/// A foreign type.
Ty,
/// A macro invocation.
Macro(Mac),
}
impl ForeignItemKind {
pub fn descriptive_variant(&self) -> &str {
match *self {
ForeignItemKind::Fn(..) => "foreign function",
ForeignItemKind::Static(..) => "foreign static item",
ForeignItemKind::Ty => "foreign type",
ForeignItemKind::Macro(..) => "macro in foreign module",
}
}
}
| 30.184429 | 100 | 0.576601 |
1e54a1c92d969c8c452df38262befedf341ff212 | 27,519 | use std::io;
use std::marker::PhantomData;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use ordered_float::OrderedFloat;
use rayon::prelude::*;
use wasabi_leb128::{ReadLeb128, WriteLeb128};
use crate::{BlockType, Idx, Limits, RawCustomSection, ValType};
use crate::error::{AddErrInfo, Error, ErrorKind, SetErrElem};
use crate::lowlevel::{CustomSection, Expr, Instr, Module, NameSection, NameSubSection, Parallel, Section, WithSize, ImportType, SectionOffset, Offsets};
/* Trait and impl for decoding/encoding between binary format (as per spec) and our own formats (see ast module) */
pub trait WasmBinary: Sized {
fn decode<R: io::Read>(reader: &mut R, state: &mut DecodeState) -> Result<Self, Error>;
fn encode<W: io::Write>(&self, writer: &mut W) -> io::Result<usize>;
}
/// "Global" state kept during decoding. Useful for error reporting (At which byte offset did
/// parsing fail?) and mapping from our AST back to the binary (function index <-> code section offset).
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct DecodeState {
pub current_offset: usize,
/// The vec of offsets is aligned with the vec of low-level sections, i.e., the index of this
/// vec corresponds to the enumeration index of raw sections in the binary.
section_offsets: Vec<usize>,
/// The index of the vec corresponds to the index of the code element, which is the function
/// index minus the number of important functions (which don't have a code/body).
code_offsets: Vec<usize>,
}
impl DecodeState {
pub fn new() -> DecodeState {
DecodeState::with_offset(0)
}
pub fn with_offset(current_offset: usize) -> DecodeState {
DecodeState {
current_offset,
section_offsets: Vec::new(),
code_offsets: Vec::new(),
}
}
/// Convert code offsets into an easier to understand mapping of function indices.
pub fn into_offsets(self, module: &Module) -> Offsets {
assert_eq!(self.section_offsets.len(), module.sections.len());
let sections = module.sections.iter()
.map(std::mem::discriminant)
.zip(self.section_offsets.into_iter())
.collect();
let imported_function_count = module.sections.iter()
.filter_map(|section|
if let Section::Import(WithSize(SectionOffset(imports))) = section {
Some(imports)
} else {
None
})
.flat_map(|imports| imports.iter()
.filter(|import|
if let ImportType::Function(_) = import.type_ { true } else { false }))
.count();
let functions_code = self.code_offsets.into_iter()
.enumerate()
.map(|(code_idx, byte_offset)|
(Idx::from(imported_function_count + code_idx), byte_offset))
.collect();
Offsets {
sections,
functions_code,
}
}
}
/* Primitive types */
impl WasmBinary for u8 {
fn decode<R: io::Read>(reader: &mut R, state: &mut DecodeState) -> Result<Self, Error> {
let byte = reader.read_u8().add_err_info::<u8>(state.current_offset)?;
state.current_offset += 1;
Ok(byte)
}
fn encode<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {
writer.write_u8(*self)?;
Ok(1)
}
}
impl WasmBinary for u32 {
fn decode<R: io::Read>(reader: &mut R, state: &mut DecodeState) -> Result<Self, Error> {
let (value, bytes_read) = reader.read_leb128().add_err_info::<u32>(state.current_offset)?;
state.current_offset += bytes_read;
Ok(value)
}
fn encode<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {
writer.write_leb128(*self)
}
}
// The WebAssembly wasm32 spec only has 32-bit integer indices, so this usize implementation is
// only for convenience when serializing Rust usize values (e.g., Rust array or vector indices).
// You should always parse values with the u32 implementation since that ensures correct range.
impl WasmBinary for usize {
fn decode<R: io::Read>(_: &mut R, _: &mut DecodeState) -> Result<Self, Error> {
unimplemented!("use u32 impl for parsing wasm32 indices")
}
fn encode<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {
if *self > u32::max_value() as usize {
// TODO Proper design would be an error type of its own for serialization, but that
// would clutter the interface of all encode() method implementations. So for now
// a custom io::Error is sufficient (since it is the only one).
return Err(io::Error::new(io::ErrorKind::InvalidData,
"wasm32 does not allow unsigned int (e.g., indices) larger than 32 bits"));
}
writer.write_leb128(*self)
}
}
impl WasmBinary for i32 {
fn decode<R: io::Read>(reader: &mut R, state: &mut DecodeState) -> Result<Self, Error> {
let (value, bytes_read) = reader.read_leb128().add_err_info::<i32>(state.current_offset)?;
state.current_offset += bytes_read;
Ok(value)
}
fn encode<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {
writer.write_leb128(*self)
}
}
impl WasmBinary for i64 {
fn decode<R: io::Read>(reader: &mut R, state: &mut DecodeState) -> Result<Self, Error> {
let (value, bytes_read) = reader.read_leb128().add_err_info::<i64>(state.current_offset)?;
state.current_offset += bytes_read;
Ok(value)
}
fn encode<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {
writer.write_leb128(*self)
}
}
impl WasmBinary for OrderedFloat<f32> {
fn decode<R: io::Read>(reader: &mut R, state: &mut DecodeState) -> Result<Self, Error> {
let value = reader.read_f32::<LittleEndian>().add_err_info::<f32>(state.current_offset)?;
state.current_offset += 4;
Ok(value.into())
}
fn encode<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {
writer.write_f32::<LittleEndian>(self.into_inner())?;
Ok(4)
}
}
impl WasmBinary for OrderedFloat<f64> {
fn decode<R: io::Read>(reader: &mut R, state: &mut DecodeState) -> Result<Self, Error> {
let value = reader.read_f64::<LittleEndian>().add_err_info::<f64>(state.current_offset)?;
state.current_offset += 8;
Ok(value.into())
}
fn encode<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {
writer.write_f64::<LittleEndian>(self.into_inner())?;
Ok(8)
}
}
/* Generic "AST combinators" */
impl<T: WasmBinary> WasmBinary for WithSize<T> {
fn decode<R: io::Read>(reader: &mut R, state: &mut DecodeState) -> Result<Self, Error> {
// The expected size is only necessary to speed up parallel decoding.
// In this (serial) case, we just use it for error checking.
let offset_before_size = state.current_offset;
let expected_size_bytes = u32::decode(reader, state).set_err_elem::<Self>()?;
let offset_before_content = state.current_offset;
let t = T::decode(reader, state)?;
let actual_size_bytes = state.current_offset - offset_before_content;
if actual_size_bytes != expected_size_bytes as usize {
return Err(Error::new::<T>(
offset_before_size,
ErrorKind::Size {
expected: expected_size_bytes,
actual: actual_size_bytes,
}));
}
Ok(WithSize(t))
}
fn encode<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {
// Write to an intermediate buffer first because we need to know the encoding size.
let mut buf = Vec::new();
let encoded_size_bytes = self.0.encode(&mut buf)?;
// Then write the size as LEB128 and copy all bytes from the intermediate buffer over.
let mut bytes_written = encoded_size_bytes.encode(writer)?;
writer.write_all(&buf)?;
bytes_written += encoded_size_bytes;
Ok(bytes_written)
}
}
impl<T: WasmBinary> WasmBinary for SectionOffset<T> {
fn decode<R: io::Read>(reader: &mut R, state: &mut DecodeState) -> Result<Self, Error> {
// Remember at which offset this section contents (T) started.
state.section_offsets.push(state.current_offset);
T::decode(reader, state).map(SectionOffset)
}
fn encode<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {
self.0.encode(writer)
}
}
/// Do not blindly trust the decoded element_count for pre-allocating a vector, but instead limit
/// the pre-allocation to some sensible size (e.g., 1 MB).
/// Otherwise a (e.g., malicious) Wasm file could request very large amounts of memory just by
/// having a large vec-size in the binary.
/// (We got struck by plenty such out of memory errors when testing our Wasm parser with AFL.
/// See tests/invalid/oom-large-vector-size/oom.wasm)
fn limit_prealloc_capacity<T>(element_count: u32) -> usize {
// Limit to 1 MB, which should be hit almost never for real (benign) Wasm binaries:
// The Wasm vectors with the largest number of elements are most likely bodies of functions
// (i.e., vectors of instructions), and a single function is likely not having that many
// instructions.
const PREALLOC_LIMIT_BYTES: usize = 1 << 20;
// Vec::with_capacity() takes number of elements, not bytes; so divide bytes by element size.
let element_limit = PREALLOC_LIMIT_BYTES / std::mem::size_of::<T>();
std::cmp::min(element_count as usize, element_limit)
}
/// Generic vectors of T.
/// see https://webassembly.github.io/spec/core/binary/conventions.html#vectors
impl<T: WasmBinary> WasmBinary for Vec<T> {
fn decode<R: io::Read>(reader: &mut R, state: &mut DecodeState) -> Result<Self, Error> {
let element_count = u32::decode(reader, state).set_err_elem::<Self>()?;
let mut vec = Vec::with_capacity(limit_prealloc_capacity::<T>(element_count));
for _ in 0..element_count {
vec.push(T::decode(reader, state)?);
}
Ok(vec)
}
fn encode<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {
let mut bytes_written = self.len().encode(writer)?;
for element in self {
bytes_written += element.encode(writer)?;
}
Ok(bytes_written)
}
}
// TODO This is no longer a generic wrapper for a Vec<WithSize<T>> construction
// that can be parsed in parallel. It is now specific to Code section parsing.
// So give it its own type, like ParallelCode
/// Provide parallel decoding/encoding when explicitly requested by Parallel<...> marker struct.
impl<T: WasmBinary + Send + Sync> WasmBinary for Parallel<Vec<WithSize<T>>> {
fn decode<R: io::Read>(reader: &mut R, state: &mut DecodeState) -> Result<Self, Error> {
// Treat the individual WithSize<T> parts as Vec<u8> (i.e., don't parse the content T just yet,
// instead read each element first into a plain byte buffer (non-parallel, but hopefully fast).
// Then decode the byte buffers in parallel to the actual T's.
// NOTE This means error reporting is subtly different compared to when we use the serial
// WithSize implementation: WithSize parses T first and then compares the actual size to
// the expected size, whereas here we assume the size is correct and the error is generated
// later during parallel parsing of the contents T (which could, e.g., yield an Eof).
let element_count = u32::decode(reader, state).set_err_elem::<Self>()?;
// Contains the offset of the size (for error reporting), the expected size, the offset of
// of content T, and the (unparsed) bytes of contents.
let mut elements: Vec<(usize, u32, usize, Vec<u8>)> = Vec::with_capacity(
limit_prealloc_capacity::<(usize, u32, usize, Vec<u8>)>(element_count));
// Read each element into a buffer first (+ the information mentioned before).
for _ in 0..element_count {
let size_offset = state.current_offset;
let content_size_bytes = u32::decode(reader, state).set_err_elem::<WithSize<T>>()?;
let offset_before_content = state.current_offset;
let mut buf = vec![0u8; content_size_bytes as usize];
reader.read_exact(buf.as_mut_slice()).add_err_info::<T>(offset_before_content)?;
state.current_offset += content_size_bytes as usize;
// Remember where each code offset started.
state.code_offsets.push(offset_before_content);
elements.push((size_offset, content_size_bytes, offset_before_content, buf));
}
// Then, parallel decoding of each buffer to actual elements T.
let decoded: Result<Vec<WithSize<T>>, Error> = elements.into_par_iter()
.map(|(size_offset, expected_size_bytes, offset_before_content, buf)| -> Result<WithSize<T>, Error> {
// Every individual code section parser gets its own state. This only works, because
// the code_offsets have already been inserted during serial parsing above, and
// the rest of the decode state is only for the global current_offset in bytes.
let mut forked_state = DecodeState::with_offset(offset_before_content);
let t = T::decode(&mut &buf[..], &mut forked_state)?;
// While a too short size will result in an Eof error, we still need to check that
// the size was not too long (i.e., that the whole buffer has been consumed).
let actual_size_bytes = forked_state.current_offset - offset_before_content;
if actual_size_bytes != expected_size_bytes as usize {
return Err(Error::new::<T>(
size_offset,
ErrorKind::Size {
expected: expected_size_bytes,
actual: actual_size_bytes,
}));
}
Ok(WithSize(t))
})
.collect();
Ok(Parallel(decoded?))
}
fn encode<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {
let mut bytes_written = self.0.len().encode(writer)?;
// Encode elements to buffers in parallel.
let encoded: io::Result<Vec<Vec<u8>>> = self.0.par_iter()
.map(|element: &WithSize<T>| {
let mut buf = Vec::new();
element.0.encode(&mut buf)?;
Ok(buf)
})
.collect();
// Write sizes and buffer contents to actual writer (non-parallel, but hopefully fast).
for buf in encoded? {
bytes_written += buf.encode(writer)?;
}
Ok(bytes_written)
}
}
impl<T: WasmBinary> WasmBinary for Box<[T]> {
fn decode<R: io::Read>(reader: &mut R, state: &mut DecodeState) -> Result<Self, Error> {
// Reuse Vec implementation, and just drop capacity field to get Box<[T]>.
Ok(Vec::<T>::decode(reader, state)?.into_boxed_slice())
}
fn encode<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {
// Essentially the same implementation as for Vec<T>, but we cannot reuse it, since we can't
// convert a Box<[T]> to a Vec<T> without owning the box (or allocating).
let mut bytes_written = self.len().encode(writer)?;
for element in self.iter() {
bytes_written += element.encode(writer)?;
}
Ok(bytes_written)
}
}
/// UTF-8 strings.
impl WasmBinary for String {
fn decode<R: io::Read>(reader: &mut R, state: &mut DecodeState) -> Result<Self, Error> {
// Reuse Vec<u8> implementation, then convert to UTF-8, consuming the buffer so no
// re-allocation is necessary.
let offset_before = state.current_offset;
let buf: Vec<u8> = Vec::decode(reader, state).set_err_elem::<String>()?;
Ok(String::from_utf8(buf).add_err_info::<String>(offset_before)?)
}
fn encode<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {
// Cannot reuse implementation of Vec<u8> for writing, because we only have the string
// borrowed, but conversion via into_bytes (which produces a Vec) would require owning it.
let mut bytes_written = self.len().encode(writer)?;
writer.write_all(self.as_bytes())?;
bytes_written += self.len();
Ok(bytes_written)
}
}
/* Special cases that cannot be derived and need a manual impl */
impl WasmBinary for Module {
fn decode<R: io::Read>(reader: &mut R, state: &mut DecodeState) -> Result<Self, Error> {
// Check magic number.
let mut magic_number = [0u8; 4];
reader.read_exact(&mut magic_number).add_err_info::<Module>(0)?;
if &magic_number != b"\0asm" {
return Err(Error::new::<Module>(0, ErrorKind::MagicNumber { actual: magic_number }));
}
state.current_offset += 4;
// Check version.
let version = reader.read_u32::<LittleEndian>().add_err_info::<Module>(4)?;
if version != 1 {
return Err(Error::new::<Module>(4, ErrorKind::Version { actual: version }));
}
state.current_offset += 4;
// Parse sections until EOF.
let mut sections = Vec::new();
let mut last_section_type = None;
loop {
let offset_section_begin = state.current_offset;
match Section::decode(reader, state) {
Ok(mut section) => {
// To insert custom sections at the correct place when serializing again, we
// need to remember after which other non-custom section they originally came.
if let Section::Custom(CustomSection::Raw(r)) = &mut section {
r.after = last_section_type;
} else {
last_section_type = Some(std::mem::discriminant(§ion));
}
sections.push(section);
}
// If we cannot even read one more byte (the ID of the next section), we are done.
Err(e) if e.kind() == &ErrorKind::Eof && e.offset() == offset_section_begin => break,
// All other errors (including Eof in the _middle_ of a section, i.e.,
// where we read at least some bytes), are an error and will be reported.
Err(e) => return Err(e)
};
}
Ok(Module { sections })
}
fn encode<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {
writer.write_all(b"\0asm")?;
writer.write_all(&[1, 0, 0, 0])?;
let mut bytes_written = 8;
for section in &self.sections {
bytes_written += section.encode(writer)?;
}
Ok(bytes_written)
}
}
/// needs manual impl because of block handling: End op-code terminates body, but only if block stack is empty
impl WasmBinary for Expr {
fn decode<R: io::Read>(reader: &mut R, state: &mut DecodeState) -> Result<Self, Error> {
let mut instructions = Vec::new();
let mut block_depth = 0;
while block_depth >= 0 {
let instr = Instr::decode(reader, state)?;
block_depth += match instr {
Instr::Block(..) | Instr::Loop(..) | Instr::If(..) => 1,
// Else ends a block, but also starts a new one
Instr::Else => -1 + 1,
Instr::End => -1,
_ => 0
};
instructions.push(instr);
}
Ok(Expr(instructions))
}
fn encode<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {
let mut bytes_written = 0;
for instruction in &self.0 {
bytes_written += instruction.encode(writer)?;
}
Ok(bytes_written)
}
}
/// Needs manual impl because of compressed format: even though BlockType is "logically" an enum,
/// it has no tag, because they know that 0x40 (empty block) and ValType bytes are disjoint.
impl WasmBinary for BlockType {
fn decode<R: io::Read>(reader: &mut R, state: &mut DecodeState) -> Result<Self, Error> {
let tag = u8::decode(reader, state).set_err_elem::<Self>()?;
Ok(BlockType(match tag {
0x40 => None,
byte => {
// Retry, now interpreting as ValType.
let buf = [byte; 1];
state.current_offset -= 1;
Some(ValType::decode(&mut &buf[..], state)?)
}
}))
}
fn encode<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {
match self {
BlockType(None) => 0x40u8.encode(writer),
BlockType(Some(ref val_type)) => val_type.encode(writer)
}
}
}
/// Needs manual impl because the tag if max is present comes at the beginning of the struct, not
/// before the max field.
impl WasmBinary for Limits {
fn decode<R: io::Read>(reader: &mut R, state: &mut DecodeState) -> Result<Self, Error> {
let tag = u8::decode(reader, state).set_err_elem::<Self>()?;
Ok(match tag {
0x00 => Limits {
initial_size: u32::decode(reader, state)?,
max_size: None,
},
0x01 => Limits {
initial_size: u32::decode(reader, state)?,
max_size: Some(u32::decode(reader, state)?),
},
byte => return Err(Error::invalid_tag::<Limits>(state.current_offset, byte))
})
}
fn encode<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {
let mut bytes_written = 0;
match self.max_size {
None => {
bytes_written += 0x00u8.encode(writer)?;
bytes_written += self.initial_size.encode(writer)?;
}
Some(ref max_size) => {
bytes_written += 0x01u8.encode(writer)?;
bytes_written += self.initial_size.encode(writer)?;
bytes_written += max_size.encode(writer)?;
}
}
Ok(bytes_written)
}
}
impl<T> WasmBinary for PhantomData<T> {
fn decode<R: io::Read>(_: &mut R, _: &mut DecodeState) -> Result<Self, Error> { Ok(PhantomData) }
fn encode<W: io::Write>(&self, _: &mut W) -> io::Result<usize> { Ok(0) }
}
/* Custom sections and name subsection parsing. */
impl WasmBinary for CustomSection {
fn decode<R: io::Read>(reader: &mut R, state: &mut DecodeState) -> Result<Self, Error> {
let size_offset = state.current_offset;
let section_size_bytes = u32::decode(reader, state).set_err_elem::<Self>()?;
// Each custom section must have a name, see https://webassembly.github.io/spec/core/binary/modules.html#binary-customsec
let name_offset = state.current_offset;
let name = String::decode(reader, state).set_err_elem::<Self>()?;
let name_size_bytes = state.current_offset - name_offset;
// Remember the offset of this custom section in the binary.
state.section_offsets.push(name_offset);
// The size of the section includes also the bytes of the name, so we have to subtract
// the size of the name to get the size of the content only.
let content_size_bytes = (section_size_bytes as usize).checked_sub(name_size_bytes)
// Check that the name alone is not already longer than the overall size of the section.
.ok_or_else(|| Error::new::<Self>(
size_offset,
ErrorKind::Size {
expected: section_size_bytes,
actual: state.current_offset - size_offset,
}))?;
// Read to a buffer first, so that we can always fall back to returning a raw custom section.
let mut content_state = DecodeState::with_offset(state.current_offset);
let mut content = vec![0u8; content_size_bytes as usize];
reader.read_exact(content.as_mut_slice()).add_err_info::<Self>(state.current_offset)?;
state.current_offset += content_size_bytes;
let section = match name.as_str() {
"name" => {
// Unfortunately, some name sections are invalid (e.g., from the UE4 engine, an
// early Wasm binary). But we don't want to fail completely, so downgrade to warning.
match NameSection::decode(&mut content.as_slice(), &mut content_state) {
Ok(name_section) => CustomSection::Name(name_section),
Err(err) => {
eprintln!("Warning: Wasm binary at offset 0x{:x} ({}): could not parse name section, ignoring whole section...", size_offset, size_offset);
eprintln!("Caused by: {}", err);
// Keep the section as a raw section at least
CustomSection::Raw(RawCustomSection { name, content, after: None })
}
}
}
// Unknown custom section: parse the rest (excluding the name, which we already did.)
// After is set later correctly by Module::decode().
_ => CustomSection::Raw(RawCustomSection { name, content, after: None }),
};
Ok(section)
}
fn encode<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {
// Write to an intermediate buffer first because we need to know the custom section size.
let mut buf = Vec::new();
match self {
CustomSection::Name(name_sec) => {
"name".to_string().encode(&mut buf)?;
name_sec.encode(&mut buf)?;
}
CustomSection::Raw(sec) => {
sec.name.encode(&mut buf)?;
buf.extend_from_slice(&sec.content);
}
}
// Then write the size as LEB128 and copy all bytes from the intermediate buffer over.
let encoded_size_bytes = buf.len();
let mut bytes_written = encoded_size_bytes.encode(writer)?;
writer.write_all(&buf)?;
bytes_written += encoded_size_bytes;
Ok(bytes_written)
}
}
impl WasmBinary for NameSection {
fn decode<R: io::Read>(reader: &mut R, state: &mut DecodeState) -> Result<Self, Error> {
// Parse subsections until EOF, cf. Module sections parsing.
let mut subsections = Vec::new();
loop {
let offset_section_begin = state.current_offset;
match NameSubSection::decode(reader, state) {
Ok(section) => subsections.push(section),
// If we cannot even read one more byte (the ID of the next section), we are done.
Err(e) if e.kind() == &ErrorKind::Eof && e.offset() == offset_section_begin => break,
// All other errors (including Eof in the _middle_ of a section, i.e.,
// where we read at least some bytes), are an error and will be reported.
Err(e) => return Err(e)
};
}
Ok(NameSection { subsections })
}
fn encode<W: io::Write>(&self, writer: &mut W) -> io::Result<usize> {
let mut bytes_written = 0;
for section in &self.subsections {
bytes_written += section.encode(writer)?;
}
Ok(bytes_written)
}
} | 42.797823 | 163 | 0.602202 |
0e399f0727fd89cab8cf2209cdd1d89afc07c8cd | 927 | use azure_core::headers::{
account_kind_from_headers, date_from_headers, request_id_from_headers, sku_name_from_headers,
};
use azure_core::RequestId;
use chrono::{DateTime, Utc};
use http::HeaderMap;
#[derive(Debug, Clone)]
pub struct GetAccountInformationResponse {
pub request_id: RequestId,
pub date: DateTime<Utc>,
pub sku_name: String,
pub account_kind: String,
}
impl GetAccountInformationResponse {
pub(crate) fn from_headers(
headers: &HeaderMap,
) -> crate::Result<GetAccountInformationResponse> {
let request_id = request_id_from_headers(headers)?;
let date = date_from_headers(headers)?;
let sku_name = sku_name_from_headers(headers)?;
let account_kind = account_kind_from_headers(headers)?;
Ok(GetAccountInformationResponse {
request_id,
date,
sku_name,
account_kind,
})
}
}
| 28.090909 | 97 | 0.681769 |
db54fa1aa4e42292c678c8b18e88c1bf66c181df | 1,425 | extern crate basic_web_server;
use std::net::TcpListener;
use std::net::TcpStream;
use std::io::prelude::*;
use std::fs;
use std::time::Duration;
use basic_web_server::ThreadPool;
use std::thread;
fn main() {
let address = "127.0.0.1:3000";
let listener = TcpListener::bind(address).unwrap();
let thread_pool = ThreadPool::new(4);
for stream in listener.incoming() {
let stream = stream.unwrap();
thread_pool.execute(|| handle_connection(stream));
}
println!("shutting down");
}
fn handle_connection(mut stream: TcpStream) {
let file_name;
let mut status = 200;
let mut status_text = "ok";
let mut buffer = [0; 1024];
stream.read(&mut buffer).unwrap();
if buffer.starts_with(path("/").as_bytes()) {
file_name = "index.html";
}
else if buffer.starts_with(path("/sleep").as_bytes()) {
thread::sleep(Duration::from_secs(10));
file_name = "sleep.html"
} else {
status = 404;
status_text = "not found";
file_name = "404.html";
}
let html = fs::read_to_string(file_name).unwrap();
let response = format!("HTTP/1.1 {} {}\r\n\r\n{}", status, status_text, html);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
println!("request:\n{}", String::from_utf8_lossy(&buffer));
}
fn path(location: &str) -> String {
format!("GET {} HTTP/1.1\r\n", location)
} | 26.388889 | 82 | 0.620351 |
4a0aa93f941222c0080f5633c884f18ace9c9933 | 270 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct EnvironmentId {
index: usize,
}
impl EnvironmentId {
pub fn new(index: usize) -> EnvironmentId {
EnvironmentId { index }
}
pub fn get_id(&self) -> usize {
self.index
}
}
| 18 | 50 | 0.6 |
1819b671f4c4d49f75d18754380ce32d19e2f340 | 18,193 | use crate::common::{hash::PyHash, lock::PyRwLock};
use crate::{
builtins::{PyStrRef, PyTypeRef},
function::{FromArgs, FuncArgs, IntoPyResult, OptionalArg},
protocol::{PyBuffer, PyIterReturn, PyMappingMethods},
utils::Either,
IdProtocol, PyComparisonValue, PyObjectRef, PyRef, PyResult, PyValue, TypeProtocol,
VirtualMachine,
};
use crossbeam_utils::atomic::AtomicCell;
use std::cmp::Ordering;
bitflags! {
pub struct PyTypeFlags: u64 {
const HEAPTYPE = 1 << 9;
const BASETYPE = 1 << 10;
const METHOD_DESCR = 1 << 17;
const HAS_DICT = 1 << 40;
#[cfg(debug_assertions)]
const _CREATED_WITH_FLAGS = 1 << 63;
}
}
impl PyTypeFlags {
// Default used for both built-in and normal classes: empty, for now.
// CPython default: Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | Py_TPFLAGS_HAVE_VERSION_TAG
pub const DEFAULT: Self = Self::empty();
// CPython: See initialization of flags in type_new.
/// Used for types created in Python. Subclassable and are a
/// heaptype.
pub fn heap_type_flags() -> Self {
Self::DEFAULT | Self::HEAPTYPE | Self::BASETYPE
}
pub fn has_feature(self, flag: Self) -> bool {
self.contains(flag)
}
#[cfg(debug_assertions)]
pub fn is_created_with_flags(self) -> bool {
self.contains(Self::_CREATED_WITH_FLAGS)
}
}
impl Default for PyTypeFlags {
fn default() -> Self {
Self::DEFAULT
}
}
pub(crate) type GenericMethod = fn(&PyObjectRef, FuncArgs, &VirtualMachine) -> PyResult;
pub(crate) type NewFunc = fn(PyTypeRef, FuncArgs, &VirtualMachine) -> PyResult;
pub(crate) type DelFunc = fn(&PyObjectRef, &VirtualMachine) -> PyResult<()>;
pub(crate) type DescrGetFunc =
fn(PyObjectRef, Option<PyObjectRef>, Option<PyObjectRef>, &VirtualMachine) -> PyResult;
pub(crate) type DescrSetFunc =
fn(PyObjectRef, PyObjectRef, Option<PyObjectRef>, &VirtualMachine) -> PyResult<()>;
pub(crate) type HashFunc = fn(&PyObjectRef, &VirtualMachine) -> PyResult<PyHash>;
pub(crate) type RichCompareFunc = fn(
&PyObjectRef,
&PyObjectRef,
PyComparisonOp,
&VirtualMachine,
) -> PyResult<Either<PyObjectRef, PyComparisonValue>>;
pub(crate) type GetattroFunc = fn(PyObjectRef, PyStrRef, &VirtualMachine) -> PyResult;
pub(crate) type SetattroFunc =
fn(&PyObjectRef, PyStrRef, Option<PyObjectRef>, &VirtualMachine) -> PyResult<()>;
pub(crate) type BufferFunc = fn(&PyObjectRef, &VirtualMachine) -> PyResult<PyBuffer>;
pub(crate) type MappingFunc = fn(&PyObjectRef, &VirtualMachine) -> PyResult<PyMappingMethods>;
pub(crate) type IterFunc = fn(PyObjectRef, &VirtualMachine) -> PyResult;
pub(crate) type IterNextFunc = fn(&PyObjectRef, &VirtualMachine) -> PyResult<PyIterReturn>;
// The corresponding field in CPython is `tp_` prefixed.
// e.g. name -> tp_name
#[derive(Default)]
pub struct PyTypeSlots {
pub name: PyRwLock<Option<String>>, // tp_name, not class name
// tp_basicsize, tp_itemsize
// Methods to implement standard operations
// Method suites for standard classes
// tp_as_number
// tp_as_sequence
pub as_mapping: AtomicCell<Option<MappingFunc>>,
// More standard operations (here for binary compatibility)
pub hash: AtomicCell<Option<HashFunc>>,
pub call: AtomicCell<Option<GenericMethod>>,
// tp_str
pub getattro: AtomicCell<Option<GetattroFunc>>,
pub setattro: AtomicCell<Option<SetattroFunc>>,
// Functions to access object as input/output buffer
pub as_buffer: Option<BufferFunc>,
// Assigned meaning in release 2.1
// rich comparisons
pub richcompare: AtomicCell<Option<RichCompareFunc>>,
// Iterators
pub iter: AtomicCell<Option<IterFunc>>,
pub iternext: AtomicCell<Option<IterNextFunc>>,
// Flags to define presence of optional/expanded features
pub flags: PyTypeFlags,
// tp_doc
pub doc: Option<&'static str>,
// Strong reference on a heap type, borrowed reference on a static type
// tp_base
// tp_dict
pub descr_get: AtomicCell<Option<DescrGetFunc>>,
pub descr_set: AtomicCell<Option<DescrSetFunc>>,
// tp_dictoffset
// tp_init
// tp_alloc
pub new: AtomicCell<Option<NewFunc>>,
// tp_free
// tp_is_gc
// tp_bases
// tp_mro
// tp_cache
// tp_subclasses
// tp_weaklist
pub del: AtomicCell<Option<DelFunc>>,
}
impl PyTypeSlots {
pub fn from_flags(flags: PyTypeFlags) -> Self {
Self {
flags,
..Default::default()
}
}
}
impl std::fmt::Debug for PyTypeSlots {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("PyTypeSlots")
}
}
#[pyimpl]
pub trait SlotConstructor: PyValue {
type Args: FromArgs;
#[pyslot]
fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
let args: Self::Args = args.bind(vm)?;
Self::py_new(cls, args, vm)
}
fn py_new(cls: PyTypeRef, args: Self::Args, vm: &VirtualMachine) -> PyResult;
}
#[pyimpl]
pub trait SlotDestructor: PyValue {
#[inline] // for __del__
#[pyslot]
fn slot_del(zelf: &PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
if let Some(zelf) = zelf.downcast_ref() {
Self::del(zelf, vm)
} else {
Err(vm.new_type_error("unexpected payload for __del__".to_owned()))
}
}
#[pymethod]
fn __del__(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
Self::slot_del(&zelf, vm)
}
fn del(zelf: &PyRef<Self>, vm: &VirtualMachine) -> PyResult<()>;
}
#[pyimpl]
pub trait Callable: PyValue {
#[pyslot]
fn slot_call(zelf: &PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
if let Some(zelf) = zelf.downcast_ref() {
Self::call(zelf, args, vm)
} else {
Err(vm.new_type_error("unexpected payload for __call__".to_owned()))
}
}
#[pymethod]
fn __call__(zelf: PyRef<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
Self::call(&zelf, args, vm)
}
fn call(zelf: &PyRef<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult;
}
#[pyimpl]
pub trait SlotDescriptor: PyValue {
#[pyslot]
fn descr_get(
zelf: PyObjectRef,
obj: Option<PyObjectRef>,
cls: Option<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult;
#[pymethod(magic)]
fn get(
zelf: PyObjectRef,
obj: PyObjectRef,
cls: OptionalArg<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult {
Self::descr_get(zelf, Some(obj), cls.into_option(), vm)
}
fn _zelf(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
zelf.try_into_value(vm)
}
fn _unwrap(
zelf: PyObjectRef,
obj: Option<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<(PyRef<Self>, PyObjectRef)> {
let zelf = Self::_zelf(zelf, vm)?;
let obj = vm.unwrap_or_none(obj);
Ok((zelf, obj))
}
fn _check(
zelf: PyObjectRef,
obj: Option<PyObjectRef>,
vm: &VirtualMachine,
) -> Result<(PyRef<Self>, PyObjectRef), PyResult> {
// CPython descr_check
if let Some(obj) = obj {
// if (!PyObject_TypeCheck(obj, descr->d_type)) {
// PyErr_Format(PyExc_TypeError,
// "descriptor '%V' for '%.100s' objects "
// "doesn't apply to a '%.100s' object",
// descr_name((PyDescrObject *)descr), "?",
// descr->d_type->slot_name,
// obj->ob_type->slot_name);
// *pres = NULL;
// return 1;
// } else {
Ok((Self::_zelf(zelf, vm).unwrap(), obj))
// }
} else {
Err(Ok(zelf))
}
}
fn _cls_is<T>(cls: &Option<PyObjectRef>, other: &T) -> bool
where
T: IdProtocol,
{
cls.as_ref().map_or(false, |cls| other.is(cls))
}
}
#[pyimpl]
pub trait Hashable: PyValue {
#[pyslot]
fn slot_hash(zelf: &PyObjectRef, vm: &VirtualMachine) -> PyResult<PyHash> {
if let Some(zelf) = zelf.downcast_ref() {
Self::hash(zelf, vm)
} else {
Err(vm.new_type_error("unexpected payload for __hash__".to_owned()))
}
}
#[pymethod]
fn __hash__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyHash> {
Self::hash(&zelf, vm)
}
fn hash(zelf: &PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyHash>;
}
pub trait Unhashable: PyValue {}
impl<T> Hashable for T
where
T: Unhashable,
{
fn hash(_zelf: &PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyHash> {
Err(vm.new_type_error(format!("unhashable type: '{}'", _zelf.class().name())))
}
}
#[pyimpl]
pub trait Comparable: PyValue {
#[pyslot]
fn slot_richcompare(
zelf: &PyObjectRef,
other: &PyObjectRef,
op: PyComparisonOp,
vm: &VirtualMachine,
) -> PyResult<Either<PyObjectRef, PyComparisonValue>> {
if let Some(zelf) = zelf.downcast_ref() {
Self::cmp(zelf, other, op, vm).map(Either::B)
} else {
Err(vm.new_type_error(format!("unexpected payload for {}", op.method_name())))
}
}
fn cmp(
zelf: &PyRef<Self>,
other: &PyObjectRef,
op: PyComparisonOp,
vm: &VirtualMachine,
) -> PyResult<PyComparisonValue>;
#[pymethod(magic)]
fn eq(
zelf: PyRef<Self>,
other: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyComparisonValue> {
Self::cmp(&zelf, &other, PyComparisonOp::Eq, vm)
}
#[pymethod(magic)]
fn ne(
zelf: PyRef<Self>,
other: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyComparisonValue> {
Self::cmp(&zelf, &other, PyComparisonOp::Ne, vm)
}
#[pymethod(magic)]
fn lt(
zelf: PyRef<Self>,
other: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyComparisonValue> {
Self::cmp(&zelf, &other, PyComparisonOp::Lt, vm)
}
#[pymethod(magic)]
fn le(
zelf: PyRef<Self>,
other: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyComparisonValue> {
Self::cmp(&zelf, &other, PyComparisonOp::Le, vm)
}
#[pymethod(magic)]
fn ge(
zelf: PyRef<Self>,
other: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyComparisonValue> {
Self::cmp(&zelf, &other, PyComparisonOp::Ge, vm)
}
#[pymethod(magic)]
fn gt(
zelf: PyRef<Self>,
other: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyComparisonValue> {
Self::cmp(&zelf, &other, PyComparisonOp::Gt, vm)
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum PyComparisonOp {
// be intentional with bits so that we can do eval_ord with just a bitwise and
// bits: | Equal | Greater | Less |
Lt = 0b001,
Gt = 0b010,
Ne = 0b011,
Eq = 0b100,
Le = 0b101,
Ge = 0b110,
}
use PyComparisonOp::*;
impl PyComparisonOp {
pub fn eq_only(
self,
f: impl FnOnce() -> PyResult<PyComparisonValue>,
) -> PyResult<PyComparisonValue> {
match self {
Self::Eq => f(),
Self::Ne => f().map(|x| x.map(|eq| !eq)),
_ => Ok(PyComparisonValue::NotImplemented),
}
}
pub fn eval_ord(self, ord: Ordering) -> bool {
let bit = match ord {
Ordering::Less => Lt,
Ordering::Equal => Eq,
Ordering::Greater => Gt,
};
self as u8 & bit as u8 != 0
}
pub fn swapped(self) -> Self {
match self {
Lt => Gt,
Le => Ge,
Eq => Eq,
Ne => Ne,
Ge => Le,
Gt => Lt,
}
}
pub fn method_name(self) -> &'static str {
match self {
Lt => "__lt__",
Le => "__le__",
Eq => "__eq__",
Ne => "__ne__",
Ge => "__ge__",
Gt => "__gt__",
}
}
pub fn operator_token(self) -> &'static str {
match self {
Lt => "<",
Le => "<=",
Eq => "==",
Ne => "!=",
Ge => ">=",
Gt => ">",
}
}
/// Returns an appropriate return value for the comparison when a and b are the same object, if an
/// appropriate return value exists.
pub fn identical_optimization(self, a: &impl IdProtocol, b: &impl IdProtocol) -> Option<bool> {
self.map_eq(|| a.is(b))
}
/// Returns `Some(true)` when self is `Eq` and `f()` returns true. Returns `Some(false)` when self
/// is `Ne` and `f()` returns true. Otherwise returns `None`.
pub fn map_eq(self, f: impl FnOnce() -> bool) -> Option<bool> {
match self {
Self::Eq => {
if f() {
Some(true)
} else {
None
}
}
Self::Ne => {
if f() {
Some(false)
} else {
None
}
}
_ => None,
}
}
}
#[pyimpl]
pub trait SlotGetattro: PyValue {
#[pyslot]
fn slot_getattro(obj: PyObjectRef, name: PyStrRef, vm: &VirtualMachine) -> PyResult {
if let Ok(zelf) = obj.downcast::<Self>() {
Self::getattro(zelf, name, vm)
} else {
Err(vm.new_type_error("unexpected payload for __getattribute__".to_owned()))
}
}
// TODO: make zelf: &PyRef<Self>
fn getattro(zelf: PyRef<Self>, name: PyStrRef, vm: &VirtualMachine) -> PyResult;
#[pymethod]
fn __getattribute__(zelf: PyRef<Self>, name: PyStrRef, vm: &VirtualMachine) -> PyResult {
Self::getattro(zelf, name, vm)
}
}
#[pyimpl]
pub trait SlotSetattro: PyValue {
#[pyslot]
fn slot_setattro(
obj: &PyObjectRef,
name: PyStrRef,
value: Option<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<()> {
if let Some(zelf) = obj.downcast_ref::<Self>() {
Self::setattro(zelf, name, value, vm)
} else {
Err(vm.new_type_error("unexpected payload for __setattr__".to_owned()))
}
}
fn setattro(
zelf: &PyRef<Self>,
name: PyStrRef,
value: Option<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<()>;
#[pymethod]
fn __setattr__(
zelf: PyRef<Self>,
name: PyStrRef,
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<()> {
Self::setattro(&zelf, name, Some(value), vm)
}
#[pymethod]
fn __delattr__(zelf: PyRef<Self>, name: PyStrRef, vm: &VirtualMachine) -> PyResult<()> {
Self::setattro(&zelf, name, None, vm)
}
}
#[pyimpl]
pub trait AsBuffer: PyValue {
// TODO: `flags` parameter
#[pyslot]
fn slot_as_buffer(zelf: &PyObjectRef, vm: &VirtualMachine) -> PyResult<PyBuffer> {
let zelf = zelf
.downcast_ref()
.ok_or_else(|| vm.new_type_error("unexpected payload for as_buffer".to_owned()))?;
Self::as_buffer(zelf, vm)
}
fn as_buffer(zelf: &PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyBuffer>;
}
#[pyimpl]
pub trait AsMapping: PyValue {
#[pyslot]
fn slot_as_mapping(zelf: &PyObjectRef, vm: &VirtualMachine) -> PyResult<PyMappingMethods> {
let zelf = zelf
.downcast_ref()
.ok_or_else(|| vm.new_type_error("unexpected payload for as_mapping".to_owned()))?;
Self::as_mapping(zelf, vm)
}
fn downcast(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
zelf.downcast::<Self>().map_err(|obj| {
vm.new_type_error(format!(
"{} type is required, not {}",
Self::class(vm),
obj.class()
))
})
}
fn downcast_ref<'a>(zelf: &'a PyObjectRef, vm: &VirtualMachine) -> PyResult<&'a PyRef<Self>> {
zelf.downcast_ref::<Self>().ok_or_else(|| {
vm.new_type_error(format!(
"{} type is required, not {}",
Self::class(vm),
zelf.class()
))
})
}
fn as_mapping(zelf: &PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyMappingMethods>;
fn length(zelf: PyObjectRef, _vm: &VirtualMachine) -> PyResult<usize>;
fn subscript(zelf: PyObjectRef, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult;
fn ass_subscript(
zelf: PyObjectRef,
needle: PyObjectRef,
value: Option<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<()>;
}
#[pyimpl]
pub trait Iterable: PyValue {
#[pyslot]
#[pymethod(name = "__iter__")]
fn slot_iter(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult {
if let Ok(zelf) = zelf.downcast() {
Self::iter(zelf, vm)
} else {
Err(vm.new_type_error("unexpected payload for __iter__".to_owned()))
}
}
fn iter(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult;
}
#[pyimpl(with(Iterable))]
pub trait SlotIterator: PyValue + Iterable {
#[pyslot]
fn slot_iternext(zelf: &PyObjectRef, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
if let Some(zelf) = zelf.downcast_ref() {
Self::next(zelf, vm)
} else {
Err(vm.new_type_error("unexpected payload for __next__".to_owned()))
}
}
fn next(zelf: &PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn>;
#[pymethod]
fn __next__(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult {
Self::slot_iternext(&zelf, vm).into_pyresult(vm)
}
}
pub trait IteratorIterable: PyValue {}
impl<T> Iterable for T
where
T: IteratorIterable,
{
fn slot_iter(zelf: PyObjectRef, _vm: &VirtualMachine) -> PyResult {
Ok(zelf)
}
fn iter(_zelf: PyRef<Self>, _vm: &VirtualMachine) -> PyResult {
unreachable!("slot_iter is implemented");
}
}
| 29.0623 | 102 | 0.575771 |
e8a798ab0a7ecfad3992b2faad81fa6e0efab8c7 | 29,794 | use std::rc::Rc;
use crate::category::Category;
use crate::dimension::Dimen;
use crate::font::Font;
use crate::font_metrics::FontMetrics;
use crate::math_code::MathCode;
use crate::parser::Parser;
use crate::token::Token;
enum AtClause {
Natural,
Scaled(u16),
At(Dimen),
}
pub struct SpecialVariables<'a> {
pub prev_depth: Option<&'a mut Dimen>,
}
impl<'a> Parser<'a> {
fn is_variable_assignment_head(&mut self) -> bool {
self.is_integer_variable_head() || self.is_dimen_variable_head()
}
fn is_macro_assignment_head(&mut self) -> bool {
self.is_next_expanded_token_in_set_of_primitives(&["def"])
}
fn is_let_assignment_head(&mut self) -> bool {
self.is_next_expanded_token_in_set_of_primitives(&["let"])
}
fn is_arithmetic_head(&mut self) -> bool {
self.is_next_expanded_token_in_set_of_primitives(&[
"advance", "multiply", "divide",
])
}
fn is_shorthand_definition_head(&mut self) -> bool {
self.is_next_expanded_token_in_set_of_primitives(&["mathchardef"])
}
fn is_code_assignment_head(&mut self) -> bool {
self.is_next_expanded_token_in_set_of_primitives(&["mathcode"])
}
fn is_font_assignment_head(&mut self) -> bool {
self.is_next_expanded_token_in_set_of_primitives(&["font"])
}
fn is_fontdef_assignment_head(&mut self) -> bool {
match self.peek_expanded_token() {
Some(tok) => self.state.get_fontdef(&tok).is_some(),
None => false,
}
}
fn is_intimate_assignment_head(&mut self) -> bool {
self.is_next_expanded_token_in_set_of_primitives(&["prevdepth"])
}
fn is_global_assignment_head(&mut self) -> bool {
self.is_intimate_assignment_head()
}
fn is_simple_assignment_head(&mut self) -> bool {
self.is_let_assignment_head()
|| self.is_variable_assignment_head()
|| self.is_arithmetic_head()
|| self.is_box_assignment_head()
|| self.is_shorthand_definition_head()
|| self.is_code_assignment_head()
|| self.is_font_assignment_head()
|| self.is_fontdef_assignment_head()
|| self.is_global_assignment_head()
}
fn is_assignment_prefix(&mut self) -> bool {
self.is_next_expanded_token_in_set_of_primitives(&["global"])
}
pub fn is_assignment_head(&mut self) -> bool {
self.is_assignment_prefix()
|| self.is_macro_assignment_head()
|| self.is_simple_assignment_head()
}
fn parse_variable_assignment(&mut self, global: bool) {
if self.is_integer_variable_head() {
let variable = self.parse_integer_variable();
self.parse_equals_expanded();
let value = self.parse_number();
variable.set(self.state, global, value);
} else if self.is_dimen_variable_head() {
let variable = self.parse_dimen_variable();
self.parse_equals_expanded();
let value = self.parse_dimen();
variable.set(self.state, global, value);
} else {
panic!("unimplemented");
}
}
// Parses a control sequence or special char token to use for \def or \let
// names
fn parse_unexpanded_control_sequence(&mut self) -> Token {
match self.lex_unexpanded_token() {
Some(token) => match token {
Token::ControlSequence(_) => token,
Token::Char(_, Category::Active) => token,
_ => panic!(
"Invalid token found while looking for control sequence: {:?}",
token
),
},
None => panic!("EOF found parsing control sequence"),
}
}
fn parse_let_assignment(&mut self, global: bool) {
let tok = self.lex_expanded_token().unwrap();
if self.state.is_token_equal_to_prim(&tok, "let") {
let let_name = self.parse_unexpanded_control_sequence();
self.parse_equals_unexpanded();
self.parse_optional_space_unexpanded();
let let_value = self.lex_unexpanded_token().unwrap();
self.state.set_let(global, &let_name, &let_value);
} else {
panic!("unimplemented");
}
}
fn parse_arithmetic(&mut self, global: bool) {
let tok = self.lex_expanded_token().unwrap();
let variable = self.parse_integer_variable();
self.parse_optional_keyword_expanded("by");
self.parse_optional_spaces_expanded();
if self.state.is_token_equal_to_prim(&tok, "advance") {
let number = self.parse_number();
// TODO(xymostech): ensure this doesn't overflow
variable.set(self.state, global, variable.get(self.state) + number);
} else if self.state.is_token_equal_to_prim(&tok, "multiply") {
let number = self.parse_number();
// TODO(xymostech): ensure this doesn't overflow
variable.set(self.state, global, variable.get(self.state) * number);
} else if self.state.is_token_equal_to_prim(&tok, "divide") {
let number = self.parse_number();
variable.set(self.state, global, variable.get(self.state) / number);
} else {
panic!("Invalid arithmetic head: {:?}", tok);
}
}
fn parse_macro_assignment(&mut self, global: bool) {
let tok = self.lex_expanded_token().unwrap();
if self.state.is_token_equal_to_prim(&tok, "def") {
let control_sequence = self.parse_unexpanded_control_sequence();
let makro = self.parse_macro_definition();
self.state
.set_macro(global, &control_sequence, &Rc::new(makro));
} else {
panic!("unimplemented");
}
}
fn is_box_assignment_head(&mut self) -> bool {
self.is_next_expanded_token_in_set_of_primitives(&["setbox"])
}
fn parse_box_assignment(&mut self, global: bool) {
let tok = self.lex_expanded_token().unwrap();
if !self.state.is_token_equal_to_prim(&tok, "setbox") {
panic!("Invalid box assignment head: {:?}", tok);
}
let box_index = self.parse_8bit_number();
self.parse_equals_expanded();
let maybe_tex_box = self.parse_box();
if let Some(tex_box) = maybe_tex_box {
self.state.set_box(global, box_index, tex_box);
}
}
fn parse_shorthand_definition(&mut self, global: bool) {
let tok = self.lex_expanded_token().unwrap();
if self.state.is_token_equal_to_prim(&tok, "mathchardef") {
let control_sequence = self.parse_unexpanded_control_sequence();
self.parse_equals_expanded();
let code_value = self.parse_15bit_number();
self.state.set_math_chardef(
global,
&control_sequence,
&MathCode::from_number(code_value as u32),
);
} else {
panic!("unimplemented!");
}
}
fn parse_code_assignment(&mut self, global: bool) {
let tok = self.lex_expanded_token().unwrap();
if self.state.is_token_equal_to_prim(&tok, "mathcode") {
let num = self.parse_8bit_number();
self.parse_equals_expanded();
let code_value = self.parse_number();
self.state.set_math_code(
global,
num as char,
&MathCode::from_number(code_value as u32),
);
} else {
panic!("unimplemented");
}
}
fn parse_at_clause(&mut self) -> AtClause {
if self.parse_optional_keyword_expanded("at") {
let dimen = self.parse_dimen();
AtClause::At(dimen)
} else if self.parse_optional_keyword_expanded("scaled") {
let number = self.parse_number();
if number < 0 || number > 32768 {
panic!("Invalid magnification: {}", number);
}
AtClause::Scaled(number as u16)
} else {
self.parse_optional_spaces_expanded();
AtClause::Natural
}
}
fn parse_font_assignment(&mut self, global: bool) {
let tok = self.lex_expanded_token().unwrap();
if !self.state.is_token_equal_to_prim(&tok, "font") {
panic!("Invalid font assignment head");
}
let fontdef_name = self.parse_unexpanded_control_sequence();
// The TeXbook says that we need to "take precautions so that
// \font\cs=name\cs won't expand the second \cs until the assignments
// are done". We don't currently have a way to indicate that a certain
// token shouldn't be expanded, so assigning it to \relax and letting
// that stop the parsing should work. If someone reassigns \relax, this
// won't work correctly, so this should probably be improved at some
// point.
// TODO: Figure out how to actually prevent expansion of a given token
// while parsing the file name.
self.state.set_let(
false,
&fontdef_name,
&Token::ControlSequence("relax".to_string()),
);
self.parse_equals_expanded();
let font_name = self.parse_file_name();
let at = self.parse_at_clause();
let font_metrics = FontMetrics::from_font(&Font {
font_name: font_name.clone(),
// Since we're only accessing the design size, the scale for
// the font doesn't matter here.
scale: Dimen::zero(),
})
.unwrap_or_else(|| panic!("Invalid font name: {}", font_name));
let design_size = 65536.0 * font_metrics.get_design_size();
let font = match at {
AtClause::Natural => Font {
font_name,
scale: Dimen::from_scaled_points(design_size as i32),
},
AtClause::At(dimen) => Font {
font_name,
scale: dimen,
},
AtClause::Scaled(magnification) => {
let font_scale_sp =
design_size * (magnification as f64) / 1000.0;
Font {
font_name,
scale: Dimen::from_scaled_points(font_scale_sp as i32),
}
}
};
self.state.set_fontdef(global, &fontdef_name, &font);
}
fn parse_fontdef_assignment(&mut self, global: bool) {
let tok = self.lex_expanded_token().unwrap();
let font = self.state.get_fontdef(&tok).unwrap();
self.state.set_current_font(global, &font);
}
fn parse_intimate_assignment(
&mut self,
maybe_special_vars: Option<SpecialVariables>,
) {
let tok = self.lex_expanded_token().unwrap();
if self.state.is_token_equal_to_prim(&tok, "prevdepth") {
self.parse_equals_expanded();
let dimen = self.parse_dimen();
if let Some(special_vars) = maybe_special_vars {
if let Some(prev_depth) = special_vars.prev_depth {
*prev_depth = dimen;
} else {
panic!("Invalid prevdepth assignment");
}
} else {
panic!("Invalid prevdepth assignment");
}
} else {
panic!("unimplemented");
}
}
fn parse_global_assignment(
&mut self,
special_vars: Option<SpecialVariables>,
) {
if self.is_intimate_assignment_head() {
self.parse_intimate_assignment(special_vars)
} else {
panic!("unimplemented");
}
}
fn parse_simple_assignment(
&mut self,
global: bool,
special_vars: Option<SpecialVariables>,
) {
if self.is_variable_assignment_head() {
self.parse_variable_assignment(global)
} else if self.is_let_assignment_head() {
self.parse_let_assignment(global)
} else if self.is_arithmetic_head() {
self.parse_arithmetic(global)
} else if self.is_box_assignment_head() {
self.parse_box_assignment(global)
} else if self.is_shorthand_definition_head() {
self.parse_shorthand_definition(global)
} else if self.is_code_assignment_head() {
self.parse_code_assignment(global)
} else if self.is_font_assignment_head() {
self.parse_font_assignment(global)
} else if self.is_fontdef_assignment_head() {
self.parse_fontdef_assignment(global)
} else if self.is_global_assignment_head() {
self.parse_global_assignment(special_vars)
} else {
panic!("unimplemented");
}
}
fn parse_assignment_global(
&mut self,
global: bool,
special_vars: Option<SpecialVariables>,
) {
if self.is_macro_assignment_head() {
self.parse_macro_assignment(global)
} else if self.is_simple_assignment_head() {
self.parse_simple_assignment(global, special_vars)
} else {
let tok = self.lex_expanded_token().unwrap();
if self.state.is_token_equal_to_prim(&tok, "global") {
if self.is_assignment_head() {
self.parse_assignment_global(true, special_vars);
} else {
panic!("Non-assignment head found after \\global");
}
} else {
panic!("Invalid start found in parse_assignment");
}
}
}
pub fn parse_assignment(&mut self, special_vars: Option<SpecialVariables>) {
self.parse_assignment_global(false, special_vars);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::category::Category;
use crate::dimension::{Dimen, Unit};
use crate::makro::{Macro, MacroListElem};
use crate::testing::with_parser;
#[test]
fn it_assigns_macros() {
with_parser(&["\\def\\a #1x{#1y#1}%"], |parser| {
parser.parse_assignment(None);
assert_eq!(
*parser
.state
.get_macro(&Token::ControlSequence("a".to_string()))
.unwrap(),
Macro::new(
vec![
MacroListElem::Parameter(1),
MacroListElem::Token(Token::Char(
'x',
Category::Letter
)),
],
vec![
MacroListElem::Parameter(1),
MacroListElem::Token(Token::Char(
'y',
Category::Letter
)),
MacroListElem::Parameter(1),
]
)
);
});
}
#[test]
fn it_sets_global_defs() {
with_parser(&["\\global\\def\\a{x}%"], |parser| {
parser.state.push_state();
assert!(parser.is_assignment_head());
parser.parse_assignment(None);
assert_eq!(parser.lex_unexpanded_token(), None);
parser.state.pop_state();
assert_eq!(
*parser
.state
.get_macro(&Token::ControlSequence("a".to_string()))
.unwrap(),
Macro::new(
vec![],
vec![MacroListElem::Token(Token::Char(
'x',
Category::Letter
)),]
)
);
});
}
#[test]
fn it_assigns_lets_for_characters() {
with_parser(&["\\let\\a=b%"], |parser| {
parser.parse_assignment(None);
assert_eq!(
parser.state.get_renamed_token(&Token::ControlSequence(
"a".to_string()
)),
Some(Token::Char('b', Category::Letter))
);
});
}
#[test]
fn it_assigns_lets_for_previously_defined_macros() {
with_parser(&["\\def\\a{x}%", "\\let\\b=\\a%"], |parser| {
parser.parse_assignment(None);
parser.parse_assignment(None);
assert_eq!(
*parser
.state
.get_macro(&Token::ControlSequence("b".to_string()))
.unwrap(),
Macro::new(
vec![],
vec![MacroListElem::Token(Token::Char(
'x',
Category::Letter
)),]
)
);
});
}
#[test]
fn it_doesnt_assign_lets_for_active_tokens() {
with_parser(&["\\let\\a=@%"], |parser| {
parser.state.set_category(false, '@', Category::Active);
parser.parse_assignment(None);
assert_eq!(
parser.state.get_renamed_token(&Token::ControlSequence(
"a".to_string()
)),
None
);
});
}
#[test]
fn it_assigns_lets_for_primitives() {
with_parser(&["\\let\\a=\\def%"], |parser| {
parser.parse_assignment(None);
assert!(parser.state.is_token_equal_to_prim(
&Token::ControlSequence("a".to_string()),
"def"
));
});
}
#[test]
fn it_lets_let_be_let() {
with_parser(&["\\let\\a=\\let%", "\\a\\x=y%"], |parser| {
parser.parse_assignment(None);
parser.parse_assignment(None);
assert_eq!(
parser.state.get_renamed_token(&Token::ControlSequence(
"x".to_string()
)),
Some(Token::Char('y', Category::Letter))
);
});
}
#[test]
fn it_lets_def_be_let() {
with_parser(&["\\let\\a=\\def%", "\\a\\x #1{#1}%"], |parser| {
parser.parse_assignment(None);
parser.parse_assignment(None);
assert_eq!(
*parser
.state
.get_macro(&Token::ControlSequence("x".to_string()))
.unwrap(),
Macro::new(
vec![MacroListElem::Parameter(1),],
vec![MacroListElem::Parameter(1),]
)
);
});
}
#[test]
fn it_sets_global_lets() {
with_parser(&["\\global\\let\\a=b%"], |parser| {
parser.state.push_state();
parser.parse_assignment(None);
parser.state.pop_state();
assert_eq!(
parser.state.get_renamed_token(&Token::ControlSequence(
"a".to_string()
)),
Some(Token::Char('b', Category::Letter))
);
});
}
#[test]
fn it_sets_count_variables() {
with_parser(
&["\\count0=2%", "\\count100 -12345%", "\\count10=\\count100%"],
|parser| {
parser.parse_assignment(None);
parser.parse_assignment(None);
parser.parse_assignment(None);
assert_eq!(parser.state.get_count(0), 2);
assert_eq!(parser.state.get_count(100), -12345);
assert_eq!(parser.state.get_count(10), -12345);
},
);
}
#[test]
fn it_sets_count_variables_globally() {
with_parser(&["\\global\\count0=2%"], |parser| {
parser.state.push_state();
parser.parse_assignment(None);
parser.state.pop_state();
assert_eq!(parser.state.get_count(0), 2);
});
}
#[test]
fn it_parses_arithmetic() {
with_parser(
&[
"\\count0=150%",
"\\count1=5%",
"\\advance\\count0 by7%",
"\\multiply\\count1 by2%",
"\\divide\\count0 by\\count1%",
],
|parser| {
parser.parse_assignment(None);
parser.parse_assignment(None);
assert_eq!(parser.state.get_count(0), 150);
assert_eq!(parser.state.get_count(1), 5);
assert!(parser.is_assignment_head());
parser.parse_assignment(None);
assert_eq!(parser.state.get_count(0), 157);
assert!(parser.is_assignment_head());
parser.parse_assignment(None);
assert_eq!(parser.state.get_count(1), 10);
assert!(parser.is_assignment_head());
parser.parse_assignment(None);
assert_eq!(parser.state.get_count(0), 15);
},
);
}
#[test]
fn it_sets_boxes() {
with_parser(&["\\setbox123=\\hbox{a}%"], |parser| {
assert!(parser.is_assignment_head());
parser.parse_assignment(None);
assert!(parser.state.get_box(123).is_some());
});
}
#[test]
fn it_sets_box_dimens() {
with_parser(
&[r"\setbox0=\hbox{a}%", r"\wd0=2pt%", r"\ht0=3pt%"],
|parser| {
assert!(parser.is_assignment_head());
parser.parse_assignment(None);
assert!(parser.is_assignment_head());
parser.parse_assignment(None);
assert!(parser.is_assignment_head());
parser.parse_assignment(None);
assert_eq!(
parser.state.with_box(0, |tex_box| *tex_box.width()),
Some(Dimen::from_unit(2.0, Unit::Point))
);
assert_eq!(
parser.state.with_box(0, |tex_box| *tex_box.height()),
Some(Dimen::from_unit(3.0, Unit::Point))
);
},
);
}
#[test]
fn it_sets_mathchardefs() {
with_parser(
&[
r#"\mathchardef\x"7161%"#,
r"\mathchardef\y=1234%",
r"\def\a{=}\mathchardef\z\a7161%",
r"\x\y\z%",
],
|parser| {
assert!(parser.is_assignment_head());
parser.parse_assignment(None);
assert!(parser.is_assignment_head());
parser.parse_assignment(None);
assert!(parser.is_assignment_head());
parser.parse_assignment(None);
assert!(parser.is_assignment_head());
parser.parse_assignment(None);
let x = parser.parse_unexpanded_control_sequence();
let y = parser.parse_unexpanded_control_sequence();
let z = parser.parse_unexpanded_control_sequence();
assert_eq!(
parser.state.get_math_chardef(&x),
Some(MathCode::from_number(0x7161))
);
assert_eq!(
parser.state.get_math_chardef(&y),
Some(MathCode::from_number(1234))
);
assert_eq!(
parser.state.get_math_chardef(&z),
Some(MathCode::from_number(7161))
);
},
);
}
#[test]
fn it_sets_mathcodes() {
with_parser(
&[r#"\mathcode`*="2203%"#, r#"\mathcode`<="313C%"#],
|parser| {
assert!(parser.is_assignment_head());
parser.parse_assignment(None);
assert!(parser.is_assignment_head());
parser.parse_assignment(None);
assert_eq!(
parser.state.get_math_code('*'),
MathCode::from_number(0x2203)
);
assert_eq!(
parser.state.get_math_code('<'),
MathCode::from_number(0x313C)
);
},
);
}
#[test]
fn it_assigns_fonts() {
with_parser(
&[
r"\font\abc=cmr7%",
r"\font\$=cmr10 at 5pt%",
r"\font\boo=cmtt10 scaled 2000%",
],
|parser| {
assert!(parser.is_assignment_head());
parser.parse_assignment(None);
assert!(parser.is_assignment_head());
parser.parse_assignment(None);
assert!(parser.is_assignment_head());
parser.parse_assignment(None);
assert_eq!(
parser.state.get_fontdef(&Token::ControlSequence(
"abc".to_string()
)),
Some(Font {
font_name: "cmr7".to_string(),
scale: Dimen::from_unit(7.0, Unit::Point),
})
);
assert_eq!(
parser
.state
.get_fontdef(&Token::ControlSequence("$".to_string())),
Some(Font {
font_name: "cmr10".to_string(),
scale: Dimen::from_unit(5.0, Unit::Point),
})
);
assert_eq!(
parser.state.get_fontdef(&Token::ControlSequence(
"boo".to_string()
)),
Some(Font {
font_name: "cmtt10".to_string(),
scale: Dimen::from_unit(20.0, Unit::Point),
})
);
},
);
}
#[test]
fn it_expands_macros_in_font_assignment() {
with_parser(&[r"\def\y{10}%", r"\font\z=cmr\y%"], |parser| {
parser.parse_assignment(None);
parser.parse_assignment(None);
assert_eq!(
parser
.state
.get_fontdef(&Token::ControlSequence("z".to_string())),
Some(Font {
font_name: "cmr10".to_string(),
scale: Dimen::from_unit(10.0, Unit::Point),
})
);
});
}
#[test]
#[should_panic(expected = "Invalid font name: cmr")]
fn it_does_not_expand_the_assigned_font_name_in_font_assignment() {
with_parser(&[r"\def\x{10}%", r"\font\x=cmr\x%"], |parser| {
parser.parse_assignment(None);
parser.parse_assignment(None);
});
}
#[test]
fn it_sets_current_fonts() {
with_parser(
&[
r"\font\a=cmr10\a%",
r"\font\b=cmr7 scaled 2000\b%",
r"\font\c=cmtt10 at 5pt\c%",
r"\let\x=\a%",
r"\x%",
],
|parser| {
assert!(parser.is_assignment_head());
parser.parse_assignment(None);
assert!(parser.is_assignment_head());
parser.parse_assignment(None);
assert_eq!(
parser.state.get_current_font(),
Font {
font_name: "cmr10".to_string(),
scale: Dimen::from_unit(10.0, Unit::Point),
}
);
assert!(parser.is_assignment_head());
parser.parse_assignment(None);
assert!(parser.is_assignment_head());
parser.parse_assignment(None);
assert_eq!(
parser.state.get_current_font(),
Font {
font_name: "cmr7".to_string(),
scale: Dimen::from_unit(14.0, Unit::Point),
}
);
assert!(parser.is_assignment_head());
parser.parse_assignment(None);
assert!(parser.is_assignment_head());
parser.parse_assignment(None);
assert_eq!(
parser.state.get_current_font(),
Font {
font_name: "cmtt10".to_string(),
scale: Dimen::from_unit(5.0, Unit::Point),
}
);
assert!(parser.is_assignment_head());
parser.parse_assignment(None);
assert!(parser.is_assignment_head());
parser.parse_assignment(None);
assert_eq!(
parser.state.get_current_font(),
Font {
font_name: "cmr10".to_string(),
scale: Dimen::from_unit(10.0, Unit::Point),
}
);
},
);
}
#[test]
fn it_assigns_prevdepth_values() {
with_parser(&[r"\prevdepth=2pt%"], |parser| {
let mut prev_depth = Dimen::zero();
let special_variables = SpecialVariables {
prev_depth: Some(&mut prev_depth),
};
assert!(parser.is_assignment_head());
parser.parse_assignment(Some(special_variables));
assert_eq!(prev_depth, Dimen::from_unit(2.0, Unit::Point));
});
}
#[test]
#[should_panic(expected = "Invalid prevdepth assignment")]
fn it_fails_to_assign_prevdepth_values_with_unassigned_special_variable() {
with_parser(&[r"\prevdepth=2pt%"], |parser| {
parser
.parse_assignment(Some(SpecialVariables { prev_depth: None }));
});
}
}
| 32.776678 | 83 | 0.51017 |
d68d824b74d59795b205dec0a01737bd464ba836 | 8,503 | // SPDX-License-Identifier: Apache-2.0
use super::{enarxcall, gdbcall, syscall, Item, Kind, LARGEST_ITEM_SIZE};
use core::convert::TryInto;
use core::mem::{align_of, size_of};
/// Untrusted `sallyport` block.
#[derive(Debug, PartialEq)]
#[repr(transparent)]
pub struct Block<'a>(&'a mut [usize]);
impl<'a> Block<'a> {
/// Returns the approximate length (of `usize` elements) of the block required to fit
/// `item_count` items of biggest size and `data_size` bytes of allocated data.
/// Note, that this function does not account for alignment of the allocated data,
/// and therefore this is merely a hint and not a precise calculation.
#[allow(clippy::question_mark)] // `?` is not supported in `const` functions.
pub const fn size_hint(item_count: usize, data_size: usize) -> Option<usize> {
let item_size = if let Some(item_size) = item_count.checked_mul(LARGEST_ITEM_SIZE) {
item_size
} else {
return None;
};
let size = if let Some(size) = item_size.checked_add(data_size) {
size
} else {
return None;
};
let count = size / size_of::<usize>();
if size % size_of::<usize>() == 0 {
Some(count)
} else {
Some(count + 1)
}
}
}
impl<'a> From<&'a mut [usize]> for Block<'a> {
#[inline]
fn from(block: &'a mut [usize]) -> Self {
Self(block)
}
}
impl<'a> From<Block<'a>> for Option<(Option<Item<'a>>, Block<'a>)> {
#[inline]
fn from(block: Block<'a>) -> Self {
match block.0 {
[size, kind, tail @ ..] => {
#[inline]
fn decode_item<'a, const USIZE_COUNT: usize, T>(
size: usize,
tail: &'a mut [usize],
) -> Option<((&'a mut T, &'a mut [u8]), Block<'a>)>
where
&'a mut T: From<&'a mut [usize; USIZE_COUNT]>,
{
let (payload, tail) = tail.split_at_mut(size / size_of::<usize>());
debug_assert!(size >= size_of::<T>());
let data_size = size.checked_sub(size_of::<T>())?;
debug_assert_eq!(size_of::<T>(), USIZE_COUNT * size_of::<usize>());
let (item_payload, data) = payload.split_at_mut(USIZE_COUNT);
let item_payload: &mut [usize; USIZE_COUNT] = item_payload.try_into().ok()?;
let (prefix, data, suffix) = unsafe { data.align_to_mut::<u8>() };
if !prefix.is_empty() || !suffix.is_empty() || data.len() != data_size {
debug_assert!(prefix.is_empty());
debug_assert!(suffix.is_empty());
debug_assert_eq!(data.len(), data_size);
return None;
}
Some(((item_payload.into(), data), tail.into()))
}
if *size % align_of::<usize>() != 0 {
debug_assert_eq!(*size % align_of::<usize>(), 0);
return None;
}
match (*kind).try_into() {
Ok(Kind::End) => {
debug_assert_eq!(*size, 0);
None
}
Ok(Kind::Syscall) => {
decode_item::<{ syscall::USIZE_COUNT }, syscall::Payload>(*size, tail)
.map(|((call, data), tail)| (Some(Item::Syscall(call, data)), tail))
}
Ok(Kind::Gdbcall) => {
decode_item::<{ gdbcall::USIZE_COUNT }, gdbcall::Payload>(*size, tail)
.map(|((call, data), tail)| (Some(Item::Gdbcall(call, data)), tail))
}
Ok(Kind::Enarxcall) => {
decode_item::<{ enarxcall::USIZE_COUNT }, enarxcall::Payload>(*size, tail)
.map(|((call, data), tail)| (Some(Item::Enarxcall(call, data)), tail))
}
Err(_) => Some((None, tail.split_at_mut(*size / size_of::<usize>()).1.into())),
}
}
_ => None,
}
}
}
impl<'a> IntoIterator for Block<'a> {
type Item = Item<'a>;
type IntoIter = BlockIterator<'a>;
fn into_iter(self) -> Self::IntoIter {
BlockIterator(Some(self))
}
}
/// An iterator for `Item` over a `Block`
pub struct BlockIterator<'a>(Option<Block<'a>>);
impl<'a> Iterator for BlockIterator<'a> {
type Item = Item<'a>;
fn next(&mut self) -> Option<Self::Item> {
match self.0.take() {
Some(mut block) => loop {
match block.into() {
Some((Some(item), tail)) => {
self.0 = Some(tail);
return Some(item);
}
Some((None, tail)) => {
block = tail;
}
None => return None,
}
},
None => None,
}
}
}
#[cfg(test)]
mod tests {
use super::super::HEADER_USIZE_COUNT;
use super::*;
use libc::{SYS_exit, SYS_read, ENOSYS};
#[test]
fn block_size_hint() {
const LARGEST_ITEM_USIZE_COUNT: usize = syscall::USIZE_COUNT;
assert_eq!(
Block::size_hint(1, 42 * size_of::<usize>()),
Some(HEADER_USIZE_COUNT + LARGEST_ITEM_USIZE_COUNT + 42),
);
assert_eq!(
Block::size_hint(2, 42 * size_of::<usize>() - 2),
Some(2 * HEADER_USIZE_COUNT + 2 * LARGEST_ITEM_USIZE_COUNT + 42),
)
}
#[test]
fn block() {
let mut block: [usize; 3 * HEADER_USIZE_COUNT + 2 * syscall::USIZE_COUNT + 1] = [
(syscall::USIZE_COUNT + 1) * size_of::<usize>(), // size
Kind::Syscall as _, // kind
SYS_read as _, // num
1, // fd
0, // buf
4, // count
0, // -
0, // -
0, // -
-ENOSYS as _, // ret
0, // -
0xdeadbeef, // data
/* --------------------- */
syscall::USIZE_COUNT * size_of::<usize>(), // size
Kind::Syscall as _, // kind
SYS_exit as _, // num
5, // status
0, // -
0, // -
0, // -
0, // -
0, // -
-ENOSYS as _, // ret
0, // -
/* --------------------- */
0, // size
Kind::End as _, // kind
];
let block = Block::from(&mut block[..]);
let mut block_iter = block.into_iter();
let item = block_iter.next().unwrap();
assert!(
matches!(item, Item::Syscall (syscall::Payload{ num, argv, ret }, data) if {
assert_eq!(*num, SYS_read as _);
assert_eq!(*argv, [1, 0, 4, 0, 0, 0]);
assert_eq!(*ret, [-ENOSYS as _, 0]);
assert_eq!(data, [0xef, 0xbe, 0xad, 0xde, 0, 0, 0, 0]);
true
})
);
let item = block_iter.next().unwrap();
assert!(
matches!(item, Item::Syscall (syscall::Payload{ num, argv, ret }, data) if {
assert_eq!(*num, SYS_exit as _);
assert_eq!(*argv, [5, 0, 0, 0, 0, 0]);
assert_eq!(*ret, [-ENOSYS as _, 0]);
assert_eq!(data, []);
true
})
);
assert!(block_iter.next().is_none());
}
}
| 37.791111 | 99 | 0.408209 |
381a134b0193c3d37ebf9aba545c0d14d264cfe7 | 1,130 | //! A middleware that boxes HTTP response bodies.
use crate::Payload;
use futures::{future, TryFutureExt};
use linkerd2_error::Error;
use std::task::{Context, Poll};
#[derive(Copy, Clone, Debug)]
pub struct Layer(());
#[derive(Clone, Debug)]
pub struct BoxResponse<S>(S);
impl Layer {
pub fn new() -> Self {
Layer(())
}
}
impl<S> tower::layer::Layer<S> for Layer {
type Service = BoxResponse<S>;
fn layer(&self, inner: S) -> Self::Service {
BoxResponse(inner)
}
}
impl<S, Req, B> tower::Service<Req> for BoxResponse<S>
where
S: tower::Service<Req, Response = http::Response<B>>,
B: http_body::Body + Send + 'static,
B::Data: Send + 'static,
B::Error: Into<Error> + 'static,
{
type Response = http::Response<Payload>;
type Error = S::Error;
type Future = future::MapOk<S::Future, fn(S::Response) -> Self::Response>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.0.poll_ready(cx)
}
fn call(&mut self, req: Req) -> Self::Future {
self.0.call(req).map_ok(|rsp| rsp.map(Payload::new))
}
}
| 24.042553 | 85 | 0.610619 |
388a9dfb25a530475657d158f21a11f19a89e7ef | 7,117 | use ::std::collections::HashMap;
use ::std::sync::atomic::{AtomicBool, Ordering};
use ::std::sync::Arc;
use ::std::sync::RwLock;
use ::std::thread;
use ::std::thread::{sleep, spawn};
use ::std::time::Duration;
use ::bincode;
use ::log::debug;
use ::log::error;
use ::log::info;
use ::log::trace;
use ::log::warn;
use ::serde_json;
use ::ws::util::Token;
use ::ws::CloseCode;
use ::ws::Handshake;
use ::ws::Message;
use ::ws::Sender;
use crate::common::api::{Downstream, DownstreamEnvelope, Upstream, UpstreamEnvelope};
use crate::common::util::clear_lock;
#[derive(Debug, Clone)]
pub struct RespSender<'a> {
trace: u64,
pub connection: &'a ConnectionData,
}
impl<'a> RespSender<'a> {
pub fn new(trace: u64, connection: &'a ConnectionData) -> Self {
RespSender { trace, connection }
}
}
#[derive(Debug)]
pub struct ConnectionData {
use_json: AtomicBool,
sender: Sender,
control: Arc<ServerControl>,
}
impl ConnectionData {
pub fn new(sender: Sender, control: Arc<ServerControl>) -> Arc<Self> {
Arc::new(ConnectionData {
use_json: AtomicBool::new(false),
sender,
control,
})
}
pub fn token(&self) -> Token {
self.sender.token()
}
fn send_with_trace(&self, trace: u64, data: Downstream) {
let envelope = DownstreamEnvelope { trace, data };
trace!("sending {:?}", envelope);
assert!(!self.use_json.load(Ordering::Acquire), "to implement: json"); //TODO @mark:
let resp_data = bincode::serialize(&envelope).expect("could not encode Response");
self.sender.send(resp_data).expect("failed to send websocket response");
}
pub fn send_untraced(&self, data: Downstream) {
self.send_with_trace(0, data)
}
pub fn send_err_untraced(&self, msg: impl Into<String>) {
let msg = msg.into();
warn!("sending error response: {}", &msg);
self.send_untraced(Downstream::DaemonError(msg))
}
pub fn broadcast(&self, response: Downstream) {
self.control
.clients
.read()
.unwrap()
.values()
.for_each(|client| client.send_untraced(response.clone()))
}
pub fn no_new_connections(&self) {
self.control.is_accepting_connections.store(false, Ordering::Release);
}
pub fn shutdown(&self) {
self.no_new_connections();
let control_copy = self.control.clone();
spawn(move || {
//TODO get rid of spawn/sleep: https://github.com/housleyjk/ws-rs/issues/332
sleep(Duration::from_millis(50));
control_copy
.handle
.read()
.unwrap()
.as_ref()
.expect("could not shut down server, the handle was not initialized at startup")
.shutdown()
.unwrap();
});
}
}
impl<'a> RespSender<'a> {
pub fn send(&self, data: Downstream) {
self.connection.send_with_trace(self.trace, data);
}
pub fn send_err(&self, msg: impl Into<String>) {
let msg = msg.into();
warn!("sending error response: {}", &msg);
self.send(Downstream::DaemonError(msg))
}
}
#[derive(Debug)]
pub struct ServerControl {
clients: RwLock<HashMap<Token, Arc<ConnectionData>>>,
handle: RwLock<Option<Sender>>,
is_accepting_connections: AtomicBool,
}
impl ServerControl {
pub fn new() -> Arc<Self> {
Arc::new(ServerControl {
clients: RwLock::new(HashMap::new()),
handle: RwLock::new(None),
is_accepting_connections: AtomicBool::new(true),
})
}
}
struct ServerHandler<H: Fn(Upstream, &RespSender) -> Result<(), String>> {
connection: Arc<ConnectionData>,
handler: H,
}
impl<H: Fn(Upstream, &RespSender) -> Result<(), String>> ws::Handler for ServerHandler<H> {
fn on_open(&mut self, _: Handshake) -> ws::Result<()> {
//TODO @mark: too long path
let connection = &self.connection;
if connection.control.is_accepting_connections.load(Ordering::Acquire) {
connection
.control
.clients
.write()
.unwrap()
.insert(connection.token(), connection.clone());
} else {
debug!("rejecting connection because mangod is shutting down");
connection.send_err_untraced("the mango daemon is currently shutting down, no new connections accepted");
}
Ok(())
}
fn on_message(&mut self, req_msg: Message) -> ws::Result<()> {
let request_envelope = match req_msg {
Message::Text(req_data) => {
//TODO @mark: test this path
self.connection.use_json.store(true, Ordering::Release);
serde_json::from_str::<UpstreamEnvelope>(&req_data).map_err(|err| format!("{}", err))
}
Message::Binary(req_data) => {
self.connection.use_json.store(false, Ordering::Release);
bincode::deserialize::<UpstreamEnvelope>(&req_data).map_err(|err| format!("{}", err))
}
};
match request_envelope {
Ok(request_envelope) => {
let UpstreamEnvelope { trace: id, data } = request_envelope;
let sender = RespSender::new(id, &self.connection);
match (self.handler)(data, &sender) {
//TODO @mark: remove trace?
Ok(()) => {} //trace!("successfully handled {}", data.type_name()),
Err(err_msg) => sender.send_err(err_msg),
}
}
Err(err_msg) => {
warn!("failed to deserialize binary request: {}", &err_msg);
self.connection.send_err_untraced("could not understand binary request");
}
}
Ok(())
}
//TODO @mark: is on_close always called? also when timeout/dropped/crashed?
fn on_close(&mut self, _: CloseCode, _: &str) {
self.connection.control.clients.write().unwrap().remove(&self.connection.token());
}
}
//TODO @mark: check all Arc and RwLock to make sure it's not excessive
pub fn server(addr: &str, handler: impl Fn(Upstream, &RespSender) -> Result<(), String> + Clone + Send + 'static) {
info!("starting server at {}", addr);
let control = ServerControl::new();
let control_ref = control.clone();
let socket = ws::Builder::new()
.build(move |sender| ServerHandler {
connection: ConnectionData::new(sender, control.clone()),
handler: handler.clone(),
})
.expect("failed to build websocket server");
*control_ref.handle.write().unwrap() = Some(socket.broadcaster());
let addr_copy = addr.to_owned();
let thrd = thread::spawn(move || {
if let Err(err) = socket.listen(&addr_copy) {
error!("could not start daemon at {}, reason: {}", &addr_copy, err)
}
});
thrd.join().expect("something went wrong with the server thread");
clear_lock();
}
| 33.102326 | 117 | 0.581144 |
5d748a68dacbd1858974ac11bedc83cadfc7666e | 2,741 | use crate::encode::Encoder;
use crate::rr::{Class, Type, RR};
use crate::EncodeResult;
impl Encoder {
#[inline]
pub(super) fn rr_type(&mut self, type_: &Type) {
self.u16(*type_ as u16);
}
#[inline]
pub(super) fn rr_class(&mut self, class: &Class) {
self.u16(*class as u16);
}
pub(crate) fn rr(&mut self, rr: &RR) -> EncodeResult<()> {
match rr {
RR::A(a) => self.rr_a(a),
RR::NS(ns) => self.rr_ns(ns),
RR::MD(md) => self.rr_md(md),
RR::MF(mf) => self.rr_mf(mf),
RR::CNAME(cname) => self.rr_cname(cname),
RR::SOA(soa) => self.rr_soa(soa),
RR::MB(mb) => self.rr_mb(mb),
RR::MG(mg) => self.rr_mg(mg),
RR::MR(mr) => self.rr_mr(mr),
RR::NULL(null) => self.rr_null(null),
RR::WKS(wks) => self.rr_wks(wks),
RR::PTR(ptr) => self.rr_ptr(ptr),
RR::HINFO(hinfo) => self.rr_hinfo(hinfo),
RR::MINFO(minfo) => self.rr_minfo(minfo),
RR::MX(mx) => self.rr_mx(mx),
RR::TXT(txt) => self.rr_txt(txt),
RR::RP(rp) => self.rr_rp(rp),
RR::AFSDB(afsdb) => self.rr_afsdb(afsdb),
RR::X25(x25) => self.rr_x25(x25),
RR::ISDN(isdn) => self.rr_isdn(isdn),
RR::RT(rt) => self.rr_rt(rt),
RR::NSAP(nsap) => self.rr_nsap(nsap),
RR::GPOS(gpos) => self.rr_gpos(gpos),
RR::LOC(loc) => self.rr_loc(loc),
RR::PX(px) => self.rr_px(px),
RR::KX(kx) => self.rr_kx(kx),
RR::SRV(srv) => self.rr_srv(srv),
RR::AAAA(aaaa) => self.rr_aaaa(aaaa),
RR::SSHFP(sshfp) => self.rr_sshfp(sshfp),
RR::DNAME(dname) => self.rr_dname(dname),
RR::OPT(opt) => self.rr_opt(opt),
RR::APL(apl) => self.rr_apl(apl),
RR::NID(n_id) => self.rr_nid(n_id),
RR::L32(l_32) => self.rr_l32(l_32),
RR::L64(l_64) => self.rr_l64(l_64),
RR::LP(lp) => self.rr_lp(lp),
RR::EUI48(eui_48) => self.rr_eui48(eui_48),
RR::EUI64(eui_64) => self.rr_eui64(eui_64),
RR::URI(uri) => self.rr_uri(uri),
RR::EID(eid) => self.rr_eid(eid),
RR::NIMLOC(nimloc) => self.rr_nimloc(nimloc),
RR::DNSKEY(dnskey) => self.rr_dnskey(dnskey),
RR::DS(ds) => self.rr_ds(ds),
RR::CAA(caa) => self.rr_caa(caa),
RR::SVCB(svcb) => self.rr_service_binding(svcb),
RR::HTTPS(https) => self.rr_service_binding(https),
}
}
}
impl_encode_without_result!(Type, rr_type);
impl_encode_without_result!(Class, rr_class);
impl_encode!(RR, rr);
| 37.547945 | 63 | 0.502371 |
f5662670a94219093120f7f0894fb6c81803138f | 15,051 | #[doc = "Register `GPIO_CFGCTL16` reader"]
pub struct R(crate::R<GPIO_CFGCTL16_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<GPIO_CFGCTL16_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<GPIO_CFGCTL16_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<GPIO_CFGCTL16_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `GPIO_CFGCTL16` writer"]
pub struct W(crate::W<GPIO_CFGCTL16_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<GPIO_CFGCTL16_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<GPIO_CFGCTL16_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<GPIO_CFGCTL16_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `reg_gpio_33_pd` reader - "]
pub struct REG_GPIO_33_PD_R(crate::FieldReader<bool, bool>);
impl REG_GPIO_33_PD_R {
pub(crate) fn new(bits: bool) -> Self {
REG_GPIO_33_PD_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for REG_GPIO_33_PD_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `reg_gpio_33_pd` writer - "]
pub struct REG_GPIO_33_PD_W<'a> {
w: &'a mut W,
}
impl<'a> REG_GPIO_33_PD_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 21)) | ((value as u32 & 0x01) << 21);
self.w
}
}
#[doc = "Field `reg_gpio_33_pu` reader - "]
pub struct REG_GPIO_33_PU_R(crate::FieldReader<bool, bool>);
impl REG_GPIO_33_PU_R {
pub(crate) fn new(bits: bool) -> Self {
REG_GPIO_33_PU_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for REG_GPIO_33_PU_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `reg_gpio_33_pu` writer - "]
pub struct REG_GPIO_33_PU_W<'a> {
w: &'a mut W,
}
impl<'a> REG_GPIO_33_PU_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 20)) | ((value as u32 & 0x01) << 20);
self.w
}
}
#[doc = "Field `reg_gpio_33_drv` reader - "]
pub struct REG_GPIO_33_DRV_R(crate::FieldReader<u8, u8>);
impl REG_GPIO_33_DRV_R {
pub(crate) fn new(bits: u8) -> Self {
REG_GPIO_33_DRV_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for REG_GPIO_33_DRV_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `reg_gpio_33_drv` writer - "]
pub struct REG_GPIO_33_DRV_W<'a> {
w: &'a mut W,
}
impl<'a> REG_GPIO_33_DRV_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 18)) | ((value as u32 & 0x03) << 18);
self.w
}
}
#[doc = "Field `reg_gpio_33_smt` reader - "]
pub struct REG_GPIO_33_SMT_R(crate::FieldReader<bool, bool>);
impl REG_GPIO_33_SMT_R {
pub(crate) fn new(bits: bool) -> Self {
REG_GPIO_33_SMT_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for REG_GPIO_33_SMT_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `reg_gpio_33_smt` writer - "]
pub struct REG_GPIO_33_SMT_W<'a> {
w: &'a mut W,
}
impl<'a> REG_GPIO_33_SMT_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 << 17)) | ((value as u32 & 0x01) << 17);
self.w
}
}
#[doc = "Field `reg_gpio_33_ie` reader - "]
pub struct REG_GPIO_33_IE_R(crate::FieldReader<bool, bool>);
impl REG_GPIO_33_IE_R {
pub(crate) fn new(bits: bool) -> Self {
REG_GPIO_33_IE_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for REG_GPIO_33_IE_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `reg_gpio_33_ie` writer - "]
pub struct REG_GPIO_33_IE_W<'a> {
w: &'a mut W,
}
impl<'a> REG_GPIO_33_IE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | ((value as u32 & 0x01) << 16);
self.w
}
}
#[doc = "Field `reg_gpio_32_pd` reader - "]
pub struct REG_GPIO_32_PD_R(crate::FieldReader<bool, bool>);
impl REG_GPIO_32_PD_R {
pub(crate) fn new(bits: bool) -> Self {
REG_GPIO_32_PD_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for REG_GPIO_32_PD_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `reg_gpio_32_pd` writer - "]
pub struct REG_GPIO_32_PD_W<'a> {
w: &'a mut W,
}
impl<'a> REG_GPIO_32_PD_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | ((value as u32 & 0x01) << 5);
self.w
}
}
#[doc = "Field `reg_gpio_32_pu` reader - "]
pub struct REG_GPIO_32_PU_R(crate::FieldReader<bool, bool>);
impl REG_GPIO_32_PU_R {
pub(crate) fn new(bits: bool) -> Self {
REG_GPIO_32_PU_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for REG_GPIO_32_PU_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `reg_gpio_32_pu` writer - "]
pub struct REG_GPIO_32_PU_W<'a> {
w: &'a mut W,
}
impl<'a> REG_GPIO_32_PU_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | ((value as u32 & 0x01) << 4);
self.w
}
}
#[doc = "Field `reg_gpio_32_drv` reader - "]
pub struct REG_GPIO_32_DRV_R(crate::FieldReader<u8, u8>);
impl REG_GPIO_32_DRV_R {
pub(crate) fn new(bits: u8) -> Self {
REG_GPIO_32_DRV_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for REG_GPIO_32_DRV_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `reg_gpio_32_drv` writer - "]
pub struct REG_GPIO_32_DRV_W<'a> {
w: &'a mut W,
}
impl<'a> REG_GPIO_32_DRV_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 2)) | ((value as u32 & 0x03) << 2);
self.w
}
}
#[doc = "Field `reg_gpio_32_smt` reader - "]
pub struct REG_GPIO_32_SMT_R(crate::FieldReader<bool, bool>);
impl REG_GPIO_32_SMT_R {
pub(crate) fn new(bits: bool) -> Self {
REG_GPIO_32_SMT_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for REG_GPIO_32_SMT_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `reg_gpio_32_smt` writer - "]
pub struct REG_GPIO_32_SMT_W<'a> {
w: &'a mut W,
}
impl<'a> REG_GPIO_32_SMT_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | ((value as u32 & 0x01) << 1);
self.w
}
}
#[doc = "Field `reg_gpio_32_ie` reader - "]
pub struct REG_GPIO_32_IE_R(crate::FieldReader<bool, bool>);
impl REG_GPIO_32_IE_R {
pub(crate) fn new(bits: bool) -> Self {
REG_GPIO_32_IE_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for REG_GPIO_32_IE_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `reg_gpio_32_ie` writer - "]
pub struct REG_GPIO_32_IE_W<'a> {
w: &'a mut W,
}
impl<'a> REG_GPIO_32_IE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | (value as u32 & 0x01);
self.w
}
}
impl R {
#[doc = "Bit 21"]
#[inline(always)]
pub fn reg_gpio_33_pd(&self) -> REG_GPIO_33_PD_R {
REG_GPIO_33_PD_R::new(((self.bits >> 21) & 0x01) != 0)
}
#[doc = "Bit 20"]
#[inline(always)]
pub fn reg_gpio_33_pu(&self) -> REG_GPIO_33_PU_R {
REG_GPIO_33_PU_R::new(((self.bits >> 20) & 0x01) != 0)
}
#[doc = "Bits 18:19"]
#[inline(always)]
pub fn reg_gpio_33_drv(&self) -> REG_GPIO_33_DRV_R {
REG_GPIO_33_DRV_R::new(((self.bits >> 18) & 0x03) as u8)
}
#[doc = "Bit 17"]
#[inline(always)]
pub fn reg_gpio_33_smt(&self) -> REG_GPIO_33_SMT_R {
REG_GPIO_33_SMT_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 16"]
#[inline(always)]
pub fn reg_gpio_33_ie(&self) -> REG_GPIO_33_IE_R {
REG_GPIO_33_IE_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 5"]
#[inline(always)]
pub fn reg_gpio_32_pd(&self) -> REG_GPIO_32_PD_R {
REG_GPIO_32_PD_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 4"]
#[inline(always)]
pub fn reg_gpio_32_pu(&self) -> REG_GPIO_32_PU_R {
REG_GPIO_32_PU_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bits 2:3"]
#[inline(always)]
pub fn reg_gpio_32_drv(&self) -> REG_GPIO_32_DRV_R {
REG_GPIO_32_DRV_R::new(((self.bits >> 2) & 0x03) as u8)
}
#[doc = "Bit 1"]
#[inline(always)]
pub fn reg_gpio_32_smt(&self) -> REG_GPIO_32_SMT_R {
REG_GPIO_32_SMT_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 0"]
#[inline(always)]
pub fn reg_gpio_32_ie(&self) -> REG_GPIO_32_IE_R {
REG_GPIO_32_IE_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 21"]
#[inline(always)]
pub fn reg_gpio_33_pd(&mut self) -> REG_GPIO_33_PD_W {
REG_GPIO_33_PD_W { w: self }
}
#[doc = "Bit 20"]
#[inline(always)]
pub fn reg_gpio_33_pu(&mut self) -> REG_GPIO_33_PU_W {
REG_GPIO_33_PU_W { w: self }
}
#[doc = "Bits 18:19"]
#[inline(always)]
pub fn reg_gpio_33_drv(&mut self) -> REG_GPIO_33_DRV_W {
REG_GPIO_33_DRV_W { w: self }
}
#[doc = "Bit 17"]
#[inline(always)]
pub fn reg_gpio_33_smt(&mut self) -> REG_GPIO_33_SMT_W {
REG_GPIO_33_SMT_W { w: self }
}
#[doc = "Bit 16"]
#[inline(always)]
pub fn reg_gpio_33_ie(&mut self) -> REG_GPIO_33_IE_W {
REG_GPIO_33_IE_W { w: self }
}
#[doc = "Bit 5"]
#[inline(always)]
pub fn reg_gpio_32_pd(&mut self) -> REG_GPIO_32_PD_W {
REG_GPIO_32_PD_W { w: self }
}
#[doc = "Bit 4"]
#[inline(always)]
pub fn reg_gpio_32_pu(&mut self) -> REG_GPIO_32_PU_W {
REG_GPIO_32_PU_W { w: self }
}
#[doc = "Bits 2:3"]
#[inline(always)]
pub fn reg_gpio_32_drv(&mut self) -> REG_GPIO_32_DRV_W {
REG_GPIO_32_DRV_W { w: self }
}
#[doc = "Bit 1"]
#[inline(always)]
pub fn reg_gpio_32_smt(&mut self) -> REG_GPIO_32_SMT_W {
REG_GPIO_32_SMT_W { w: self }
}
#[doc = "Bit 0"]
#[inline(always)]
pub fn reg_gpio_32_ie(&mut self) -> REG_GPIO_32_IE_W {
REG_GPIO_32_IE_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 = "GPIO_CFGCTL16.\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 [gpio_cfgctl16](index.html) module"]
pub struct GPIO_CFGCTL16_SPEC;
impl crate::RegisterSpec for GPIO_CFGCTL16_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [gpio_cfgctl16::R](R) reader structure"]
impl crate::Readable for GPIO_CFGCTL16_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [gpio_cfgctl16::W](W) writer structure"]
impl crate::Writable for GPIO_CFGCTL16_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets GPIO_CFGCTL16 to value 0"]
impl crate::Resettable for GPIO_CFGCTL16_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| 29.686391 | 408 | 0.584679 |
bfc7fa370f553bc4e7481876f380ec652ef2e923 | 9,984 | #[macro_use]
extern crate glium;
extern crate cgmath;
extern crate noise;
extern crate rand;
mod chunk;
mod position;
mod scheduler;
use std::time::{Instant, Duration, UNIX_EPOCH, SystemTime};
use std::env;
use glium::{Surface, glutin, DisplayBuild, Program};
use glium::glutin::{ElementState, Event, VirtualKeyCode};
use cgmath::{Matrix4, Point3, Vector3, Deg};
use scheduler::MasterScheduler;
fn main() {
let display = glutin::WindowBuilder::new()
.with_vsync()
.with_depth_buffer(24)
.with_dimensions(1024, 768)
.with_title(format!("Parallel Voxels"))
.build_glium()
.unwrap();
let program = Program::from_source(&display, "
#version 140
uniform mat4 model_view_projection;
uniform vec2 chunk_position;
in vec3 position;
in vec4 color;
in float occlusion;
out vec4 v_color;
void main() {
gl_Position = model_view_projection * (vec4(chunk_position*16.0, 0.0, 0.0) + vec4(position, 1.0));
v_color = color / 255.0 * occlusion;
}
", "
#version 140
in vec4 v_color;
out vec4 f_color;
void main() {
f_color = vec4(v_color.rgb, 1.0);
}
", None).unwrap();
let mut move_camera = true;
let mut distant_camera = false;
let mut camera_side_speed = 0.0;
let mut camera_speed = 0.1;
let mut testing_mode = 0;
let mut camera_position = [0.5, 0.0, 0.0f32];
let mut seed = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as u32;
let mut thread_count = 4;
for arg in env::args() {
let arg = arg.split('=').collect::<Vec<&str>>();
match arg[0] {
"-s" => {
seed = arg[1].parse().unwrap();
},
"-tc" => {
thread_count = arg[1].parse().unwrap();
},
"-tm" => {
testing_mode = 1;
camera_speed = 16.0;
distant_camera = true;
}
_ => {
}
}
}
let mut scheduler = MasterScheduler::new(seed, thread_count);
let timestep = Duration::new(0, 16666667);
let one_second = Duration::new(1, 0);
let mut time = Duration::new(0, 0);
let mut prev_time = Instant::now();
'outer: loop {
let now = Instant::now();
time = now - prev_time + time;
prev_time = now;
while time > one_second {
println!("Lagging behind, removing one second of update time");
time = time - one_second;
}
while time > timestep {
time = time - timestep;
scheduler.update(camera_position, &display);
if move_camera {
camera_position[0] += camera_side_speed;
camera_position[1] += camera_speed;
}
if !distant_camera {
camera_position[2] = {
let pos = (camera_position[0].floor() as i32, camera_position[1].floor() as i32 & !3);
let height = {
*[scheduler.get_height([pos.0, pos.1 - 4]),
scheduler.get_height([pos.0, pos.1 - 3]),
scheduler.get_height([pos.0, pos.1 - 2]),
scheduler.get_height([pos.0, pos.1 - 1]),
scheduler.get_height([pos.0, pos.1]),
scheduler.get_height([pos.0, pos.1 + 1]),
scheduler.get_height([pos.0, pos.1 + 2]),
scheduler.get_height([pos.0, pos.1 + 3])].iter().max().unwrap() + 4
};
let next_height = {
*[scheduler.get_height([pos.0, pos.1]),
scheduler.get_height([pos.0, pos.1 + 1]),
scheduler.get_height([pos.0, pos.1 + 2]),
scheduler.get_height([pos.0, pos.1 + 3]),
scheduler.get_height([pos.0, pos.1 + 4]),
scheduler.get_height([pos.0, pos.1 + 5]),
scheduler.get_height([pos.0, pos.1 + 6]),
scheduler.get_height([pos.0, pos.1 + 7])].iter().max().unwrap() + 4
};
let y_interp = (camera_position[1] - pos.1 as f32)/4.0;
((height as f32) * (1.0 - y_interp) + (next_height as f32) * y_interp).max(camera_position[2]-0.05)
};
} else {
camera_position[2] = 128.0;
}
if testing_mode != 0 && camera_position[1] >= 4096.0 {
match testing_mode {
1 => {
camera_position[1] = 0.0;
testing_mode = 2;
scheduler.serially_generate = !scheduler.serially_generate;
scheduler.serially_populate = !scheduler.serially_populate;
scheduler.serially_mesh = !scheduler.serially_mesh;
},
2 => {
break 'outer;
},
_ => {
unreachable!();
}
}
}
}
let (width, height) = {
let window = display.get_window().unwrap();
let size = window.get_inner_size_points().unwrap();
(size.0 as f32, size.1 as f32)
};
let projection = cgmath::perspective(Deg(90.0), width / height, 0.01, 1000.0f32);
let model_view = if distant_camera {
Matrix4::look_at(Point3::from(camera_position), Point3::from(camera_position) + Vector3::new(0.0, 0.0, -1.0f32), Vector3::new(0.0, 1.0, 0.0f32))
} else {
Matrix4::look_at(Point3::from(camera_position), Point3::from(camera_position) + Vector3::new(0.0, 1.0, 0.0f32), Vector3::new(0.0, 0.0, 1.0f32))
};
let model_view_projection = projection * model_view;
let mut frame = display.draw();
frame.clear_color_and_depth((0.0, 0.2, 0.8, 0.0), 1.0);
scheduler.render(&mut frame, &program, model_view_projection);
frame.finish().unwrap();
for event in display.poll_events() {
match event {
Event::Closed => return,
Event::KeyboardInput(state, _, key_code) => {
if state == ElementState::Released {
if testing_mode != 0 {
continue;
}
if let Some(key_code) = key_code {
match key_code {
VirtualKeyCode::Key1 => {
println!("Serial generation enabled");
scheduler.serially_generate = true;
},
VirtualKeyCode::Key2 => {
println!("Parallel generation enabled");
scheduler.serially_generate = false;
},
VirtualKeyCode::Key3 => {
println!("Serial population enabled");
scheduler.serially_populate = true;
},
VirtualKeyCode::Key4 => {
println!("Parallel population enabled");
scheduler.serially_populate = false;
},
VirtualKeyCode::Key5 => {
println!("Serial meshing enabled");
scheduler.serially_mesh = true;
},
VirtualKeyCode::Key6 => {
println!("Parallel meshing enabled");
scheduler.serially_mesh = false;
},
VirtualKeyCode::Space => {
move_camera = !move_camera;
},
VirtualKeyCode::P => {
distant_camera = !distant_camera;
camera_position[2] = 0.0;
},
VirtualKeyCode::Minus => {
camera_speed -= 0.1;
},
VirtualKeyCode::Equals => {
camera_speed += 0.1;
},
VirtualKeyCode::LBracket => {
camera_side_speed -= 0.1;
},
VirtualKeyCode::RBracket => {
camera_side_speed += 0.1;
},
VirtualKeyCode::Semicolon => {
camera_side_speed = 0.0;
camera_speed = 0.0;
},
VirtualKeyCode::Escape => {
break 'outer;
},
_ => ()
}
}
}
},
_ => ()
}
}
}
println!("SG: {:.2} ms PG: {:.2} ms", scheduler.serial_generator_time, scheduler.parallel_generator_time);
println!("SP: {:.2} ms PP: {:.2} ms", scheduler.serial_populator_time, scheduler.parallel_populator_time);
println!("SM: {:.2} ms PM: {:.2} ms", scheduler.serial_meshing_time, scheduler.parallel_meshing_time);
}
| 39.152941 | 156 | 0.435196 |
dbc19dccdf7215d61d36efd574b6850adeef2da3 | 8,360 | #![doc = "generated by AutoRust 0.1.0"]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Action {
#[serde(rename = "odata.type")]
pub odata_type: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum AlertSeverity {
#[serde(rename = "0")]
N0,
#[serde(rename = "1")]
N1,
#[serde(rename = "2")]
N2,
#[serde(rename = "3")]
N3,
#[serde(rename = "4")]
N4,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AlertingAction {
#[serde(flatten)]
pub action: Action,
pub severity: AlertSeverity,
#[serde(rename = "aznsAction", default, skip_serializing_if = "Option::is_none")]
pub azns_action: Option<AzNsActionGroup>,
#[serde(rename = "throttlingInMin", default, skip_serializing_if = "Option::is_none")]
pub throttling_in_min: Option<i32>,
pub trigger: TriggerCondition,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AzNsActionGroup {
#[serde(rename = "actionGroup", default, skip_serializing_if = "Vec::is_empty")]
pub action_group: Vec<String>,
#[serde(rename = "emailSubject", default, skip_serializing_if = "Option::is_none")]
pub email_subject: Option<String>,
#[serde(rename = "customWebhookPayload", default, skip_serializing_if = "Option::is_none")]
pub custom_webhook_payload: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ConditionalOperator {
GreaterThanOrEqual,
LessThanOrEqual,
GreaterThan,
LessThan,
Equal,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Criteria {
#[serde(rename = "metricName")]
pub metric_name: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub dimensions: Vec<Dimension>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Dimension {
pub name: String,
pub operator: dimension::Operator,
pub values: Vec<String>,
}
pub mod dimension {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Operator {
Include,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorContract {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<ErrorResponse>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ErrorResponse {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LogMetricTrigger {
#[serde(rename = "thresholdOperator", default, skip_serializing_if = "Option::is_none")]
pub threshold_operator: Option<ConditionalOperator>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub threshold: Option<f64>,
#[serde(rename = "metricTriggerType", default, skip_serializing_if = "Option::is_none")]
pub metric_trigger_type: Option<MetricTriggerType>,
#[serde(rename = "metricColumn", default, skip_serializing_if = "Option::is_none")]
pub metric_column: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LogSearchRule {
#[serde(rename = "createdWithApiVersion", default, skip_serializing_if = "Option::is_none")]
pub created_with_api_version: Option<String>,
#[serde(rename = "isLegacyLogAnalyticsRule", default, skip_serializing_if = "Option::is_none")]
pub is_legacy_log_analytics_rule: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(rename = "autoMitigate", default, skip_serializing_if = "Option::is_none")]
pub auto_mitigate: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enabled: Option<log_search_rule::Enabled>,
#[serde(rename = "lastUpdatedTime", default, skip_serializing_if = "Option::is_none")]
pub last_updated_time: Option<String>,
#[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")]
pub provisioning_state: Option<log_search_rule::ProvisioningState>,
pub source: Source,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub schedule: Option<Schedule>,
pub action: Action,
}
pub mod log_search_rule {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Enabled {
#[serde(rename = "true")]
True,
#[serde(rename = "false")]
False,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ProvisioningState {
Succeeded,
Deploying,
Canceled,
Failed,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LogSearchRulePatch {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enabled: Option<log_search_rule_patch::Enabled>,
}
pub mod log_search_rule_patch {
use super::*;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Enabled {
#[serde(rename = "true")]
True,
#[serde(rename = "false")]
False,
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LogSearchRuleResource {
#[serde(flatten)]
pub resource: Resource,
pub properties: LogSearchRule,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LogSearchRuleResourceCollection {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub value: Vec<LogSearchRuleResource>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LogSearchRuleResourcePatch {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub properties: Option<LogSearchRulePatch>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LogToMetricAction {
#[serde(flatten)]
pub action: Action,
pub criteria: Vec<Criteria>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum MetricTriggerType {
Consecutive,
Total,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum QueryType {
ResultCount,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Resource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_: Option<String>,
pub location: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kind: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub etag: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Schedule {
#[serde(rename = "frequencyInMinutes")]
pub frequency_in_minutes: i32,
#[serde(rename = "timeWindowInMinutes")]
pub time_window_in_minutes: i32,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Source {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub query: Option<String>,
#[serde(rename = "authorizedResources", default, skip_serializing_if = "Vec::is_empty")]
pub authorized_resources: Vec<String>,
#[serde(rename = "dataSourceId")]
pub data_source_id: String,
#[serde(rename = "queryType", default, skip_serializing_if = "Option::is_none")]
pub query_type: Option<QueryType>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TriggerCondition {
#[serde(rename = "thresholdOperator")]
pub threshold_operator: ConditionalOperator,
pub threshold: f64,
#[serde(rename = "metricTrigger", default, skip_serializing_if = "Option::is_none")]
pub metric_trigger: Option<LogMetricTrigger>,
}
| 37.321429 | 99 | 0.697967 |
09fa783cf951a655798ee2091c5443e864235c32 | 253,514 | #![doc = "generated by AutoRust 0.1.0"]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use super::{models, API_VERSION};
#[derive(Clone)]
pub struct Client {
endpoint: String,
credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>,
scopes: Vec<String>,
pipeline: azure_core::Pipeline,
}
#[derive(Clone)]
pub struct ClientBuilder {
credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>,
endpoint: Option<String>,
scopes: Option<Vec<String>>,
}
pub const DEFAULT_ENDPOINT: &str = azure_core::resource_manager_endpoint::AZURE_PUBLIC_CLOUD;
impl ClientBuilder {
pub fn new(credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>) -> Self {
Self {
credential,
endpoint: None,
scopes: None,
}
}
pub fn endpoint(mut self, endpoint: impl Into<String>) -> Self {
self.endpoint = Some(endpoint.into());
self
}
pub fn scopes(mut self, scopes: &[&str]) -> Self {
self.scopes = Some(scopes.iter().map(|scope| (*scope).to_owned()).collect());
self
}
pub fn build(self) -> Client {
let endpoint = self.endpoint.unwrap_or_else(|| DEFAULT_ENDPOINT.to_owned());
let scopes = self.scopes.unwrap_or_else(|| vec![format!("{}/", endpoint)]);
Client::new(endpoint, self.credential, scopes)
}
}
impl Client {
pub(crate) fn endpoint(&self) -> &str {
self.endpoint.as_str()
}
pub(crate) fn token_credential(&self) -> &dyn azure_core::auth::TokenCredential {
self.credential.as_ref()
}
pub(crate) fn scopes(&self) -> Vec<&str> {
self.scopes.iter().map(String::as_str).collect()
}
pub(crate) async fn send(&self, request: impl Into<azure_core::Request>) -> 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 attached_database_configurations(&self) -> attached_database_configurations::Client {
attached_database_configurations::Client(self.clone())
}
pub fn cluster_principal_assignments(&self) -> cluster_principal_assignments::Client {
cluster_principal_assignments::Client(self.clone())
}
pub fn clusters(&self) -> clusters::Client {
clusters::Client(self.clone())
}
pub fn data_connections(&self) -> data_connections::Client {
data_connections::Client(self.clone())
}
pub fn database_principal_assignments(&self) -> database_principal_assignments::Client {
database_principal_assignments::Client(self.clone())
}
pub fn databases(&self) -> databases::Client {
databases::Client(self.clone())
}
pub fn operations(&self) -> operations::Client {
operations::Client(self.clone())
}
}
#[non_exhaustive]
#[derive(Debug, thiserror :: Error)]
#[allow(non_camel_case_types)]
pub enum Error {
#[error(transparent)]
Clusters_Get(#[from] clusters::get::Error),
#[error(transparent)]
Clusters_CreateOrUpdate(#[from] clusters::create_or_update::Error),
#[error(transparent)]
Clusters_Update(#[from] clusters::update::Error),
#[error(transparent)]
Clusters_Delete(#[from] clusters::delete::Error),
#[error(transparent)]
Clusters_Stop(#[from] clusters::stop::Error),
#[error(transparent)]
Clusters_Start(#[from] clusters::start::Error),
#[error(transparent)]
ClusterPrincipalAssignments_CheckNameAvailability(#[from] cluster_principal_assignments::check_name_availability::Error),
#[error(transparent)]
ClusterPrincipalAssignments_Get(#[from] cluster_principal_assignments::get::Error),
#[error(transparent)]
ClusterPrincipalAssignments_CreateOrUpdate(#[from] cluster_principal_assignments::create_or_update::Error),
#[error(transparent)]
ClusterPrincipalAssignments_Delete(#[from] cluster_principal_assignments::delete::Error),
#[error(transparent)]
ClusterPrincipalAssignments_List(#[from] cluster_principal_assignments::list::Error),
#[error(transparent)]
Clusters_ListFollowerDatabases(#[from] clusters::list_follower_databases::Error),
#[error(transparent)]
Clusters_DetachFollowerDatabases(#[from] clusters::detach_follower_databases::Error),
#[error(transparent)]
Clusters_DiagnoseVirtualNetwork(#[from] clusters::diagnose_virtual_network::Error),
#[error(transparent)]
Clusters_ListByResourceGroup(#[from] clusters::list_by_resource_group::Error),
#[error(transparent)]
Clusters_List(#[from] clusters::list::Error),
#[error(transparent)]
Clusters_ListSkus(#[from] clusters::list_skus::Error),
#[error(transparent)]
Clusters_CheckNameAvailability(#[from] clusters::check_name_availability::Error),
#[error(transparent)]
Databases_CheckNameAvailability(#[from] databases::check_name_availability::Error),
#[error(transparent)]
Clusters_ListSkusByResource(#[from] clusters::list_skus_by_resource::Error),
#[error(transparent)]
Databases_ListByCluster(#[from] databases::list_by_cluster::Error),
#[error(transparent)]
Databases_Get(#[from] databases::get::Error),
#[error(transparent)]
Databases_CreateOrUpdate(#[from] databases::create_or_update::Error),
#[error(transparent)]
Databases_Update(#[from] databases::update::Error),
#[error(transparent)]
Databases_Delete(#[from] databases::delete::Error),
#[error(transparent)]
DatabasePrincipalAssignments_CheckNameAvailability(#[from] database_principal_assignments::check_name_availability::Error),
#[error(transparent)]
DatabasePrincipalAssignments_Get(#[from] database_principal_assignments::get::Error),
#[error(transparent)]
DatabasePrincipalAssignments_CreateOrUpdate(#[from] database_principal_assignments::create_or_update::Error),
#[error(transparent)]
DatabasePrincipalAssignments_Delete(#[from] database_principal_assignments::delete::Error),
#[error(transparent)]
DatabasePrincipalAssignments_List(#[from] database_principal_assignments::list::Error),
#[error(transparent)]
Databases_ListPrincipals(#[from] databases::list_principals::Error),
#[error(transparent)]
Databases_AddPrincipals(#[from] databases::add_principals::Error),
#[error(transparent)]
AttachedDatabaseConfigurations_ListByCluster(#[from] attached_database_configurations::list_by_cluster::Error),
#[error(transparent)]
AttachedDatabaseConfigurations_Get(#[from] attached_database_configurations::get::Error),
#[error(transparent)]
AttachedDatabaseConfigurations_CreateOrUpdate(#[from] attached_database_configurations::create_or_update::Error),
#[error(transparent)]
AttachedDatabaseConfigurations_Delete(#[from] attached_database_configurations::delete::Error),
#[error(transparent)]
Databases_RemovePrincipals(#[from] databases::remove_principals::Error),
#[error(transparent)]
DataConnections_ListByDatabase(#[from] data_connections::list_by_database::Error),
#[error(transparent)]
DataConnections_DataConnectionValidation(#[from] data_connections::data_connection_validation::Error),
#[error(transparent)]
DataConnections_CheckNameAvailability(#[from] data_connections::check_name_availability::Error),
#[error(transparent)]
DataConnections_Get(#[from] data_connections::get::Error),
#[error(transparent)]
DataConnections_CreateOrUpdate(#[from] data_connections::create_or_update::Error),
#[error(transparent)]
DataConnections_Update(#[from] data_connections::update::Error),
#[error(transparent)]
DataConnections_Delete(#[from] data_connections::delete::Error),
#[error(transparent)]
Operations_List(#[from] operations::list::Error),
#[error(transparent)]
Clusters_ListLanguageExtensions(#[from] clusters::list_language_extensions::Error),
#[error(transparent)]
Clusters_AddLanguageExtensions(#[from] clusters::add_language_extensions::Error),
#[error(transparent)]
Clusters_RemoveLanguageExtensions(#[from] clusters::remove_language_extensions::Error),
}
pub mod clusters {
use super::{models, API_VERSION};
pub struct Client(pub(crate) super::Client);
impl Client {
pub fn get(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
subscription_id: impl Into<String>,
) -> get::Builder {
get::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
subscription_id: subscription_id.into(),
}
}
pub fn create_or_update(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
parameters: impl Into<models::Cluster>,
subscription_id: impl Into<String>,
) -> create_or_update::Builder {
create_or_update::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
parameters: parameters.into(),
subscription_id: subscription_id.into(),
}
}
pub fn update(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
parameters: impl Into<models::ClusterUpdate>,
subscription_id: impl Into<String>,
) -> update::Builder {
update::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
parameters: parameters.into(),
subscription_id: subscription_id.into(),
}
}
pub fn delete(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
subscription_id: impl Into<String>,
) -> delete::Builder {
delete::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
subscription_id: subscription_id.into(),
}
}
pub fn stop(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
subscription_id: impl Into<String>,
) -> stop::Builder {
stop::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
subscription_id: subscription_id.into(),
}
}
pub fn start(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
subscription_id: impl Into<String>,
) -> start::Builder {
start::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
subscription_id: subscription_id.into(),
}
}
pub fn list_follower_databases(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
subscription_id: impl Into<String>,
) -> list_follower_databases::Builder {
list_follower_databases::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
subscription_id: subscription_id.into(),
}
}
pub fn detach_follower_databases(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
subscription_id: impl Into<String>,
follower_database_to_remove: impl Into<models::FollowerDatabaseDefinition>,
) -> detach_follower_databases::Builder {
detach_follower_databases::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
subscription_id: subscription_id.into(),
follower_database_to_remove: follower_database_to_remove.into(),
}
}
pub fn diagnose_virtual_network(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
subscription_id: impl Into<String>,
) -> diagnose_virtual_network::Builder {
diagnose_virtual_network::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
subscription_id: subscription_id.into(),
}
}
pub fn list_by_resource_group(
&self,
resource_group_name: impl Into<String>,
subscription_id: impl Into<String>,
) -> list_by_resource_group::Builder {
list_by_resource_group::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
subscription_id: subscription_id.into(),
}
}
pub fn list(&self, subscription_id: impl Into<String>) -> list::Builder {
list::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
}
}
pub fn list_skus(&self, subscription_id: impl Into<String>) -> list_skus::Builder {
list_skus::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
}
}
pub fn check_name_availability(
&self,
subscription_id: impl Into<String>,
location: impl Into<String>,
cluster_name: impl Into<models::ClusterCheckNameRequest>,
) -> check_name_availability::Builder {
check_name_availability::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
location: location.into(),
cluster_name: cluster_name.into(),
}
}
pub fn list_skus_by_resource(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
subscription_id: impl Into<String>,
) -> list_skus_by_resource::Builder {
list_skus_by_resource::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
subscription_id: subscription_id.into(),
}
}
pub fn list_language_extensions(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
) -> list_language_extensions::Builder {
list_language_extensions::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
}
}
pub fn add_language_extensions(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
language_extensions_to_add: impl Into<models::LanguageExtensionsList>,
) -> add_language_extensions::Builder {
add_language_extensions::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
language_extensions_to_add: language_extensions_to_add.into(),
}
}
pub fn remove_language_extensions(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
language_extensions_to_remove: impl Into<models::LanguageExtensionsList>,
) -> remove_language_extensions::Builder {
remove_language_extensions::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
language_extensions_to_remove: language_extensions_to_remove.into(),
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Cluster, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name
);
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", super::API_VERSION);
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::Cluster =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 create_or_update {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::Cluster),
Created201(models::Cluster),
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) parameters: models::Cluster,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name
);
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::PUT);
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", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?;
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::Cluster =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Ok200(rsp_value))
}
http::StatusCode::CREATED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Cluster =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Created201(rsp_value))
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 update {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::Cluster),
Created201(models::Cluster),
Accepted202(models::Cluster),
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) parameters: models::ClusterUpdate,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name
);
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::PATCH);
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", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?;
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::Cluster =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Ok200(rsp_value))
}
http::StatusCode::CREATED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Cluster =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Created201(rsp_value))
}
http::StatusCode::ACCEPTED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Cluster =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Accepted202(rsp_value))
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 delete {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200,
Accepted202,
NoContent204,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name
);
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::DELETE);
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", super::API_VERSION);
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 => Ok(Response::Ok200),
http::StatusCode::ACCEPTED => Ok(Response::Accepted202),
http::StatusCode::NO_CONTENT => Ok(Response::NoContent204),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 stop {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200,
Accepted202,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/stop",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name
);
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::POST);
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", super::API_VERSION);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0);
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 => Ok(Response::Ok200),
http::StatusCode::ACCEPTED => Ok(Response::Accepted202),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 start {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200,
Accepted202,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/start",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name
);
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::POST);
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", super::API_VERSION);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0);
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 => Ok(Response::Ok200),
http::StatusCode::ACCEPTED => Ok(Response::Accepted202),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 list_follower_databases {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(
self,
) -> futures::future::BoxFuture<'static, std::result::Result<models::FollowerDatabaseListResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/listFollowerDatabases",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name
);
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::POST);
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", super::API_VERSION);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0);
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::FollowerDatabaseListResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 detach_follower_databases {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200,
Accepted202,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) subscription_id: String,
pub(crate) follower_database_to_remove: models::FollowerDatabaseDefinition,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/detachFollowerDatabases",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name
);
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::POST);
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", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.follower_database_to_remove).map_err(Error::Serialize)?;
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 => Ok(Response::Ok200),
http::StatusCode::ACCEPTED => Ok(Response::Accepted202),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 diagnose_virtual_network {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::DiagnoseVirtualNetworkResult),
Accepted202,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/diagnoseVirtualNetwork",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name
);
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::POST);
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", super::API_VERSION);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0);
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::DiagnoseVirtualNetworkResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Ok200(rsp_value))
}
http::StatusCode::ACCEPTED => Ok(Response::Accepted202),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 list_by_resource_group {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::ClusterListResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name
);
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", super::API_VERSION);
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::ClusterListResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 list {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::ClusterListResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.Kusto/clusters",
self.client.endpoint(),
&self.subscription_id
);
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", super::API_VERSION);
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::ClusterListResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 list_skus {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::SkuDescriptionList, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.Kusto/skus",
self.client.endpoint(),
&self.subscription_id
);
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", super::API_VERSION);
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::SkuDescriptionList =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 check_name_availability {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) location: String,
pub(crate) cluster_name: models::ClusterCheckNameRequest,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::CheckNameResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.Kusto/locations/{}/checkNameAvailability",
self.client.endpoint(),
&self.subscription_id,
&self.location
);
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::POST);
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", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.cluster_name).map_err(Error::Serialize)?;
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::CheckNameResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 list_skus_by_resource {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::ListResourceSkusResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/skus",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name
);
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", super::API_VERSION);
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::ListResourceSkusResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 list_language_extensions {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::LanguageExtensionsList, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/listLanguageExtensions",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name
);
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::POST);
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", super::API_VERSION);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0);
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::LanguageExtensionsList =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 add_language_extensions {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200,
Accepted202,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) language_extensions_to_add: models::LanguageExtensionsList,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/addLanguageExtensions",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name
);
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::POST);
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", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.language_extensions_to_add).map_err(Error::Serialize)?;
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 => Ok(Response::Ok200),
http::StatusCode::ACCEPTED => Ok(Response::Accepted202),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 remove_language_extensions {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200,
Accepted202,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) language_extensions_to_remove: models::LanguageExtensionsList,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/removeLanguageExtensions",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name
);
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::POST);
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", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.language_extensions_to_remove).map_err(Error::Serialize)?;
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 => Ok(Response::Ok200),
http::StatusCode::ACCEPTED => Ok(Response::Accepted202),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 cluster_principal_assignments {
use super::{models, API_VERSION};
pub struct Client(pub(crate) super::Client);
impl Client {
pub fn check_name_availability(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
subscription_id: impl Into<String>,
principal_assignment_name: impl Into<models::ClusterPrincipalAssignmentCheckNameRequest>,
) -> check_name_availability::Builder {
check_name_availability::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
subscription_id: subscription_id.into(),
principal_assignment_name: principal_assignment_name.into(),
}
}
pub fn get(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
principal_assignment_name: impl Into<String>,
) -> get::Builder {
get::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
principal_assignment_name: principal_assignment_name.into(),
}
}
pub fn create_or_update(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
principal_assignment_name: impl Into<String>,
parameters: impl Into<models::ClusterPrincipalAssignment>,
) -> create_or_update::Builder {
create_or_update::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
principal_assignment_name: principal_assignment_name.into(),
parameters: parameters.into(),
}
}
pub fn delete(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
principal_assignment_name: impl Into<String>,
) -> delete::Builder {
delete::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
principal_assignment_name: principal_assignment_name.into(),
}
}
pub fn list(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
) -> list::Builder {
list::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
}
}
}
pub mod check_name_availability {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) subscription_id: String,
pub(crate) principal_assignment_name: models::ClusterPrincipalAssignmentCheckNameRequest,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::CheckNameResult, Error>> {
Box::pin(async move {
let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/checkPrincipalAssignmentNameAvailability" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . cluster_name) ;
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::POST);
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", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.principal_assignment_name).map_err(Error::Serialize)?;
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::CheckNameResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) principal_assignment_name: String,
}
impl Builder {
pub fn into_future(
self,
) -> futures::future::BoxFuture<'static, std::result::Result<models::ClusterPrincipalAssignment, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/principalAssignments/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.principal_assignment_name
);
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", super::API_VERSION);
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::ClusterPrincipalAssignment =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 create_or_update {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::ClusterPrincipalAssignment),
Created201(models::ClusterPrincipalAssignment),
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) principal_assignment_name: String,
pub(crate) parameters: models::ClusterPrincipalAssignment,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/principalAssignments/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.principal_assignment_name
);
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::PUT);
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", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?;
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::ClusterPrincipalAssignment =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Ok200(rsp_value))
}
http::StatusCode::CREATED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ClusterPrincipalAssignment =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Created201(rsp_value))
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 delete {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200,
Accepted202,
NoContent204,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) principal_assignment_name: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/principalAssignments/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.principal_assignment_name
);
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::DELETE);
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", super::API_VERSION);
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 => Ok(Response::Ok200),
http::StatusCode::ACCEPTED => Ok(Response::Accepted202),
http::StatusCode::NO_CONTENT => Ok(Response::NoContent204),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 list {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
}
impl Builder {
pub fn into_future(
self,
) -> futures::future::BoxFuture<'static, std::result::Result<models::ClusterPrincipalAssignmentListResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/principalAssignments",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name
);
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", super::API_VERSION);
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::ClusterPrincipalAssignmentListResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 databases {
use super::{models, API_VERSION};
pub struct Client(pub(crate) super::Client);
impl Client {
pub fn check_name_availability(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
subscription_id: impl Into<String>,
resource_name: impl Into<models::CheckNameRequest>,
) -> check_name_availability::Builder {
check_name_availability::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
subscription_id: subscription_id.into(),
resource_name: resource_name.into(),
}
}
pub fn list_by_cluster(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
subscription_id: impl Into<String>,
) -> list_by_cluster::Builder {
list_by_cluster::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
subscription_id: subscription_id.into(),
}
}
pub fn get(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
database_name: impl Into<String>,
subscription_id: impl Into<String>,
) -> get::Builder {
get::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
database_name: database_name.into(),
subscription_id: subscription_id.into(),
}
}
pub fn create_or_update(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
database_name: impl Into<String>,
parameters: impl Into<models::Database>,
subscription_id: impl Into<String>,
) -> create_or_update::Builder {
create_or_update::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
database_name: database_name.into(),
parameters: parameters.into(),
subscription_id: subscription_id.into(),
}
}
pub fn update(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
database_name: impl Into<String>,
parameters: impl Into<models::Database>,
subscription_id: impl Into<String>,
) -> update::Builder {
update::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
database_name: database_name.into(),
parameters: parameters.into(),
subscription_id: subscription_id.into(),
}
}
pub fn delete(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
database_name: impl Into<String>,
subscription_id: impl Into<String>,
) -> delete::Builder {
delete::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
database_name: database_name.into(),
subscription_id: subscription_id.into(),
}
}
pub fn list_principals(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
database_name: impl Into<String>,
subscription_id: impl Into<String>,
) -> list_principals::Builder {
list_principals::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
database_name: database_name.into(),
subscription_id: subscription_id.into(),
}
}
pub fn add_principals(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
database_name: impl Into<String>,
subscription_id: impl Into<String>,
database_principals_to_add: impl Into<models::DatabasePrincipalListRequest>,
) -> add_principals::Builder {
add_principals::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
database_name: database_name.into(),
subscription_id: subscription_id.into(),
database_principals_to_add: database_principals_to_add.into(),
}
}
pub fn remove_principals(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
database_name: impl Into<String>,
subscription_id: impl Into<String>,
database_principals_to_remove: impl Into<models::DatabasePrincipalListRequest>,
) -> remove_principals::Builder {
remove_principals::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
database_name: database_name.into(),
subscription_id: subscription_id.into(),
database_principals_to_remove: database_principals_to_remove.into(),
}
}
}
pub mod check_name_availability {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) subscription_id: String,
pub(crate) resource_name: models::CheckNameRequest,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::CheckNameResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/checkNameAvailability",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name
);
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::POST);
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", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.resource_name).map_err(Error::Serialize)?;
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::CheckNameResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 list_by_cluster {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::DatabaseListResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/databases",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name
);
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", super::API_VERSION);
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::DatabaseListResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) database_name: String,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::Database, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/databases/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.database_name
);
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", super::API_VERSION);
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::Database =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 create_or_update {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::Database),
Created201(models::Database),
Accepted202(models::Database),
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) database_name: String,
pub(crate) parameters: models::Database,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/databases/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.database_name
);
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::PUT);
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", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?;
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::Database =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Ok200(rsp_value))
}
http::StatusCode::CREATED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Database =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Created201(rsp_value))
}
http::StatusCode::ACCEPTED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Database =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Accepted202(rsp_value))
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 update {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::Database),
Created201(models::Database),
Accepted202(models::Database),
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) database_name: String,
pub(crate) parameters: models::Database,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/databases/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.database_name
);
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::PATCH);
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", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?;
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::Database =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Ok200(rsp_value))
}
http::StatusCode::CREATED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Database =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Created201(rsp_value))
}
http::StatusCode::ACCEPTED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::Database =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Accepted202(rsp_value))
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 delete {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200,
Accepted202,
NoContent204,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) database_name: String,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/databases/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.database_name
);
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::DELETE);
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", super::API_VERSION);
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 => Ok(Response::Ok200),
http::StatusCode::ACCEPTED => Ok(Response::Accepted202),
http::StatusCode::NO_CONTENT => Ok(Response::NoContent204),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 list_principals {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) database_name: String,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(
self,
) -> futures::future::BoxFuture<'static, std::result::Result<models::DatabasePrincipalListResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/databases/{}/listPrincipals",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.database_name
);
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::POST);
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", super::API_VERSION);
let req_body = azure_core::EMPTY_BODY;
req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0);
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::DatabasePrincipalListResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 add_principals {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) database_name: String,
pub(crate) subscription_id: String,
pub(crate) database_principals_to_add: models::DatabasePrincipalListRequest,
}
impl Builder {
pub fn into_future(
self,
) -> futures::future::BoxFuture<'static, std::result::Result<models::DatabasePrincipalListResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/databases/{}/addPrincipals",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.database_name
);
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::POST);
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", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.database_principals_to_add).map_err(Error::Serialize)?;
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::DatabasePrincipalListResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 remove_principals {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) database_name: String,
pub(crate) subscription_id: String,
pub(crate) database_principals_to_remove: models::DatabasePrincipalListRequest,
}
impl Builder {
pub fn into_future(
self,
) -> futures::future::BoxFuture<'static, std::result::Result<models::DatabasePrincipalListResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/databases/{}/removePrincipals",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.database_name
);
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::POST);
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", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.database_principals_to_remove).map_err(Error::Serialize)?;
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::DatabasePrincipalListResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 database_principal_assignments {
use super::{models, API_VERSION};
pub struct Client(pub(crate) super::Client);
impl Client {
pub fn check_name_availability(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
database_name: impl Into<String>,
subscription_id: impl Into<String>,
principal_assignment_name: impl Into<models::DatabasePrincipalAssignmentCheckNameRequest>,
) -> check_name_availability::Builder {
check_name_availability::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
database_name: database_name.into(),
subscription_id: subscription_id.into(),
principal_assignment_name: principal_assignment_name.into(),
}
}
pub fn get(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
database_name: impl Into<String>,
principal_assignment_name: impl Into<String>,
) -> get::Builder {
get::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
database_name: database_name.into(),
principal_assignment_name: principal_assignment_name.into(),
}
}
pub fn create_or_update(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
database_name: impl Into<String>,
principal_assignment_name: impl Into<String>,
parameters: impl Into<models::DatabasePrincipalAssignment>,
) -> create_or_update::Builder {
create_or_update::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
database_name: database_name.into(),
principal_assignment_name: principal_assignment_name.into(),
parameters: parameters.into(),
}
}
pub fn delete(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
database_name: impl Into<String>,
principal_assignment_name: impl Into<String>,
) -> delete::Builder {
delete::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
database_name: database_name.into(),
principal_assignment_name: principal_assignment_name.into(),
}
}
pub fn list(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
database_name: impl Into<String>,
) -> list::Builder {
list::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
database_name: database_name.into(),
}
}
}
pub mod check_name_availability {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) database_name: String,
pub(crate) subscription_id: String,
pub(crate) principal_assignment_name: models::DatabasePrincipalAssignmentCheckNameRequest,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::CheckNameResult, Error>> {
Box::pin(async move {
let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/databases/{}/checkPrincipalAssignmentNameAvailability" , self . client . endpoint () , & self . subscription_id , & self . resource_group_name , & self . cluster_name , & self . database_name) ;
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::POST);
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", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.principal_assignment_name).map_err(Error::Serialize)?;
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::CheckNameResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) database_name: String,
pub(crate) principal_assignment_name: String,
}
impl Builder {
pub fn into_future(
self,
) -> futures::future::BoxFuture<'static, std::result::Result<models::DatabasePrincipalAssignment, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/databases/{}/principalAssignments/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.database_name,
&self.principal_assignment_name
);
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", super::API_VERSION);
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::DatabasePrincipalAssignment =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 create_or_update {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::DatabasePrincipalAssignment),
Created201(models::DatabasePrincipalAssignment),
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) database_name: String,
pub(crate) principal_assignment_name: String,
pub(crate) parameters: models::DatabasePrincipalAssignment,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/databases/{}/principalAssignments/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.database_name,
&self.principal_assignment_name
);
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::PUT);
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", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?;
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::DatabasePrincipalAssignment =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Ok200(rsp_value))
}
http::StatusCode::CREATED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::DatabasePrincipalAssignment =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Created201(rsp_value))
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 delete {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200,
Accepted202,
NoContent204,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) database_name: String,
pub(crate) principal_assignment_name: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/databases/{}/principalAssignments/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.database_name,
&self.principal_assignment_name
);
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::DELETE);
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", super::API_VERSION);
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 => Ok(Response::Ok200),
http::StatusCode::ACCEPTED => Ok(Response::Accepted202),
http::StatusCode::NO_CONTENT => Ok(Response::NoContent204),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 list {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) database_name: String,
}
impl Builder {
pub fn into_future(
self,
) -> futures::future::BoxFuture<'static, std::result::Result<models::DatabasePrincipalAssignmentListResult, Error>>
{
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/databases/{}/principalAssignments",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.database_name
);
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", super::API_VERSION);
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::DatabasePrincipalAssignmentListResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 attached_database_configurations {
use super::{models, API_VERSION};
pub struct Client(pub(crate) super::Client);
impl Client {
pub fn list_by_cluster(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
subscription_id: impl Into<String>,
) -> list_by_cluster::Builder {
list_by_cluster::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
subscription_id: subscription_id.into(),
}
}
pub fn get(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
attached_database_configuration_name: impl Into<String>,
subscription_id: impl Into<String>,
) -> get::Builder {
get::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
attached_database_configuration_name: attached_database_configuration_name.into(),
subscription_id: subscription_id.into(),
}
}
pub fn create_or_update(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
attached_database_configuration_name: impl Into<String>,
parameters: impl Into<models::AttachedDatabaseConfiguration>,
subscription_id: impl Into<String>,
) -> create_or_update::Builder {
create_or_update::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
attached_database_configuration_name: attached_database_configuration_name.into(),
parameters: parameters.into(),
subscription_id: subscription_id.into(),
}
}
pub fn delete(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
attached_database_configuration_name: impl Into<String>,
subscription_id: impl Into<String>,
) -> delete::Builder {
delete::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
attached_database_configuration_name: attached_database_configuration_name.into(),
subscription_id: subscription_id.into(),
}
}
}
pub mod list_by_cluster {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(
self,
) -> futures::future::BoxFuture<'static, std::result::Result<models::AttachedDatabaseConfigurationListResult, Error>>
{
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/attachedDatabaseConfigurations",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name
);
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", super::API_VERSION);
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::AttachedDatabaseConfigurationListResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) attached_database_configuration_name: String,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(
self,
) -> futures::future::BoxFuture<'static, std::result::Result<models::AttachedDatabaseConfiguration, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/attachedDatabaseConfigurations/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.attached_database_configuration_name
);
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", super::API_VERSION);
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::AttachedDatabaseConfiguration =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 create_or_update {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::AttachedDatabaseConfiguration),
Created201(models::AttachedDatabaseConfiguration),
Accepted202(models::AttachedDatabaseConfiguration),
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) attached_database_configuration_name: String,
pub(crate) parameters: models::AttachedDatabaseConfiguration,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/attachedDatabaseConfigurations/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.attached_database_configuration_name
);
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::PUT);
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", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?;
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::AttachedDatabaseConfiguration =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Ok200(rsp_value))
}
http::StatusCode::CREATED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::AttachedDatabaseConfiguration =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Created201(rsp_value))
}
http::StatusCode::ACCEPTED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::AttachedDatabaseConfiguration =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Accepted202(rsp_value))
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 delete {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200,
Accepted202,
NoContent204,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) attached_database_configuration_name: String,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/attachedDatabaseConfigurations/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.attached_database_configuration_name
);
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::DELETE);
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", super::API_VERSION);
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 => Ok(Response::Ok200),
http::StatusCode::ACCEPTED => Ok(Response::Accepted202),
http::StatusCode::NO_CONTENT => Ok(Response::NoContent204),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 data_connections {
use super::{models, API_VERSION};
pub struct Client(pub(crate) super::Client);
impl Client {
pub fn list_by_database(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
database_name: impl Into<String>,
subscription_id: impl Into<String>,
) -> list_by_database::Builder {
list_by_database::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
database_name: database_name.into(),
subscription_id: subscription_id.into(),
}
}
pub fn data_connection_validation(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
database_name: impl Into<String>,
subscription_id: impl Into<String>,
parameters: impl Into<models::DataConnectionValidation>,
) -> data_connection_validation::Builder {
data_connection_validation::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
database_name: database_name.into(),
subscription_id: subscription_id.into(),
parameters: parameters.into(),
}
}
pub fn check_name_availability(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
database_name: impl Into<String>,
subscription_id: impl Into<String>,
data_connection_name: impl Into<models::DataConnectionCheckNameRequest>,
) -> check_name_availability::Builder {
check_name_availability::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
database_name: database_name.into(),
subscription_id: subscription_id.into(),
data_connection_name: data_connection_name.into(),
}
}
pub fn get(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
database_name: impl Into<String>,
data_connection_name: impl Into<String>,
subscription_id: impl Into<String>,
) -> get::Builder {
get::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
database_name: database_name.into(),
data_connection_name: data_connection_name.into(),
subscription_id: subscription_id.into(),
}
}
pub fn create_or_update(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
database_name: impl Into<String>,
data_connection_name: impl Into<String>,
parameters: impl Into<models::DataConnection>,
subscription_id: impl Into<String>,
) -> create_or_update::Builder {
create_or_update::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
database_name: database_name.into(),
data_connection_name: data_connection_name.into(),
parameters: parameters.into(),
subscription_id: subscription_id.into(),
}
}
pub fn update(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
database_name: impl Into<String>,
data_connection_name: impl Into<String>,
parameters: impl Into<models::DataConnection>,
subscription_id: impl Into<String>,
) -> update::Builder {
update::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
database_name: database_name.into(),
data_connection_name: data_connection_name.into(),
parameters: parameters.into(),
subscription_id: subscription_id.into(),
}
}
pub fn delete(
&self,
resource_group_name: impl Into<String>,
cluster_name: impl Into<String>,
database_name: impl Into<String>,
data_connection_name: impl Into<String>,
subscription_id: impl Into<String>,
) -> delete::Builder {
delete::Builder {
client: self.0.clone(),
resource_group_name: resource_group_name.into(),
cluster_name: cluster_name.into(),
database_name: database_name.into(),
data_connection_name: data_connection_name.into(),
subscription_id: subscription_id.into(),
}
}
}
pub mod list_by_database {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) database_name: String,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::DataConnectionListResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/databases/{}/dataConnections",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.database_name
);
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", super::API_VERSION);
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::DataConnectionListResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 data_connection_validation {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::DataConnectionValidationListResult),
Accepted202,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) database_name: String,
pub(crate) subscription_id: String,
pub(crate) parameters: models::DataConnectionValidation,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/databases/{}/dataConnectionValidation",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.database_name
);
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::POST);
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", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?;
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::DataConnectionValidationListResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Ok200(rsp_value))
}
http::StatusCode::ACCEPTED => Ok(Response::Accepted202),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 check_name_availability {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) database_name: String,
pub(crate) subscription_id: String,
pub(crate) data_connection_name: models::DataConnectionCheckNameRequest,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::CheckNameResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/databases/{}/checkNameAvailability",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.database_name
);
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::POST);
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", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.data_connection_name).map_err(Error::Serialize)?;
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::CheckNameResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) database_name: String,
pub(crate) data_connection_name: String,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::DataConnection, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/databases/{}/dataConnections/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.database_name,
&self.data_connection_name
);
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", super::API_VERSION);
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::DataConnection =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 create_or_update {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::DataConnection),
Created201(models::DataConnection),
Accepted202(models::DataConnection),
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) database_name: String,
pub(crate) data_connection_name: String,
pub(crate) parameters: models::DataConnection,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/databases/{}/dataConnections/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.database_name,
&self.data_connection_name
);
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::PUT);
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", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?;
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::DataConnection =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Ok200(rsp_value))
}
http::StatusCode::CREATED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::DataConnection =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Created201(rsp_value))
}
http::StatusCode::ACCEPTED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::DataConnection =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Accepted202(rsp_value))
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 update {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::DataConnection),
Created201(models::DataConnection),
Accepted202(models::DataConnection),
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) database_name: String,
pub(crate) data_connection_name: String,
pub(crate) parameters: models::DataConnection,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/databases/{}/dataConnections/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.database_name,
&self.data_connection_name
);
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::PATCH);
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", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?;
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::DataConnection =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Ok200(rsp_value))
}
http::StatusCode::CREATED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::DataConnection =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Created201(rsp_value))
}
http::StatusCode::ACCEPTED => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::DataConnection =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Accepted202(rsp_value))
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 delete {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200,
Accepted202,
NoContent204,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) resource_group_name: String,
pub(crate) cluster_name: String,
pub(crate) database_name: String,
pub(crate) data_connection_name: String,
pub(crate) subscription_id: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kusto/clusters/{}/databases/{}/dataConnections/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.cluster_name,
&self.database_name,
&self.data_connection_name
);
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::DELETE);
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", super::API_VERSION);
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 => Ok(Response::Ok200),
http::StatusCode::ACCEPTED => Ok(Response::Accepted202),
http::StatusCode::NO_CONTENT => Ok(Response::NoContent204),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
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 operations {
use super::{models, API_VERSION};
pub struct Client(pub(crate) super::Client);
impl Client {
pub fn list(&self) -> list::Builder {
list::Builder { client: self.0.clone() }
}
}
pub mod list {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::CloudError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::OperationListResult, Error>> {
Box::pin(async move {
let url_str = &format!("{}/providers/Microsoft.Kusto/operations", 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", super::API_VERSION);
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::OperationListResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::CloudError =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
}
| 51.611156 | 317 | 0.521017 |
7a6bf0f819e5e4b2d324068a41ab8abaf6a26062 | 83,529 | //!
//! Take an AST and transform it into bytecode
//!
//! Inspirational code:
//! https://github.com/python/cpython/blob/master/Python/compile.c
//! https://github.com/micropython/micropython/blob/master/py/compile.c
use crate::error::{CompileError, CompileErrorType};
pub use crate::mode::Mode;
use crate::symboltable::{
make_symbol_table, statements_to_symbol_table, Symbol, SymbolScope, SymbolTable,
};
use indexmap::IndexSet;
use itertools::Itertools;
use num_complex::Complex64;
use rustpython_ast as ast;
use rustpython_bytecode::bytecode::{self, CallType, CodeObject, Instruction, Label};
type CompileResult<T> = Result<T, CompileError>;
/// Main structure holding the state of compilation.
struct Compiler {
output_stack: Vec<(CodeObject, IndexSet<String>)>,
symbol_table_stack: Vec<SymbolTable>,
nxt_label: usize,
source_path: String,
current_source_location: ast::Location,
current_qualified_path: Option<String>,
done_with_future_stmts: bool,
ctx: CompileContext,
opts: CompileOpts,
}
#[derive(Debug, Clone)]
pub struct CompileOpts {
/// How optimized the bytecode output should be; any optimize > 0 does
/// not emit assert statements
pub optimize: u8,
}
impl Default for CompileOpts {
fn default() -> Self {
CompileOpts { optimize: 0 }
}
}
#[derive(Clone, Copy)]
struct CompileContext {
in_loop: bool,
func: FunctionContext,
}
#[derive(Clone, Copy, PartialEq)]
enum FunctionContext {
NoFunction,
Function,
AsyncFunction,
}
impl CompileContext {
fn in_func(self) -> bool {
!matches!(self.func, FunctionContext::NoFunction)
}
}
/// A helper function for the shared code of the different compile functions
fn with_compiler(
source_path: String,
opts: CompileOpts,
f: impl FnOnce(&mut Compiler) -> CompileResult<()>,
) -> CompileResult<CodeObject> {
let mut compiler = Compiler::new(opts, source_path);
compiler.push_new_code_object("<module>".to_owned());
f(&mut compiler)?;
let code = compiler.pop_code_object();
trace!("Compilation completed: {:?}", code);
Ok(code)
}
/// Compile a standard Python program to bytecode
pub fn compile_program(
ast: ast::Program,
source_path: String,
opts: CompileOpts,
) -> CompileResult<CodeObject> {
let symbol_table = match make_symbol_table(&ast) {
Ok(x) => x,
Err(e) => return Err(e.into_compile_error(source_path)),
};
with_compiler(source_path, opts, |compiler| {
compiler.compile_program(&ast, symbol_table)
})
}
/// Compile a single Python expression to bytecode
pub fn compile_statement_eval(
statement: Vec<ast::Statement>,
source_path: String,
opts: CompileOpts,
) -> CompileResult<CodeObject> {
let symbol_table = match statements_to_symbol_table(&statement) {
Ok(x) => x,
Err(e) => return Err(e.into_compile_error(source_path)),
};
with_compiler(source_path, opts, |compiler| {
compiler.compile_statement_eval(&statement, symbol_table)
})
}
/// Compile a Python program to bytecode for the context of a REPL
pub fn compile_program_single(
ast: ast::Program,
source_path: String,
opts: CompileOpts,
) -> CompileResult<CodeObject> {
let symbol_table = match make_symbol_table(&ast) {
Ok(x) => x,
Err(e) => return Err(e.into_compile_error(source_path)),
};
with_compiler(source_path, opts, |compiler| {
compiler.compile_program_single(&ast, symbol_table)
})
}
impl Compiler {
fn new(opts: CompileOpts, source_path: String) -> Self {
Compiler {
output_stack: Vec::new(),
symbol_table_stack: Vec::new(),
nxt_label: 0,
source_path,
current_source_location: ast::Location::default(),
current_qualified_path: None,
done_with_future_stmts: false,
ctx: CompileContext {
in_loop: false,
func: FunctionContext::NoFunction,
},
opts,
}
}
fn error(&self, error: CompileErrorType) -> CompileError {
self.error_loc(error, self.current_source_location)
}
fn error_loc(&self, error: CompileErrorType, location: ast::Location) -> CompileError {
CompileError {
error,
location,
source_path: self.source_path.clone(),
}
}
fn push_output(&mut self, code: CodeObject) {
self.output_stack.push((code, IndexSet::new()));
}
fn push_new_code_object(&mut self, obj_name: String) {
let line_number = self.get_source_line_number();
self.push_output(CodeObject::new(
Default::default(),
0,
0,
0,
self.source_path.clone(),
line_number,
obj_name,
));
}
fn pop_code_object(&mut self) -> CodeObject {
let (mut code, names) = self.output_stack.pop().unwrap();
code.names.extend(names);
code
}
// could take impl Into<Cow<str>>, but everything is borrowed from ast structs; we never
// actually have a `String` to pass
fn name(&mut self, name: &str) -> bytecode::NameIdx {
let cache = &mut self.output_stack.last_mut().expect("nothing on stack").1;
if let Some(x) = cache.get_index_of(name) {
x
} else {
cache.insert_full(name.to_owned()).0
}
}
fn compile_program(
&mut self,
program: &ast::Program,
symbol_table: SymbolTable,
) -> CompileResult<()> {
let size_before = self.output_stack.len();
self.symbol_table_stack.push(symbol_table);
let (statements, doc) = get_doc(&program.statements);
if let Some(value) = doc {
self.emit_constant(bytecode::ConstantData::Str { value });
let doc = self.name("__doc__");
self.emit(Instruction::StoreName {
idx: doc,
scope: bytecode::NameScope::Global,
});
}
self.compile_statements(statements)?;
assert_eq!(self.output_stack.len(), size_before);
// Emit None at end:
self.emit_constant(bytecode::ConstantData::None);
self.emit(Instruction::ReturnValue);
Ok(())
}
fn compile_program_single(
&mut self,
program: &ast::Program,
symbol_table: SymbolTable,
) -> CompileResult<()> {
self.symbol_table_stack.push(symbol_table);
let mut emitted_return = false;
for (i, statement) in program.statements.iter().enumerate() {
let is_last = i == program.statements.len() - 1;
if let ast::StatementType::Expression { ref expression } = statement.node {
self.compile_expression(expression)?;
if is_last {
self.emit(Instruction::Duplicate);
self.emit(Instruction::PrintExpr);
self.emit(Instruction::ReturnValue);
emitted_return = true;
} else {
self.emit(Instruction::PrintExpr);
}
} else {
self.compile_statement(&statement)?;
}
}
if !emitted_return {
self.emit_constant(bytecode::ConstantData::None);
self.emit(Instruction::ReturnValue);
}
Ok(())
}
// Compile statement in eval mode:
fn compile_statement_eval(
&mut self,
statements: &[ast::Statement],
symbol_table: SymbolTable,
) -> CompileResult<()> {
self.symbol_table_stack.push(symbol_table);
for statement in statements {
if let ast::StatementType::Expression { ref expression } = statement.node {
self.compile_expression(expression)?;
} else {
return Err(self.error_loc(CompileErrorType::ExpectExpr, statement.location));
}
}
self.emit(Instruction::ReturnValue);
Ok(())
}
fn compile_statements(&mut self, statements: &[ast::Statement]) -> CompileResult<()> {
for statement in statements {
self.compile_statement(statement)?
}
Ok(())
}
fn scope_for_name(&self, name: &str) -> bytecode::NameScope {
let symbol = self.lookup_name(name);
match symbol.scope {
SymbolScope::Global => bytecode::NameScope::Global,
SymbolScope::Nonlocal => bytecode::NameScope::NonLocal,
SymbolScope::Unknown => bytecode::NameScope::Free,
SymbolScope::Local => {
// Only in function block, we use load local
// https://github.com/python/cpython/blob/master/Python/compile.c#L3582
if self.ctx.in_func() {
bytecode::NameScope::Local
} else {
bytecode::NameScope::Free
}
}
}
}
fn load_name(&mut self, name: &str) {
let scope = self.scope_for_name(name);
let idx = self.name(name);
self.emit(Instruction::LoadName { idx, scope });
}
fn store_name(&mut self, name: &str) {
let scope = self.scope_for_name(name);
let idx = self.name(name);
self.emit(Instruction::StoreName { idx, scope });
}
fn compile_statement(&mut self, statement: &ast::Statement) -> CompileResult<()> {
trace!("Compiling {:?}", statement);
self.set_source_location(statement.location);
use ast::StatementType::*;
match &statement.node {
// we do this here because `from __future__` still executes that `from` statement at runtime,
// we still need to compile the ImportFrom down below
ImportFrom { module, names, .. } if module.as_deref() == Some("__future__") => {
self.compile_future_features(&names)?
}
// if we find any other statement, stop accepting future statements
_ => self.done_with_future_stmts = true,
}
match &statement.node {
Import { names } => {
// import a, b, c as d
for name in names {
let name_idx = Some(self.name(&name.symbol));
self.emit(Instruction::Import {
name_idx,
symbols_idx: vec![],
level: 0,
});
if let Some(alias) = &name.alias {
for part in name.symbol.split('.').skip(1) {
let idx = self.name(part);
self.emit(Instruction::LoadAttr { idx });
}
self.store_name(alias);
} else {
self.store_name(name.symbol.split('.').next().unwrap());
}
}
}
ImportFrom {
level,
module,
names,
} => {
let import_star = names.iter().any(|n| n.symbol == "*");
let module_idx = module.as_ref().map(|s| self.name(s));
if import_star {
let star = self.name("*");
// from .... import *
self.emit(Instruction::Import {
name_idx: module_idx,
symbols_idx: vec![star],
level: *level,
});
self.emit(Instruction::ImportStar);
} else {
// from mod import a, b as c
// First, determine the fromlist (for import lib):
let from_list = names.iter().map(|n| self.name(&n.symbol)).collect();
// Load module once:
self.emit(Instruction::Import {
name_idx: module_idx,
symbols_idx: from_list,
level: *level,
});
for name in names {
let idx = self.name(&name.symbol);
// import symbol from module:
self.emit(Instruction::ImportFrom { idx });
// Store module under proper name:
if let Some(alias) = &name.alias {
self.store_name(alias);
} else {
self.store_name(&name.symbol);
}
}
// Pop module from stack:
self.emit(Instruction::Pop);
}
}
Expression { expression } => {
self.compile_expression(expression)?;
// Pop result of stack, since we not use it:
self.emit(Instruction::Pop);
}
Global { .. } | Nonlocal { .. } => {
// Handled during symbol table construction.
}
If { test, body, orelse } => {
let end_label = self.new_label();
match orelse {
None => {
// Only if:
self.compile_jump_if(test, false, end_label)?;
self.compile_statements(body)?;
self.set_label(end_label);
}
Some(statements) => {
// if - else:
let else_label = self.new_label();
self.compile_jump_if(test, false, else_label)?;
self.compile_statements(body)?;
self.emit(Instruction::Jump { target: end_label });
// else:
self.set_label(else_label);
self.compile_statements(statements)?;
}
}
self.set_label(end_label);
}
While { test, body, orelse } => self.compile_while(test, body, orelse)?,
With {
is_async,
items,
body,
} => {
let is_async = *is_async;
let end_labels = items
.iter()
.map(|item| {
let end_label = self.new_label();
self.compile_expression(&item.context_expr)?;
if is_async {
self.emit(Instruction::BeforeAsyncWith);
self.emit(Instruction::GetAwaitable);
self.emit_constant(bytecode::ConstantData::None);
self.emit(Instruction::YieldFrom);
self.emit(Instruction::SetupAsyncWith { end: end_label });
} else {
self.emit(Instruction::SetupWith { end: end_label });
}
match &item.optional_vars {
Some(var) => {
self.compile_store(var)?;
}
None => {
self.emit(Instruction::Pop);
}
}
Ok(end_label)
})
.collect::<CompileResult<Vec<_>>>()?;
self.compile_statements(body)?;
// sort of "stack up" the layers of with blocks:
// with a, b: body -> start_with(a) start_with(b) body() end_with(b) end_with(a)
for end_label in end_labels.into_iter().rev() {
self.emit(Instruction::PopBlock);
self.emit(Instruction::EnterFinally);
self.set_label(end_label);
self.emit(Instruction::WithCleanupStart);
if is_async {
self.emit(Instruction::GetAwaitable);
self.emit_constant(bytecode::ConstantData::None);
self.emit(Instruction::YieldFrom);
}
self.emit(Instruction::WithCleanupFinish);
}
}
For {
is_async,
target,
iter,
body,
orelse,
} => self.compile_for(target, iter, body, orelse, *is_async)?,
Raise { exception, cause } => match exception {
Some(value) => {
self.compile_expression(value)?;
match cause {
Some(cause) => {
self.compile_expression(cause)?;
self.emit(Instruction::Raise { argc: 2 });
}
None => {
self.emit(Instruction::Raise { argc: 1 });
}
}
}
None => {
self.emit(Instruction::Raise { argc: 0 });
}
},
Try {
body,
handlers,
orelse,
finalbody,
} => self.compile_try_statement(body, handlers, orelse, finalbody)?,
FunctionDef {
is_async,
name,
args,
body,
decorator_list,
returns,
} => {
self.compile_function_def(name, args, body, decorator_list, returns, *is_async)?;
}
ClassDef {
name,
body,
bases,
keywords,
decorator_list,
} => self.compile_class_def(name, body, bases, keywords, decorator_list)?,
Assert { test, msg } => {
// if some flag, ignore all assert statements!
if self.opts.optimize == 0 {
let end_label = self.new_label();
self.compile_jump_if(test, true, end_label)?;
let assertion_error = self.name("AssertionError");
self.emit(Instruction::LoadName {
idx: assertion_error,
scope: bytecode::NameScope::Global,
});
match msg {
Some(e) => {
self.compile_expression(e)?;
self.emit(Instruction::CallFunction {
typ: CallType::Positional(1),
});
}
None => {
self.emit(Instruction::CallFunction {
typ: CallType::Positional(0),
});
}
}
self.emit(Instruction::Raise { argc: 1 });
self.set_label(end_label);
}
}
Break => {
if !self.ctx.in_loop {
return Err(self.error_loc(CompileErrorType::InvalidBreak, statement.location));
}
self.emit(Instruction::Break);
}
Continue => {
if !self.ctx.in_loop {
return Err(
self.error_loc(CompileErrorType::InvalidContinue, statement.location)
);
}
self.emit(Instruction::Continue);
}
Return { value } => {
if !self.ctx.in_func() {
return Err(self.error_loc(CompileErrorType::InvalidReturn, statement.location));
}
match value {
Some(v) => {
if self.ctx.func == FunctionContext::AsyncFunction
&& self
.current_code()
.flags
.contains(bytecode::CodeFlags::IS_GENERATOR)
{
return Err(self.error_loc(
CompileErrorType::AsyncReturnValue,
statement.location,
));
}
self.compile_expression(v)?;
}
None => {
self.emit_constant(bytecode::ConstantData::None);
}
}
self.emit(Instruction::ReturnValue);
}
Assign { targets, value } => {
self.compile_expression(value)?;
for (i, target) in targets.iter().enumerate() {
if i + 1 != targets.len() {
self.emit(Instruction::Duplicate);
}
self.compile_store(target)?;
}
}
AugAssign { target, op, value } => {
self.compile_expression(target)?;
self.compile_expression(value)?;
// Perform operation:
self.compile_op(op, true);
self.compile_store(target)?;
}
AnnAssign {
target,
annotation,
value,
} => self.compile_annotated_assign(target, annotation, value)?,
Delete { targets } => {
for target in targets {
self.compile_delete(target)?;
}
}
Pass => {
// No need to emit any code here :)
}
}
Ok(())
}
fn compile_delete(&mut self, expression: &ast::Expression) -> CompileResult<()> {
match &expression.node {
ast::ExpressionType::Identifier { name } => {
let idx = self.name(name);
self.emit(Instruction::DeleteName { idx });
}
ast::ExpressionType::Attribute { value, name } => {
self.compile_expression(value)?;
let idx = self.name(name);
self.emit(Instruction::DeleteAttr { idx });
}
ast::ExpressionType::Subscript { a, b } => {
self.compile_expression(a)?;
self.compile_expression(b)?;
self.emit(Instruction::DeleteSubscript);
}
ast::ExpressionType::Tuple { elements } => {
for element in elements {
self.compile_delete(element)?;
}
}
_ => return Err(self.error(CompileErrorType::Delete(expression.name()))),
}
Ok(())
}
fn enter_function(&mut self, name: &str, args: &ast::Parameters) -> CompileResult<()> {
let have_defaults = !args.defaults.is_empty();
if have_defaults {
// Construct a tuple:
let size = args.defaults.len();
for element in &args.defaults {
self.compile_expression(element)?;
}
self.emit(Instruction::BuildTuple {
size,
unpack: false,
});
}
let mut num_kw_only_defaults = 0;
for (kw, default) in args.kwonlyargs.iter().zip(&args.kw_defaults) {
if let Some(default) = default {
self.emit_constant(bytecode::ConstantData::Str {
value: kw.arg.clone(),
});
self.compile_expression(default)?;
num_kw_only_defaults += 1;
}
}
if num_kw_only_defaults > 0 {
self.emit(Instruction::BuildMap {
size: num_kw_only_defaults,
unpack: false,
for_call: false,
});
}
let mut flags = bytecode::CodeFlags::default();
if have_defaults {
flags |= bytecode::CodeFlags::HAS_DEFAULTS;
}
if num_kw_only_defaults > 0 {
flags |= bytecode::CodeFlags::HAS_KW_ONLY_DEFAULTS;
}
let line_number = self.get_source_line_number();
self.push_output(CodeObject::new(
flags,
args.posonlyargs_count,
args.args.len(),
args.kwonlyargs.len(),
self.source_path.clone(),
line_number,
name.to_owned(),
));
for name in &args.args {
self.name(&name.arg);
}
for name in &args.kwonlyargs {
self.name(&name.arg);
}
let mut compile_varargs = |va: &ast::Varargs, flag| match va {
ast::Varargs::None | ast::Varargs::Unnamed => {}
ast::Varargs::Named(name) => {
self.current_code().flags |= flag;
self.name(&name.arg);
}
};
compile_varargs(&args.vararg, bytecode::CodeFlags::HAS_VARARGS);
compile_varargs(&args.kwarg, bytecode::CodeFlags::HAS_VARKEYWORDS);
self.enter_scope();
Ok(())
}
fn prepare_decorators(&mut self, decorator_list: &[ast::Expression]) -> CompileResult<()> {
for decorator in decorator_list {
self.compile_expression(decorator)?;
}
Ok(())
}
fn apply_decorators(&mut self, decorator_list: &[ast::Expression]) {
// Apply decorators:
for _ in decorator_list {
self.emit(Instruction::CallFunction {
typ: CallType::Positional(1),
});
}
}
fn compile_try_statement(
&mut self,
body: &[ast::Statement],
handlers: &[ast::ExceptHandler],
orelse: &Option<ast::Suite>,
finalbody: &Option<ast::Suite>,
) -> CompileResult<()> {
let mut handler_label = self.new_label();
let finally_handler_label = self.new_label();
let else_label = self.new_label();
// Setup a finally block if we have a finally statement.
if finalbody.is_some() {
self.emit(Instruction::SetupFinally {
handler: finally_handler_label,
});
}
// try:
self.emit(Instruction::SetupExcept {
handler: handler_label,
});
self.compile_statements(body)?;
self.emit(Instruction::PopBlock);
self.emit(Instruction::Jump { target: else_label });
// except handlers:
self.set_label(handler_label);
// Exception is on top of stack now
handler_label = self.new_label();
for handler in handlers {
// If we gave a typ,
// check if this handler can handle the exception:
if let Some(exc_type) = &handler.typ {
// Duplicate exception for test:
self.emit(Instruction::Duplicate);
// Check exception type:
self.compile_expression(exc_type)?;
self.emit(Instruction::CompareOperation {
op: bytecode::ComparisonOperator::ExceptionMatch,
});
// We cannot handle this exception type:
self.emit(Instruction::JumpIfFalse {
target: handler_label,
});
// We have a match, store in name (except x as y)
if let Some(alias) = &handler.name {
self.store_name(alias);
} else {
// Drop exception from top of stack:
self.emit(Instruction::Pop);
}
} else {
// Catch all!
// Drop exception from top of stack:
self.emit(Instruction::Pop);
}
// Handler code:
self.compile_statements(&handler.body)?;
self.emit(Instruction::PopException);
if finalbody.is_some() {
self.emit(Instruction::PopBlock); // pop finally block
// We enter the finally block, without exception.
self.emit(Instruction::EnterFinally);
}
self.emit(Instruction::Jump {
target: finally_handler_label,
});
// Emit a new label for the next handler
self.set_label(handler_label);
handler_label = self.new_label();
}
self.emit(Instruction::Jump {
target: handler_label,
});
self.set_label(handler_label);
// If code flows here, we have an unhandled exception,
// raise the exception again!
self.emit(Instruction::Raise { argc: 0 });
// We successfully ran the try block:
// else:
self.set_label(else_label);
if let Some(statements) = orelse {
self.compile_statements(statements)?;
}
if finalbody.is_some() {
self.emit(Instruction::PopBlock); // pop finally block
// We enter the finally block, without return / exception.
self.emit(Instruction::EnterFinally);
}
// finally:
self.set_label(finally_handler_label);
if let Some(statements) = finalbody {
self.compile_statements(statements)?;
self.emit(Instruction::EndFinally);
}
Ok(())
}
fn compile_function_def(
&mut self,
name: &str,
args: &ast::Parameters,
body: &[ast::Statement],
decorator_list: &[ast::Expression],
returns: &Option<ast::Expression>, // TODO: use type hint somehow..
is_async: bool,
) -> CompileResult<()> {
// Create bytecode for this function:
// remember to restore self.ctx.in_loop to the original after the function is compiled
let prev_ctx = self.ctx;
self.ctx = CompileContext {
in_loop: false,
func: if is_async {
FunctionContext::AsyncFunction
} else {
FunctionContext::Function
},
};
let qualified_name = self.create_qualified_name(name, "");
let old_qualified_path = self.current_qualified_path.take();
self.current_qualified_path = Some(self.create_qualified_name(name, ".<locals>"));
self.prepare_decorators(decorator_list)?;
self.enter_function(name, args)?;
let (body, doc_str) = get_doc(body);
self.compile_statements(body)?;
// Emit None at end:
match body.last().map(|s| &s.node) {
Some(ast::StatementType::Return { .. }) => {
// the last instruction is a ReturnValue already, we don't need to emit it
}
_ => {
self.emit_constant(bytecode::ConstantData::None);
self.emit(Instruction::ReturnValue);
}
}
let mut code = self.pop_code_object();
self.leave_scope();
// Prepare type annotations:
let mut num_annotations = 0;
// Return annotation:
if let Some(annotation) = returns {
// key:
self.emit_constant(bytecode::ConstantData::Str {
value: "return".to_owned(),
});
// value:
self.compile_expression(annotation)?;
num_annotations += 1;
}
let mut visit_arg_annotation = |arg: &ast::Parameter| -> CompileResult<()> {
if let Some(annotation) = &arg.annotation {
self.emit_constant(bytecode::ConstantData::Str {
value: arg.arg.to_owned(),
});
self.compile_expression(&annotation)?;
num_annotations += 1;
}
Ok(())
};
for arg in args.args.iter().chain(args.kwonlyargs.iter()) {
visit_arg_annotation(arg)?;
}
if let ast::Varargs::Named(arg) = &args.vararg {
visit_arg_annotation(arg)?;
}
if let ast::Varargs::Named(arg) = &args.kwarg {
visit_arg_annotation(arg)?;
}
if num_annotations > 0 {
code.flags |= bytecode::CodeFlags::HAS_ANNOTATIONS;
self.emit(Instruction::BuildMap {
size: num_annotations,
unpack: false,
for_call: false,
});
}
if is_async {
code.flags |= bytecode::CodeFlags::IS_COROUTINE;
}
self.emit_constant(bytecode::ConstantData::Code {
code: Box::new(code),
});
self.emit_constant(bytecode::ConstantData::Str {
value: qualified_name,
});
// Turn code object into function object:
self.emit(Instruction::MakeFunction);
self.emit(Instruction::Duplicate);
self.load_docstring(doc_str);
self.emit(Instruction::Rotate { amount: 2 });
let doc = self.name("__doc__");
self.emit(Instruction::StoreAttr { idx: doc });
self.apply_decorators(decorator_list);
self.store_name(name);
self.current_qualified_path = old_qualified_path;
self.ctx = prev_ctx;
Ok(())
}
fn find_ann(&self, body: &[ast::Statement]) -> bool {
use ast::StatementType::*;
let option_stmt_to_bool = |suit: &Option<ast::Suite>| -> bool {
match suit {
Some(stmts) => self.find_ann(stmts),
None => false,
}
};
for statement in body {
let res = match &statement.node {
AnnAssign {
target: _,
annotation: _,
value: _,
} => true,
For {
is_async: _,
target: _,
iter: _,
body,
orelse,
} => self.find_ann(body) || option_stmt_to_bool(orelse),
If {
test: _,
body,
orelse,
} => self.find_ann(body) || option_stmt_to_bool(orelse),
While {
test: _,
body,
orelse,
} => self.find_ann(body) || option_stmt_to_bool(orelse),
With {
is_async: _,
items: _,
body,
} => self.find_ann(body),
Try {
body,
handlers: _,
orelse,
finalbody,
} => {
self.find_ann(&body)
|| option_stmt_to_bool(orelse)
|| option_stmt_to_bool(finalbody)
}
_ => false,
};
if res {
return true;
}
}
false
}
fn compile_class_def(
&mut self,
name: &str,
body: &[ast::Statement],
bases: &[ast::Expression],
keywords: &[ast::Keyword],
decorator_list: &[ast::Expression],
) -> CompileResult<()> {
let prev_ctx = self.ctx;
self.ctx = CompileContext {
func: FunctionContext::NoFunction,
in_loop: false,
};
let qualified_name = self.create_qualified_name(name, "");
let old_qualified_path = self.current_qualified_path.take();
self.current_qualified_path = Some(qualified_name.clone());
self.prepare_decorators(decorator_list)?;
self.emit(Instruction::LoadBuildClass);
let line_number = self.get_source_line_number();
self.push_output(CodeObject::new(
Default::default(),
0,
0,
0,
self.source_path.clone(),
line_number,
name.to_owned(),
));
self.enter_scope();
let (new_body, doc_str) = get_doc(body);
let dunder_name = self.name("__name__");
self.emit(Instruction::LoadName {
idx: dunder_name,
scope: bytecode::NameScope::Global,
});
let dunder_module = self.name("__module__");
self.emit(Instruction::StoreName {
idx: dunder_module,
scope: bytecode::NameScope::Free,
});
self.emit_constant(bytecode::ConstantData::Str {
value: qualified_name.clone(),
});
let qualname = self.name("__qualname__");
self.emit(Instruction::StoreName {
idx: qualname,
scope: bytecode::NameScope::Free,
});
self.load_docstring(doc_str);
let doc = self.name("__doc__");
self.emit(Instruction::StoreName {
idx: doc,
scope: bytecode::NameScope::Free,
});
// setup annotations
if self.find_ann(body) {
self.emit(Instruction::SetupAnnotation);
}
self.compile_statements(new_body)?;
self.emit_constant(bytecode::ConstantData::None);
self.emit(Instruction::ReturnValue);
let mut code = self.pop_code_object();
code.flags.remove(bytecode::CodeFlags::NEW_LOCALS);
self.leave_scope();
self.emit_constant(bytecode::ConstantData::Code {
code: Box::new(code),
});
self.emit_constant(bytecode::ConstantData::Str {
value: name.to_owned(),
});
// Turn code object into function object:
self.emit(Instruction::MakeFunction);
self.emit_constant(bytecode::ConstantData::Str {
value: qualified_name,
});
for base in bases {
self.compile_expression(base)?;
}
if !keywords.is_empty() {
let mut kwarg_names = vec![];
for keyword in keywords {
if let Some(name) = &keyword.name {
kwarg_names.push(bytecode::ConstantData::Str {
value: name.to_owned(),
});
} else {
// This means **kwargs!
panic!("name must be set");
}
self.compile_expression(&keyword.value)?;
}
self.emit_constant(bytecode::ConstantData::Tuple {
elements: kwarg_names,
});
self.emit(Instruction::CallFunction {
typ: CallType::Keyword(2 + keywords.len() + bases.len()),
});
} else {
self.emit(Instruction::CallFunction {
typ: CallType::Positional(2 + bases.len()),
});
}
self.apply_decorators(decorator_list);
self.store_name(name);
self.current_qualified_path = old_qualified_path;
self.ctx = prev_ctx;
Ok(())
}
fn load_docstring(&mut self, doc_str: Option<String>) {
// TODO: __doc__ must be default None and no bytecodes unless it is Some
// Duplicate top of stack (the function or class object)
// Doc string value:
self.emit_constant(match doc_str {
Some(doc) => bytecode::ConstantData::Str { value: doc },
None => bytecode::ConstantData::None, // set docstring None if not declared
});
}
fn compile_while(
&mut self,
test: &ast::Expression,
body: &[ast::Statement],
orelse: &Option<Vec<ast::Statement>>,
) -> CompileResult<()> {
let start_label = self.new_label();
let else_label = self.new_label();
let end_label = self.new_label();
self.emit(Instruction::SetupLoop {
start: start_label,
end: end_label,
});
self.set_label(start_label);
self.compile_jump_if(test, false, else_label)?;
let was_in_loop = self.ctx.in_loop;
self.ctx.in_loop = true;
self.compile_statements(body)?;
self.ctx.in_loop = was_in_loop;
self.emit(Instruction::Jump {
target: start_label,
});
self.set_label(else_label);
self.emit(Instruction::PopBlock);
if let Some(orelse) = orelse {
self.compile_statements(orelse)?;
}
self.set_label(end_label);
Ok(())
}
fn compile_for(
&mut self,
target: &ast::Expression,
iter: &ast::Expression,
body: &[ast::Statement],
orelse: &Option<Vec<ast::Statement>>,
is_async: bool,
) -> CompileResult<()> {
// Start loop
let start_label = self.new_label();
let else_label = self.new_label();
let end_label = self.new_label();
self.emit(Instruction::SetupLoop {
start: start_label,
end: end_label,
});
// The thing iterated:
self.compile_expression(iter)?;
if is_async {
let check_asynciter_label = self.new_label();
let body_label = self.new_label();
self.emit(Instruction::GetAIter);
self.set_label(start_label);
self.emit(Instruction::SetupExcept {
handler: check_asynciter_label,
});
self.emit(Instruction::GetANext);
self.emit_constant(bytecode::ConstantData::None);
self.emit(Instruction::YieldFrom);
self.compile_store(target)?;
self.emit(Instruction::PopBlock);
self.emit(Instruction::Jump { target: body_label });
self.set_label(check_asynciter_label);
self.emit(Instruction::Duplicate);
let stopasynciter = self.name("StopAsyncIteration");
self.emit(Instruction::LoadName {
idx: stopasynciter,
scope: bytecode::NameScope::Global,
});
self.emit(Instruction::CompareOperation {
op: bytecode::ComparisonOperator::ExceptionMatch,
});
self.emit(Instruction::JumpIfTrue { target: else_label });
self.emit(Instruction::Raise { argc: 0 });
let was_in_loop = self.ctx.in_loop;
self.ctx.in_loop = true;
self.set_label(body_label);
self.compile_statements(body)?;
self.ctx.in_loop = was_in_loop;
} else {
// Retrieve Iterator
self.emit(Instruction::GetIter);
self.set_label(start_label);
self.emit(Instruction::ForIter { target: else_label });
// Start of loop iteration, set targets:
self.compile_store(target)?;
let was_in_loop = self.ctx.in_loop;
self.ctx.in_loop = true;
self.compile_statements(body)?;
self.ctx.in_loop = was_in_loop;
}
self.emit(Instruction::Jump {
target: start_label,
});
self.set_label(else_label);
self.emit(Instruction::PopBlock);
if let Some(orelse) = orelse {
self.compile_statements(orelse)?;
}
self.set_label(end_label);
if is_async {
self.emit(Instruction::Pop);
}
Ok(())
}
fn compile_chained_comparison(
&mut self,
vals: &[ast::Expression],
ops: &[ast::Comparison],
) -> CompileResult<()> {
assert!(!ops.is_empty());
assert_eq!(vals.len(), ops.len() + 1);
let to_operator = |op: &ast::Comparison| match op {
ast::Comparison::Equal => bytecode::ComparisonOperator::Equal,
ast::Comparison::NotEqual => bytecode::ComparisonOperator::NotEqual,
ast::Comparison::Less => bytecode::ComparisonOperator::Less,
ast::Comparison::LessOrEqual => bytecode::ComparisonOperator::LessOrEqual,
ast::Comparison::Greater => bytecode::ComparisonOperator::Greater,
ast::Comparison::GreaterOrEqual => bytecode::ComparisonOperator::GreaterOrEqual,
ast::Comparison::In => bytecode::ComparisonOperator::In,
ast::Comparison::NotIn => bytecode::ComparisonOperator::NotIn,
ast::Comparison::Is => bytecode::ComparisonOperator::Is,
ast::Comparison::IsNot => bytecode::ComparisonOperator::IsNot,
};
// a == b == c == d
// compile into (pseudocode):
// result = a == b
// if result:
// result = b == c
// if result:
// result = c == d
// initialize lhs outside of loop
self.compile_expression(&vals[0])?;
let break_label = self.new_label();
let last_label = self.new_label();
// for all comparisons except the last (as the last one doesn't need a conditional jump)
let ops_slice = &ops[0..ops.len()];
let vals_slice = &vals[1..ops.len()];
for (op, val) in ops_slice.iter().zip(vals_slice.iter()) {
self.compile_expression(val)?;
// store rhs for the next comparison in chain
self.emit(Instruction::Duplicate);
self.emit(Instruction::Rotate { amount: 3 });
self.emit(Instruction::CompareOperation {
op: to_operator(op),
});
// if comparison result is false, we break with this value; if true, try the next one.
self.emit(Instruction::JumpIfFalseOrPop {
target: break_label,
});
}
// handle the last comparison
self.compile_expression(vals.last().unwrap())?;
self.emit(Instruction::CompareOperation {
op: to_operator(ops.last().unwrap()),
});
if vals.len() > 2 {
self.emit(Instruction::Jump { target: last_label });
// early exit left us with stack: `rhs, comparison_result`. We need to clean up rhs.
self.set_label(break_label);
self.emit(Instruction::Rotate { amount: 2 });
self.emit(Instruction::Pop);
self.set_label(last_label);
}
Ok(())
}
fn compile_annotated_assign(
&mut self,
target: &ast::Expression,
annotation: &ast::Expression,
value: &Option<ast::Expression>,
) -> CompileResult<()> {
if let Some(value) = value {
self.compile_expression(value)?;
self.compile_store(target)?;
}
// Annotations are only evaluated in a module or class.
if self.ctx.in_func() {
return Ok(());
}
// Compile annotation:
self.compile_expression(annotation)?;
if let ast::ExpressionType::Identifier { name } = &target.node {
// Store as dict entry in __annotations__ dict:
let annotations = self.name("__annotations__");
self.emit(Instruction::LoadName {
idx: annotations,
scope: bytecode::NameScope::Local,
});
self.emit_constant(bytecode::ConstantData::Str {
value: name.to_owned(),
});
self.emit(Instruction::StoreSubscript);
} else {
// Drop annotation if not assigned to simple identifier.
self.emit(Instruction::Pop);
}
Ok(())
}
fn compile_store(&mut self, target: &ast::Expression) -> CompileResult<()> {
match &target.node {
ast::ExpressionType::Identifier { name } => {
self.store_name(name);
}
ast::ExpressionType::Subscript { a, b } => {
self.compile_expression(a)?;
self.compile_expression(b)?;
self.emit(Instruction::StoreSubscript);
}
ast::ExpressionType::Attribute { value, name } => {
self.compile_expression(value)?;
let idx = self.name(name);
self.emit(Instruction::StoreAttr { idx });
}
ast::ExpressionType::List { elements } | ast::ExpressionType::Tuple { elements } => {
let mut seen_star = false;
// Scan for star args:
for (i, element) in elements.iter().enumerate() {
if let ast::ExpressionType::Starred { .. } = &element.node {
if seen_star {
return Err(self.error(CompileErrorType::MultipleStarArgs));
} else {
seen_star = true;
self.emit(Instruction::UnpackEx {
before: i,
after: elements.len() - i - 1,
});
}
}
}
if !seen_star {
self.emit(Instruction::UnpackSequence {
size: elements.len(),
});
}
for element in elements {
if let ast::ExpressionType::Starred { value } = &element.node {
self.compile_store(value)?;
} else {
self.compile_store(element)?;
}
}
}
_ => {
return Err(self.error(match target.node {
ast::ExpressionType::Starred { .. } => CompileErrorType::SyntaxError(
"starred assignment target must be in a list or tuple".to_owned(),
),
_ => CompileErrorType::Assign(target.name()),
}))
}
}
Ok(())
}
fn compile_op(&mut self, op: &ast::Operator, inplace: bool) {
let i = match op {
ast::Operator::Add => bytecode::BinaryOperator::Add,
ast::Operator::Sub => bytecode::BinaryOperator::Subtract,
ast::Operator::Mult => bytecode::BinaryOperator::Multiply,
ast::Operator::MatMult => bytecode::BinaryOperator::MatrixMultiply,
ast::Operator::Div => bytecode::BinaryOperator::Divide,
ast::Operator::FloorDiv => bytecode::BinaryOperator::FloorDivide,
ast::Operator::Mod => bytecode::BinaryOperator::Modulo,
ast::Operator::Pow => bytecode::BinaryOperator::Power,
ast::Operator::LShift => bytecode::BinaryOperator::Lshift,
ast::Operator::RShift => bytecode::BinaryOperator::Rshift,
ast::Operator::BitOr => bytecode::BinaryOperator::Or,
ast::Operator::BitXor => bytecode::BinaryOperator::Xor,
ast::Operator::BitAnd => bytecode::BinaryOperator::And,
};
self.emit(Instruction::BinaryOperation { op: i, inplace });
}
/// Implement boolean short circuit evaluation logic.
/// https://en.wikipedia.org/wiki/Short-circuit_evaluation
///
/// This means, in a boolean statement 'x and y' the variable y will
/// not be evaluated when x is false.
///
/// The idea is to jump to a label if the expression is either true or false
/// (indicated by the condition parameter).
fn compile_jump_if(
&mut self,
expression: &ast::Expression,
condition: bool,
target_label: Label,
) -> CompileResult<()> {
// Compile expression for test, and jump to label if false
match &expression.node {
ast::ExpressionType::BoolOp { op, values } => {
match op {
ast::BooleanOperator::And => {
if condition {
// If all values are true.
let end_label = self.new_label();
let (last_value, values) = values.split_last().unwrap();
// If any of the values is false, we can short-circuit.
for value in values {
self.compile_jump_if(value, false, end_label)?;
}
// It depends upon the last value now: will it be true?
self.compile_jump_if(last_value, true, target_label)?;
self.set_label(end_label);
} else {
// If any value is false, the whole condition is false.
for value in values {
self.compile_jump_if(value, false, target_label)?;
}
}
}
ast::BooleanOperator::Or => {
if condition {
// If any of the values is true.
for value in values {
self.compile_jump_if(value, true, target_label)?;
}
} else {
// If all of the values are false.
let end_label = self.new_label();
let (last_value, values) = values.split_last().unwrap();
// If any value is true, we can short-circuit:
for value in values {
self.compile_jump_if(value, true, end_label)?;
}
// It all depends upon the last value now!
self.compile_jump_if(last_value, false, target_label)?;
self.set_label(end_label);
}
}
}
}
ast::ExpressionType::Unop {
op: ast::UnaryOperator::Not,
a,
} => {
self.compile_jump_if(a, !condition, target_label)?;
}
_ => {
// Fall back case which always will work!
self.compile_expression(expression)?;
if condition {
self.emit(Instruction::JumpIfTrue {
target: target_label,
});
} else {
self.emit(Instruction::JumpIfFalse {
target: target_label,
});
}
}
}
Ok(())
}
/// Compile a boolean operation as an expression.
/// This means, that the last value remains on the stack.
fn compile_bool_op(
&mut self,
op: &ast::BooleanOperator,
values: &[ast::Expression],
) -> CompileResult<()> {
let end_label = self.new_label();
let (last_value, values) = values.split_last().unwrap();
for value in values {
self.compile_expression(value)?;
match op {
ast::BooleanOperator::And => {
self.emit(Instruction::JumpIfFalseOrPop { target: end_label });
}
ast::BooleanOperator::Or => {
self.emit(Instruction::JumpIfTrueOrPop { target: end_label });
}
}
}
// If all values did not qualify, take the value of the last value:
self.compile_expression(last_value)?;
self.set_label(end_label);
Ok(())
}
fn compile_dict(
&mut self,
pairs: &[(Option<ast::Expression>, ast::Expression)],
) -> CompileResult<()> {
let mut size = 0;
let mut has_unpacking = false;
for (is_unpacking, subpairs) in &pairs.iter().group_by(|e| e.0.is_none()) {
if is_unpacking {
for (_, value) in subpairs {
self.compile_expression(value)?;
size += 1;
}
has_unpacking = true;
} else {
let mut subsize = 0;
for (key, value) in subpairs {
if let Some(key) = key {
self.compile_expression(key)?;
self.compile_expression(value)?;
subsize += 1;
}
}
self.emit(Instruction::BuildMap {
size: subsize,
unpack: false,
for_call: false,
});
size += 1;
}
}
if size == 0 {
self.emit(Instruction::BuildMap {
size,
unpack: false,
for_call: false,
});
}
if size > 1 || has_unpacking {
self.emit(Instruction::BuildMap {
size,
unpack: true,
for_call: false,
});
}
Ok(())
}
fn compile_expression(&mut self, expression: &ast::Expression) -> CompileResult<()> {
trace!("Compiling {:?}", expression);
self.set_source_location(expression.location);
use ast::ExpressionType::*;
match &expression.node {
Call {
function,
args,
keywords,
} => self.compile_call(function, args, keywords)?,
BoolOp { op, values } => self.compile_bool_op(op, values)?,
Binop { a, op, b } => {
self.compile_expression(a)?;
self.compile_expression(b)?;
// Perform operation:
self.compile_op(op, false);
}
Subscript { a, b } => {
self.compile_expression(a)?;
self.compile_expression(b)?;
self.emit(Instruction::Subscript);
}
Unop { op, a } => {
self.compile_expression(a)?;
// Perform operation:
let i = match op {
ast::UnaryOperator::Pos => bytecode::UnaryOperator::Plus,
ast::UnaryOperator::Neg => bytecode::UnaryOperator::Minus,
ast::UnaryOperator::Not => bytecode::UnaryOperator::Not,
ast::UnaryOperator::Inv => bytecode::UnaryOperator::Invert,
};
let i = Instruction::UnaryOperation { op: i };
self.emit(i);
}
Attribute { value, name } => {
self.compile_expression(value)?;
let idx = self.name(name);
self.emit(Instruction::LoadAttr { idx });
}
Compare { vals, ops } => {
self.compile_chained_comparison(vals, ops)?;
}
Number { value } => {
let const_value = match value {
ast::Number::Integer { value } => bytecode::ConstantData::Integer {
value: value.clone(),
},
ast::Number::Float { value } => bytecode::ConstantData::Float { value: *value },
ast::Number::Complex { real, imag } => bytecode::ConstantData::Complex {
value: Complex64::new(*real, *imag),
},
};
self.emit_constant(const_value);
}
List { elements } => {
let size = elements.len();
let must_unpack = self.gather_elements(elements)?;
self.emit(Instruction::BuildList {
size,
unpack: must_unpack,
});
}
Tuple { elements } => {
let size = elements.len();
let must_unpack = self.gather_elements(elements)?;
self.emit(Instruction::BuildTuple {
size,
unpack: must_unpack,
});
}
Set { elements } => {
let size = elements.len();
let must_unpack = self.gather_elements(elements)?;
self.emit(Instruction::BuildSet {
size,
unpack: must_unpack,
});
}
Dict { elements } => {
self.compile_dict(elements)?;
}
Slice { elements } => {
let size = elements.len();
for element in elements {
self.compile_expression(element)?;
}
self.emit(Instruction::BuildSlice { size });
}
Yield { value } => {
if !self.ctx.in_func() {
return Err(self.error(CompileErrorType::InvalidYield));
}
self.mark_generator();
match value {
Some(expression) => self.compile_expression(expression)?,
Option::None => self.emit_constant(bytecode::ConstantData::None),
};
self.emit(Instruction::YieldValue);
}
Await { value } => {
if self.ctx.func != FunctionContext::AsyncFunction {
return Err(self.error(CompileErrorType::InvalidAwait));
}
self.compile_expression(value)?;
self.emit(Instruction::GetAwaitable);
self.emit_constant(bytecode::ConstantData::None);
self.emit(Instruction::YieldFrom);
}
YieldFrom { value } => {
match self.ctx.func {
FunctionContext::NoFunction => {
return Err(self.error(CompileErrorType::InvalidYieldFrom))
}
FunctionContext::AsyncFunction => {
return Err(self.error(CompileErrorType::AsyncYieldFrom))
}
FunctionContext::Function => {}
}
self.mark_generator();
self.compile_expression(value)?;
self.emit(Instruction::GetIter);
self.emit_constant(bytecode::ConstantData::None);
self.emit(Instruction::YieldFrom);
}
True => {
self.emit_constant(bytecode::ConstantData::Boolean { value: true });
}
False => {
self.emit_constant(bytecode::ConstantData::Boolean { value: false });
}
ast::ExpressionType::None => {
self.emit_constant(bytecode::ConstantData::None);
}
Ellipsis => {
self.emit_constant(bytecode::ConstantData::Ellipsis);
}
ast::ExpressionType::String { value } => {
self.compile_string(value)?;
}
Bytes { value } => {
self.emit_constant(bytecode::ConstantData::Bytes {
value: value.clone(),
});
}
Identifier { name } => {
self.load_name(name);
}
Lambda { args, body } => {
let prev_ctx = self.ctx;
self.ctx = CompileContext {
in_loop: false,
func: FunctionContext::Function,
};
let name = "<lambda>".to_owned();
self.enter_function(&name, args)?;
self.compile_expression(body)?;
self.emit(Instruction::ReturnValue);
let code = self.pop_code_object();
self.leave_scope();
self.emit_constant(bytecode::ConstantData::Code {
code: Box::new(code),
});
self.emit_constant(bytecode::ConstantData::Str { value: name });
// Turn code object into function object:
self.emit(Instruction::MakeFunction);
self.ctx = prev_ctx;
}
Comprehension { kind, generators } => {
self.compile_comprehension(kind, generators)?;
}
Starred { .. } => {
return Err(self.error(CompileErrorType::InvalidStarExpr));
}
IfExpression { test, body, orelse } => {
let no_label = self.new_label();
let end_label = self.new_label();
self.compile_jump_if(test, false, no_label)?;
// True case
self.compile_expression(body)?;
self.emit(Instruction::Jump { target: end_label });
// False case
self.set_label(no_label);
self.compile_expression(orelse)?;
// End
self.set_label(end_label);
}
NamedExpression { left, right } => {
self.compile_expression(right)?;
self.emit(Instruction::Duplicate);
self.compile_store(left)?;
}
}
Ok(())
}
fn compile_keywords(&mut self, keywords: &[ast::Keyword]) -> CompileResult<()> {
let mut size = 0;
for (is_unpacking, subkeywords) in &keywords.iter().group_by(|e| e.name.is_none()) {
if is_unpacking {
for keyword in subkeywords {
self.compile_expression(&keyword.value)?;
size += 1;
}
} else {
let mut subsize = 0;
for keyword in subkeywords {
if let Some(name) = &keyword.name {
self.emit_constant(bytecode::ConstantData::Str {
value: name.to_owned(),
});
self.compile_expression(&keyword.value)?;
subsize += 1;
}
}
self.emit(Instruction::BuildMap {
size: subsize,
unpack: false,
for_call: false,
});
size += 1;
}
}
if size > 1 {
self.emit(Instruction::BuildMap {
size,
unpack: true,
for_call: true,
});
}
Ok(())
}
fn compile_call(
&mut self,
function: &ast::Expression,
args: &[ast::Expression],
keywords: &[ast::Keyword],
) -> CompileResult<()> {
self.compile_expression(function)?;
let count = args.len() + keywords.len();
// Normal arguments:
let must_unpack = self.gather_elements(args)?;
let has_double_star = keywords.iter().any(|k| k.name.is_none());
if must_unpack || has_double_star {
// Create a tuple with positional args:
self.emit(Instruction::BuildTuple {
size: args.len(),
unpack: must_unpack,
});
// Create an optional map with kw-args:
if !keywords.is_empty() {
self.compile_keywords(keywords)?;
self.emit(Instruction::CallFunction {
typ: CallType::Ex(true),
});
} else {
self.emit(Instruction::CallFunction {
typ: CallType::Ex(false),
});
}
} else {
// Keyword arguments:
if !keywords.is_empty() {
let mut kwarg_names = vec![];
for keyword in keywords {
if let Some(name) = &keyword.name {
kwarg_names.push(bytecode::ConstantData::Str {
value: name.to_owned(),
});
} else {
// This means **kwargs!
panic!("name must be set");
}
self.compile_expression(&keyword.value)?;
}
self.emit_constant(bytecode::ConstantData::Tuple {
elements: kwarg_names,
});
self.emit(Instruction::CallFunction {
typ: CallType::Keyword(count),
});
} else {
self.emit(Instruction::CallFunction {
typ: CallType::Positional(count),
});
}
}
Ok(())
}
// Given a vector of expr / star expr generate code which gives either
// a list of expressions on the stack, or a list of tuples.
fn gather_elements(&mut self, elements: &[ast::Expression]) -> CompileResult<bool> {
// First determine if we have starred elements:
let has_stars = elements
.iter()
.any(|e| matches!(e.node, ast::ExpressionType::Starred { .. }));
for element in elements {
if let ast::ExpressionType::Starred { value } = &element.node {
self.compile_expression(value)?;
} else {
self.compile_expression(element)?;
if has_stars {
self.emit(Instruction::BuildTuple {
size: 1,
unpack: false,
});
}
}
}
Ok(has_stars)
}
fn compile_comprehension(
&mut self,
kind: &ast::ComprehensionKind,
generators: &[ast::Comprehension],
) -> CompileResult<()> {
// We must have at least one generator:
assert!(!generators.is_empty());
let name = match kind {
ast::ComprehensionKind::GeneratorExpression { .. } => "<genexpr>",
ast::ComprehensionKind::List { .. } => "<listcomp>",
ast::ComprehensionKind::Set { .. } => "<setcomp>",
ast::ComprehensionKind::Dict { .. } => "<dictcomp>",
}
.to_owned();
let line_number = self.get_source_line_number();
// Create magnificent function <listcomp>:
self.push_output(CodeObject::new(
Default::default(),
1,
1,
0,
self.source_path.clone(),
line_number,
name.clone(),
));
let arg0 = self.name(".0");
self.enter_scope();
// Create empty object of proper type:
match kind {
ast::ComprehensionKind::GeneratorExpression { .. } => {}
ast::ComprehensionKind::List { .. } => {
self.emit(Instruction::BuildList {
size: 0,
unpack: false,
});
}
ast::ComprehensionKind::Set { .. } => {
self.emit(Instruction::BuildSet {
size: 0,
unpack: false,
});
}
ast::ComprehensionKind::Dict { .. } => {
self.emit(Instruction::BuildMap {
size: 0,
unpack: false,
for_call: false,
});
}
}
let mut loop_labels = vec![];
for generator in generators {
if generator.is_async {
unimplemented!("async for comprehensions");
}
if loop_labels.is_empty() {
// Load iterator onto stack (passed as first argument):
self.emit(Instruction::LoadName {
idx: arg0,
scope: bytecode::NameScope::Local,
});
} else {
// Evaluate iterated item:
self.compile_expression(&generator.iter)?;
// Get iterator / turn item into an iterator
self.emit(Instruction::GetIter);
}
// Setup for loop:
let start_label = self.new_label();
let end_label = self.new_label();
loop_labels.push((start_label, end_label));
self.emit(Instruction::SetupLoop {
start: start_label,
end: end_label,
});
self.set_label(start_label);
self.emit(Instruction::ForIter { target: end_label });
self.compile_store(&generator.target)?;
// Now evaluate the ifs:
for if_condition in &generator.ifs {
self.compile_jump_if(if_condition, false, start_label)?
}
}
let mut compile_element = |element| {
self.compile_expression(element).map_err(|e| {
if let CompileErrorType::InvalidStarExpr = e.error {
self.error(CompileErrorType::SyntaxError(
"iterable unpacking cannot be used in comprehension".to_owned(),
))
} else {
e
}
})
};
match kind {
ast::ComprehensionKind::GeneratorExpression { element } => {
compile_element(element)?;
self.mark_generator();
self.emit(Instruction::YieldValue);
self.emit(Instruction::Pop);
}
ast::ComprehensionKind::List { element } => {
compile_element(element)?;
self.emit(Instruction::ListAppend {
i: 1 + generators.len(),
});
}
ast::ComprehensionKind::Set { element } => {
compile_element(element)?;
self.emit(Instruction::SetAdd {
i: 1 + generators.len(),
});
}
ast::ComprehensionKind::Dict { key, value } => {
// changed evaluation order for Py38 named expression PEP 572
self.compile_expression(key)?;
self.compile_expression(value)?;
self.emit(Instruction::MapAddRev {
i: 1 + generators.len(),
});
}
}
for (start_label, end_label) in loop_labels.iter().rev() {
// Repeat:
self.emit(Instruction::Jump {
target: *start_label,
});
// End of for loop:
self.set_label(*end_label);
self.emit(Instruction::PopBlock);
}
// Return freshly filled list:
self.emit(Instruction::ReturnValue);
// Fetch code for listcomp function:
let code = self.pop_code_object();
// Pop scope
self.leave_scope();
// List comprehension code:
self.emit_constant(bytecode::ConstantData::Code {
code: Box::new(code),
});
// List comprehension function name:
self.emit_constant(bytecode::ConstantData::Str { value: name });
// Turn code object into function object:
self.emit(Instruction::MakeFunction);
// Evaluate iterated item:
self.compile_expression(&generators[0].iter)?;
// Get iterator / turn item into an iterator
self.emit(Instruction::GetIter);
// Call just created <listcomp> function:
self.emit(Instruction::CallFunction {
typ: CallType::Positional(1),
});
Ok(())
}
fn compile_string(&mut self, string: &ast::StringGroup) -> CompileResult<()> {
if let Some(value) = try_get_constant_string(string) {
self.emit_constant(bytecode::ConstantData::Str { value });
} else {
match string {
ast::StringGroup::Joined { values } => {
for value in values {
self.compile_string(value)?;
}
self.emit(Instruction::BuildString { size: values.len() })
}
ast::StringGroup::Constant { value } => {
self.emit_constant(bytecode::ConstantData::Str {
value: value.to_owned(),
});
}
ast::StringGroup::FormattedValue {
value,
conversion,
spec,
} => {
match spec {
Some(spec) => self.compile_string(spec)?,
None => self.emit_constant(bytecode::ConstantData::Str {
value: String::new(),
}),
};
self.compile_expression(value)?;
self.emit(Instruction::FormatValue {
conversion: conversion.map(compile_conversion_flag),
});
}
}
}
Ok(())
}
fn compile_future_features(
&mut self,
features: &[ast::ImportSymbol],
) -> Result<(), CompileError> {
if self.done_with_future_stmts {
return Err(self.error(CompileErrorType::InvalidFuturePlacement));
}
for feature in features {
match &*feature.symbol {
// Python 3 features; we've already implemented them by default
"nested_scopes" | "generators" | "division" | "absolute_import"
| "with_statement" | "print_function" | "unicode_literals" => {}
// "generator_stop" => {}
// "annotations" => {}
other => {
return Err(self.error(CompileErrorType::InvalidFutureFeature(other.to_owned())))
}
}
}
Ok(())
}
// Scope helpers:
fn enter_scope(&mut self) {
// println!("Enter scope {:?}", self.symbol_table_stack);
// Enter first subscope!
let table = self
.symbol_table_stack
.last_mut()
.unwrap()
.sub_tables
.remove(0);
self.symbol_table_stack.push(table);
}
fn leave_scope(&mut self) {
// println!("Leave scope {:?}", self.symbol_table_stack);
let table = self.symbol_table_stack.pop().unwrap();
assert!(table.sub_tables.is_empty());
}
fn lookup_name(&self, name: &str) -> &Symbol {
// println!("Looking up {:?}", name);
let symbol_table = self.symbol_table_stack.last().unwrap();
symbol_table.lookup(name).expect(
"The symbol must be present in the symbol table, even when it is undefined in python.",
)
}
// Low level helper functions:
fn emit(&mut self, instruction: Instruction) {
let location = compile_location(&self.current_source_location);
// TODO: insert source filename
let code = self.current_code();
code.instructions.push(instruction);
code.locations.push(location);
}
fn emit_constant(&mut self, constant: bytecode::ConstantData) {
let code = self.current_code();
let idx = code.constants.len();
code.constants.push(constant);
self.emit(Instruction::LoadConst { idx })
}
fn current_code(&mut self) -> &mut CodeObject {
&mut self
.output_stack
.last_mut()
.expect("No OutputStream on stack")
.0
}
// Generate a new label
fn new_label(&mut self) -> Label {
let l = Label::new(self.nxt_label);
self.nxt_label += 1;
l
}
// Assign current position the given label
fn set_label(&mut self, label: Label) {
let code = self.current_code();
let pos = code.instructions.len();
code.label_map.insert(label, pos);
}
fn set_source_location(&mut self, location: ast::Location) {
self.current_source_location = location;
}
fn get_source_line_number(&mut self) -> usize {
self.current_source_location.row()
}
fn create_qualified_name(&self, name: &str, suffix: &str) -> String {
if let Some(ref qualified_path) = self.current_qualified_path {
format!("{}.{}{}", qualified_path, name, suffix)
} else {
format!("{}{}", name, suffix)
}
}
fn mark_generator(&mut self) {
self.current_code().flags |= bytecode::CodeFlags::IS_GENERATOR
}
}
fn get_doc(body: &[ast::Statement]) -> (&[ast::Statement], Option<String>) {
if let Some((val, body_rest)) = body.split_first() {
if let ast::StatementType::Expression { ref expression } = val.node {
if let ast::ExpressionType::String { value } = &expression.node {
if let Some(value) = try_get_constant_string(value) {
return (body_rest, Some(value));
}
}
}
}
(body, None)
}
fn try_get_constant_string(string: &ast::StringGroup) -> Option<String> {
fn get_constant_string_inner(out_string: &mut String, string: &ast::StringGroup) -> bool {
match string {
ast::StringGroup::Constant { value } => {
out_string.push_str(&value);
true
}
ast::StringGroup::Joined { values } => values
.iter()
.all(|value| get_constant_string_inner(out_string, value)),
ast::StringGroup::FormattedValue { .. } => false,
}
}
let mut out_string = String::new();
if get_constant_string_inner(&mut out_string, string) {
Some(out_string)
} else {
None
}
}
fn compile_location(location: &ast::Location) -> bytecode::Location {
bytecode::Location::new(location.row(), location.column())
}
fn compile_conversion_flag(conversion_flag: ast::ConversionFlag) -> bytecode::ConversionFlag {
match conversion_flag {
ast::ConversionFlag::Ascii => bytecode::ConversionFlag::Ascii,
ast::ConversionFlag::Repr => bytecode::ConversionFlag::Repr,
ast::ConversionFlag::Str => bytecode::ConversionFlag::Str,
}
}
#[cfg(test)]
mod tests {
use super::{CompileOpts, Compiler};
use crate::symboltable::make_symbol_table;
use rustpython_bytecode::bytecode::CodeObject;
use rustpython_parser::parser;
fn compile_exec(source: &str) -> CodeObject {
let mut compiler: Compiler =
Compiler::new(CompileOpts::default(), "source_path".to_owned());
compiler.push_new_code_object("<module>".to_owned());
let ast = parser::parse_program(source).unwrap();
let symbol_scope = make_symbol_table(&ast).unwrap();
compiler.compile_program(&ast, symbol_scope).unwrap();
compiler.pop_code_object()
}
macro_rules! assert_dis_snapshot {
($value:expr) => {
insta::assert_snapshot!(
insta::internals::AutoName,
$value.display_expand_codeobjects().to_string(),
stringify!($value)
)
};
}
#[test]
fn test_if_ors() {
assert_dis_snapshot!(compile_exec(
"\
if True or False or False:
pass
"
));
}
#[test]
fn test_if_ands() {
assert_dis_snapshot!(compile_exec(
"\
if True and False and False:
pass
"
));
}
#[test]
fn test_if_mixed() {
assert_dis_snapshot!(compile_exec(
"\
if (True and False) or (False and True):
pass
"
));
}
}
| 34.978643 | 105 | 0.492248 |
b95e5c77005c316a9db795c1bb4459ff3816520c | 2,911 | //! Inputs are the actual contents sent to a target for each exeuction.
pub mod bytes;
pub use bytes::BytesInput;
pub mod encoded;
pub use encoded::*;
pub mod gramatron;
pub use gramatron::*;
pub mod generalized;
pub use generalized::*;
#[cfg(feature = "nautilus")]
pub mod nautilus;
#[cfg(feature = "nautilus")]
pub use nautilus::*;
use alloc::{
string::{String, ToString},
vec::Vec,
};
use core::{clone::Clone, fmt::Debug};
use serde::{Deserialize, Serialize};
#[cfg(feature = "std")]
use std::{fs::File, io::Read, path::Path};
#[cfg(feature = "std")]
use crate::bolts::fs::write_file_atomic;
use crate::{bolts::ownedref::OwnedSlice, Error};
/// An input for the target
pub trait Input: Clone + Serialize + serde::de::DeserializeOwned + Debug {
#[cfg(feature = "std")]
/// Write this input to the file
fn to_file<P>(&self, path: P) -> Result<(), Error>
where
P: AsRef<Path>,
{
write_file_atomic(path, &postcard::to_allocvec(self)?)
}
#[cfg(not(feature = "std"))]
/// Write this input to the file
fn to_file<P>(&self, _path: P) -> Result<(), Error> {
Err(Error::NotImplemented("Not supported in no_std".into()))
}
/// Load the contents of this input from a file
#[cfg(feature = "std")]
fn from_file<P>(path: P) -> Result<Self, Error>
where
P: AsRef<Path>,
{
let mut file = File::open(path)?;
let mut bytes: Vec<u8> = vec![];
file.read_to_end(&mut bytes)?;
Ok(postcard::from_bytes(&bytes)?)
}
/// Write this input to the file
#[cfg(not(feature = "std"))]
fn from_file<P>(_path: P) -> Result<Self, Error> {
Err(Error::NotImplemented("Not supprted in no_std".into()))
}
/// Generate a name for this input
fn generate_name(&self, idx: usize) -> String;
/// An hook executed if the input is stored as `Testcase`
fn wrapped_as_testcase(&mut self) {}
}
/// An input for tests, mainly. There is no real use much else.
#[derive(Copy, Clone, Serialize, Deserialize, Debug)]
pub struct NopInput {}
impl Input for NopInput {
fn generate_name(&self, _idx: usize) -> String {
"nop-input".to_string()
}
}
impl HasTargetBytes for NopInput {
fn target_bytes(&self) -> OwnedSlice<u8> {
OwnedSlice::from(vec![0])
}
}
// TODO change this to fn target_bytes(&self, buffer: &mut Vec<u8>) -> &[u8];
/// Can be represented with a vector of bytes
/// This representation is not necessarily deserializable
/// Instead, it can be used as bytes input for a target
pub trait HasTargetBytes {
/// Target bytes, that can be written to a target
fn target_bytes(&self) -> OwnedSlice<u8>;
}
/// Contains an internal bytes Vector
pub trait HasBytesVec {
/// The internal bytes map
fn bytes(&self) -> &[u8];
/// The internal bytes map (as mutable borrow)
fn bytes_mut(&mut self) -> &mut Vec<u8>;
}
| 27.72381 | 77 | 0.632772 |
330525ee6bdbe1e64d3cb59c4a25e0d87afd2b6c | 114,461 | use fnv::{FnvHashMap};
use owning_ref::{OwningHandle};
use self::stock_syms::*;
use smallvec::{SmallVec};
use std::{fmt, fs, str, u32};
use std::any::{Any, TypeId, type_name};
use std::cell::{Cell, Ref, RefCell, RefMut};
use std::collections::{HashMap, hash_map::Entry::{Occupied, Vacant}, HashSet};
use std::convert::{TryFrom};
use std::fmt::{Debug, Display, Formatter, Pointer};
use std::io::{self, stderr, stdout, Write};
use std::iter::{FromIterator};
use std::marker::{PhantomData};
use std::num::{NonZeroU32};
use std::ops::{Deref, DerefMut};
use std::panic::{self, AssertUnwindSafe};
use std::path::{PathBuf};
use std::rc::{Rc};
use std::time::{SystemTime, UNIX_EPOCH};
use super::{eval, lex};
use super::class::{Class, Obj};
use super::code::{Coro, GFn};
use super::collections::{Arr, DequeAccess, DequeOps, IntoElement, Str, Tab};
use super::error::{GResult};
use super::eval::{Env, EnvMode, Expander, Expansion};
use super::gc::{Allocate, Heap, Gc, GcHeader, Slot, Root, Visitor};
use super::iter::{GcCallable, GIter, GIterState, Iterable, IterableOps};
use super::parse::{Parser};
use super::transform::{KnownOp, known_ops};
use super::val::{Num, Val};
use super::vm::{Frame, GlspApiName, Vm};
use super::wrap::{FromVal, ToCallArgs, Callable, CallableOps, ToVal, WrappedFn};
#[cfg(feature = "compiler")]
use std::mem::forget;
#[cfg(feature = "compiler")]
use super::{code::Stay, compile::{Action, Recording}};
//-------------------------------------------------------------------------------------------------
// ACTIVE_ENGINE
//-------------------------------------------------------------------------------------------------
thread_local! {
static ACTIVE_ENGINE: RefCell<Option<Rc<EngineStorage>>> = RefCell::new(None);
pub(crate) static ACTIVE_ENGINE_ID: Cell<Option<u8>> = Cell::new(None);
//a bitset used for assigning engine ids. one bit for each possible id; the bit is set if an
//engine is currently using that id. it's an error for more than 256 engines to coexist
//within a single thread.
static ID_BITSET: [Cell<u32>; 8] = [
Cell::new(0), Cell::new(0), Cell::new(0), Cell::new(0),
Cell::new(0), Cell::new(0), Cell::new(0), Cell::new(0)
];
}
fn alloc_engine_id() -> Option<u8> {
ID_BITSET.with(|bitset| {
for i in 0 .. 8 {
let mut bits = bitset[i].get();
let mut j = 0;
if bits != 0xffffffff {
while bits & 0x1 == 0x1 {
bits >>= 1;
j += 1;
}
assert!(j <= 31 && i*32 + j <= 255);
bitset[i].set(bitset[i].get() | (1 << j));
return Some((i*32 + j) as u8)
}
}
None
})
}
fn free_engine_id(id: u8) {
ID_BITSET.with(|bitset| {
let i = id as usize / 32;
let j = id as u32 % 32;
assert!(bitset[i].get() & (0x1 << j) != 0);
bitset[i].set(bitset[i].get() & !(0x1 << j));
})
}
#[inline(always)]
fn with_engine<R, F: FnOnce(&EngineStorage) -> R>(f: F) -> R {
ACTIVE_ENGINE.with(|ref_cell| {
let borrow = ref_cell.borrow();
let rc = borrow.as_ref().unwrap();
f(&rc)
})
}
#[inline(always)]
pub(crate) fn with_heap<R, F: FnOnce(&Heap) -> R>(f: F) -> R {
ACTIVE_ENGINE.with(|ref_cell| {
let opt_rc = ref_cell.borrow();
match &*opt_rc {
Some(rc) => f(&rc.heap),
None => panic!("called with_heap when no glsp engine is active")
}
})
}
#[inline(always)]
pub(crate) fn with_vm<R, F: FnOnce(&Vm) -> R>(f: F) -> R {
ACTIVE_ENGINE.with(|ref_cell| {
let opt_rc = ref_cell.borrow();
match &*opt_rc {
Some(rc) => f(&rc.vm),
None => panic!("called with_vm when no glsp engine is active")
}
})
}
#[inline(always)]
pub(crate) fn with_known_ops<R, F: FnOnce(&HashMap<Sym, KnownOp>) -> R>(f: F) -> R {
ACTIVE_ENGINE.with(|ref_cell| {
let opt_rc = ref_cell.borrow();
match &*opt_rc {
Some(rc) => f(&rc.known_ops),
None => panic!("called with_known_ops when no glsp engine is active")
}
})
}
#[doc(hidden)]
pub fn with_lazy_val<R, FInit, FUse>(key: &str, f_init: FInit, f_use: FUse) -> R
where
FInit: FnOnce() -> Val,
FUse: FnOnce(&Val) -> R
{
//we access the HashMap twice, rather than using the Entry api, because we don't want the
//lazy_storage to be borrowed while f_init or f_use are executing - it's possible that
//they might recursively call something which, in turn, calls glsp::with_lazy_val.
//(for example, this could definitely occur with the eval!() macro.)
let val = with_engine(|engine| {
engine.lazy_storage.borrow().get(key).cloned()
});
if let Some(val) = val {
f_use(&val)
} else {
let new_val = f_init();
with_engine(|engine| {
engine.lazy_storage.borrow_mut().insert(key.to_string(), new_val.clone());
});
f_use(&new_val)
}
}
//-------------------------------------------------------------------------------------------------
// pr!(), prn!(), epr!(), eprn!()
//-------------------------------------------------------------------------------------------------
//we can't have the macros call rt::with_pr_writer directly, because their arguments might use
//the ? operator. we use PrWriter and EprWriter as (slightly inefficient) adapters instead.
#[doc(hidden)]
pub struct PrWriter;
impl Write for PrWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
with_engine(|engine| engine.pr_writer.borrow_mut().write(buf))
}
fn flush(&mut self) -> io::Result<()> {
with_engine(|engine| engine.pr_writer.borrow_mut().flush())
}
}
#[doc(hidden)]
pub struct EprWriter;
impl Write for EprWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
with_engine(|engine| engine.epr_writer.borrow_mut().write(buf))
}
fn flush(&mut self) -> io::Result<()> {
with_engine(|engine| engine.epr_writer.borrow_mut().flush())
}
}
/**
Prints to the active [`Runtime`](struct.Runtime.html)'s current
[`pr_writer`](fn.set_pr_writer.html).
The input syntax is identical to [`print!`](https://doc.rust-lang.org/std/macro.print.html).
The `pr_writer` defaults to [`Stdout`](https://doc.rust-lang.org/std/io/struct.Stdout.html).
*/
#[macro_export]
macro_rules! pr {
($($arg:tt)*) => (
{
use std::io::Write;
write!($crate::PrWriter, $($arg)*).ok();
$crate::PrWriter.flush().ok();
}
);
}
/**
Prints to the active [`Runtime`](struct.Runtime.html)'s current
[`pr_writer`](fn.set_pr_writer.html), with a trailing `'\n'`.
The input syntax is identical to [`println!`](https://doc.rust-lang.org/std/macro.println.html).
The `pr_writer` defaults to [`Stdout`](https://doc.rust-lang.org/std/io/struct.Stdout.html).
*/
#[macro_export]
macro_rules! prn {
($($arg:tt)*) => (
{
use std::io::Write;
writeln!($crate::PrWriter, $($arg)*).ok();
}
);
}
/**
Prints to the active [`Runtime`](struct.Runtime.html)'s current
[`epr_writer`](fn.set_epr_writer.html).
The input syntax is identical to [`eprint!`](https://doc.rust-lang.org/std/macro.eprint.html).
The `epr_writer` defaults to [`Stderr`](https://doc.rust-lang.org/std/io/struct.Stderr.html).
*/
#[macro_export]
macro_rules! epr {
($($arg:tt)*) => (
{
use std::io::Write;
write!($crate::EprWriter, $($arg)*).ok();
$crate::EprWriter.flush().ok();
}
);
}
/**
Prints to the active [`Runtime`](struct.Runtime.html)'s current
[`epr_writer`](fn.set_epr_writer.html), with a trailing `'\n'`.
The input syntax is identical to [`eprintln!`](https://doc.rust-lang.org/std/macro.eprintln.html).
The `epr_writer` defaults to [`Stderr`](https://doc.rust-lang.org/std/io/struct.Stderr.html).
*/
#[macro_export]
macro_rules! eprn {
($($arg:tt)*) => (
{
use std::io::Write;
writeln!($crate::EprWriter, $($arg)*).ok();
}
);
}
//-------------------------------------------------------------------------------------------------
// EngineStorage, EngineBuilder and Engine
//-------------------------------------------------------------------------------------------------
//GSend is for data which can be moved from one engine to another. GStore is for data which
//can be stored on an engine's gc heap (i.e., anything except a Root<T> or a borrowed Lib/RData)
//these are not unsafe traits, even in "unsafe-internals" mode, because the Heap contains
//dynamic checks (in the write barrier) to ensure that a Root is never assigned to a Heap
//other than its originating Heap.
/**
An auto trait for types which can be moved between one [`Runtime`](struct.Runtime.html) and
another.
This is enforced with a `GSend` bound on the closure and return value for
[`Runtime::run`](struct.Runtime.html#method.run). For example, it's not possible for `run()`
to capture a [`Root<Arr>`](struct.Root.html) or return a [`Val`](enum.Val.html).
This enforcement is slightly leaky. For example, it's possible to sneak a [`Val`](enum.Val.html)
into the global scope by using
[`thread_local!`](https://doc.rust-lang.org/std/macro.thread_local.html), or by implementing
`GSend` for one of your own types. GameLisp contains dynamic checks to detect this
situation, in which case the process will abort.
*/
pub auto trait GSend { }
impl !GSend for Sym { }
impl !GSend for RFn { }
impl<T> !GSend for Gc<T> { }
impl<T> !GSend for Root<T> { }
impl<T> !GSend for LibRef<T> { }
impl<T> !GSend for LibRefMut<T> { }
impl<T> !GSend for RRef<T> { }
impl<T> !GSend for RRefMut<T> { }
/**
An auto trait for types which can be stored on the garbage-collected heap.
This is enforced with a `GStore` bound on the [`RStore` trait](trait.RStore.html), so that all
types stored in an [`RData`](struct.RData.html) must implement `GStore`.
This trait is automatically implemented for most types. The main counterexample is
[`Root`](struct.Root.html) (and any type which transitively contains a `Root`, like
[`Val`](enum.Val.html)), because storing a `Root` on the garbage-collected heap would
be too likely to cause memory leaks.
Note that [libraries](trait.Lib.html) are not stored on the garbage-collected heap, so
library types don't need to implement `GStore`, and it's fine for libraries to contain
`Root`s.
*/
pub auto trait GStore { }
impl GStore for RData { }
impl<T> !GStore for Root<T> { }
impl<T> !GStore for LibRef<T> { }
impl<T> !GStore for LibRefMut<T> { }
impl<T> !GStore for RRef<T> { }
impl<T> !GStore for RRefMut<T> { }
impl<T> !Send for Gc<T> { }
impl<T> !Send for Root<T> { }
impl !Send for Sym { }
impl !Send for RFn { }
#[doc(hidden)]
pub struct EngineBuilder;
impl EngineBuilder {
pub fn new() -> EngineBuilder {
EngineBuilder
}
pub fn build(self) -> Engine {
Engine::new()
}
}
#[doc(hidden)]
pub struct Engine(Rc<EngineStorage>);
impl Drop for Engine {
fn drop(&mut self) {
//we drop all of the Libs in the reverse order that they were registered, while
//temporarily making this engine active, before dropping any other part of the engine
//(trying to make Lib destructors as user-friendly as possible). we allow take_lib() and
//add_lib() to be called in a Lib destructor by leaving engine.libs and
//engine.libs_ordering unborrowed while the destructor runs.
self.run(|| {
with_engine(|engine| {
while let Some(type_id) = engine.libs_ordering.borrow_mut().pop() {
let lib = engine.libs.borrow_mut().remove(&type_id).unwrap();
drop(lib);
}
//todo: we should consider free()ing all RData without any ACTIVE_RUNTIME, so
//that their destructors can't get up to any mischief like calling add_lib().
//we need to clean up the Heap because otherwise it will leak memory if the
//unsafe-internals flag is disabled, by leaving Rc reference loops intact. as
//such, we first need to clean up anything that holds a Root. (this also helps
//us to uphold the invariant that a Root cannot exist when its Heap is dropped.)
engine.lazy_storage.borrow_mut().clear();
engine.syms.borrow_mut().clear();
engine.rfns.borrow_mut().clear();
engine.vm.clear();
engine.heap.clear();
});
Ok(())
});
free_engine_id(self.0.id);
//this should be guaranteed, i think, since engine.run() borrows the Engine so that it
//can't be dropped, and there should be no other source for an Rc<EngineStorage>.
debug_assert!(Rc::strong_count(&self.0) == 1);
}
}
struct EngineStorage {
id: u8,
heap: Heap,
vm: Vm,
pr_writer: RefCell<Box<dyn Write>>,
epr_writer: RefCell<Box<dyn Write>>,
syms: RefCell<Vec<SymEntry>>,
syms_map: RefCell<HashMap<Rc<str>, Sym>>,
gensym_counter: Cell<u32>,
gensym_seed: RefCell<Option<String>>,
spans: RefCell<Vec<SpanStorage>>,
spans_map: RefCell<HashMap<SpanStorage, Span>>,
filenames: RefCell<Vec<Rc<str>>>,
filenames_map: RefCell<HashMap<Rc<str>, Filename>>,
required: RefCell<HashSet<PathBuf>>,
rfns: RefCell<Vec<RFnEntry>>,
rfns_map: RefCell<HashMap<usize, RFn>>,
rclasses: RefCell<HashMap<TypeId, Rc<RClass>>>,
rclass_names: RefCell<HashSet<&'static str>>,
in_expander: RefCell<Option<(Option<Sym>, Span, Rc<Env>)>>,
errors_verbose: Cell<bool>,
libs: RefCell<HashMap<TypeId, Rc<dyn Any>>>,
libs_ordering: RefCell<Vec<TypeId>>,
#[cfg(feature = "compiler")] recording: RefCell<Option<Recording>>,
#[cfg(feature = "compiler")] playing_back: RefCell<Option<Recording>>,
lazy_storage: RefCell<HashMap<String, Val>>,
known_ops: HashMap<Sym, KnownOp>
}
struct SymEntry {
name: Rc<str>,
kind: SymKind,
bound_global: Option<GlobalEntry>,
bound_macro: Option<Expander>
}
struct GlobalEntry {
val: Val,
frozen: bool
}
struct RFnEntry {
name: Option<Sym>,
wrapped_fn: WrappedFn
}
impl Engine {
pub fn new() -> Engine {
//build the initial syms database
let syms = Vec::from_iter(STOCK_SYMS.iter().map(|&(name, kind)| {
SymEntry {
name: name.into(),
kind,
bound_global: None,
bound_macro: None
}
}));
let syms_map = HashMap::from_iter(syms.iter().enumerate().map(|(i, sym_entry)| {
(Rc::clone(&sym_entry.name), Sym(i as u32))
}));
//the initial spans database just contains "Generated", so that it's always Span(0)
let spans = vec![SpanStorage::Generated];
let mut spans_map = HashMap::new();
spans_map.insert(SpanStorage::Generated, Span(0));
//Filenames and RFns store a NonZeroU32 to enable some layout optimizations. therefore,
//we need to insert dummy entries for Filename(0) and RFn(0).
let rfns = vec![RFnEntry {
name: None,
wrapped_fn: rfn!(|| panic!())
}];
let filenames = vec!["".into()];
let engine = Engine(Rc::new(EngineStorage {
id: alloc_engine_id().expect("more than 256 simultaneous Runtimes"),
heap: Heap::new(),
vm: Vm::new(),
pr_writer: RefCell::new(Box::new(stdout())),
epr_writer: RefCell::new(Box::new(stderr())),
syms: RefCell::new(syms),
syms_map: RefCell::new(syms_map),
gensym_counter: Cell::new(0),
gensym_seed: RefCell::new(None),
spans: RefCell::new(spans),
spans_map: RefCell::new(spans_map),
filenames: RefCell::new(filenames),
filenames_map: RefCell::new(HashMap::new()),
required: RefCell::new(HashSet::new()),
rfns: RefCell::new(rfns),
rfns_map: RefCell::new(HashMap::new()),
rclasses: RefCell::new(HashMap::new()),
rclass_names: RefCell::new(HashSet::new()),
in_expander: RefCell::new(None),
errors_verbose: Cell::new(true),
libs: RefCell::new(HashMap::new()),
libs_ordering: RefCell::new(Vec::new()),
#[cfg(feature = "compiler")] recording: RefCell::new(None),
#[cfg(feature = "compiler")] playing_back: RefCell::new(None),
lazy_storage: RefCell::new(HashMap::new()),
known_ops: known_ops()
}));
engine
}
//once we have specialisation, we could permit the closure to return any value, and only
//have the error-reporting behaviour when the return type is GResult<_>.
pub fn run<F, R>(&self, f: F) -> Option<R>
where
F: FnOnce() -> GResult<R>,
F: GSend,
R: GSend
{
let old_active_engine = ACTIVE_ENGINE.with(|ref_cell| {
ref_cell.replace(Some(self.0.clone()))
});
let old_engine_id = ACTIVE_ENGINE_ID.with(|cell| {
cell.replace(Some(self.0.id))
});
let _guard = Guard::new(|| {
ACTIVE_ENGINE.with(|ref_cell| {
ref_cell.replace(old_active_engine);
});
ACTIVE_ENGINE_ID.with(|cell| {
cell.set(old_engine_id);
});
});
let result = f();
if let Err(ref error) = result {
if error.stack_trace().is_some() {
eprn!("\nunhandled error in run() call:\n\n{}", error);
} else {
eprn!("\nunhandled error in run() call: {}", error);
}
}
result.ok()
}
}
//-------------------------------------------------------------------------------------------------
// Guard
//-------------------------------------------------------------------------------------------------
//because rfns are allowed to panic, and because various glsp functions can early-exit when an
//error is generated, we need to be careful about unwind-safety. we mostly achieve this using the
//Guard struct, which runs an arbitrary closure when it's dropped.
pub(crate) struct Guard<F: FnOnce()>(Option<F>);
impl<F: FnOnce()> Guard<F> {
pub(crate) fn new(f: F) -> Guard<F> {
Guard(Some(f))
}
}
impl<F: FnOnce()> Drop for Guard<F> {
fn drop(&mut self) {
(self.0.take().unwrap())()
}
}
//-------------------------------------------------------------------------------------------------
// Sym, ToSym, RFn, Filename
//-------------------------------------------------------------------------------------------------
/**
The `sym` primitive type.
Symbols are represented by a small `Copy` type (a 32-bit integer id).
To convert a string into a symbol, you should usually call [`glsp::sym`](fn.sym.html).
*/
#[derive(PartialEq, Eq, Hash, Copy, Clone)]
pub struct Sym(pub(crate) u32);
const MAX_SYM: u32 = 0xffffff;
impl Sym {
/**
Returns the name of the symbol.
For gensyms, the name is the same as its printed representation, e.g. `#<gs:tag:8>`.
*/
pub fn name(&self) -> Rc<str> {
with_engine(|engine| {
Rc::clone(&engine.syms.borrow()[self.0 as usize].name)
})
}
/**
Returns `true` if this symbol is a gensym.
Gensyms are constructed using [`glsp::gensym`](fn.gensym.html) or
[`glsp::gensym_with_tag`](fn.gensym_with_tag.html).
*/
pub fn is_gensym(&self) -> bool {
self.kind() == SymKind::Gensym
}
//only public so that it can be used internally by the backquote!() macro
#[doc(hidden)]
pub fn kind(&self) -> SymKind {
with_engine(|engine| {
engine.syms.borrow()[self.0 as usize].kind
})
}
//used internally by the encoder and by (bind-global!). we forbid special forms' names from
//being rebound to global or local variables, but not from being bound to a macro. a (let)
//macro has its uses, but a shadowing local variable named something like `defer` would break
//too many macros to be useful.
pub(crate) fn is_bindable(&self) -> bool {
match self.kind() {
SymKind::StockSpecial => false,
SymKind::Normal | SymKind::StockKeyword |
SymKind::StockTransform | SymKind::Gensym => true
}
}
//only public so that it can be used internally by the backquote!() macro
#[doc(hidden)]
pub fn from_u32(id: u32) -> Sym {
assert!(id <= MAX_SYM);
Sym(id)
}
//only public so that it can be used internally by the backquote!() macro
#[doc(hidden)]
pub fn to_u32(&self) -> u32 {
self.0
}
}
/**
A type which can be converted to a [`Sym`](struct.Sym.html).
This is mostly used to make APIs more ergonomic. For example, the argument to
[`glsp::global`](fn.global.html) is a generic `S: ToSym`, which means that it can
receive either a symbol or a string:
glsp::global(my_lib.my_sym)?;
glsp::global("sym-name")?;
*/
pub trait ToSym {
fn to_sym(&self) -> GResult<Sym>;
}
impl<'a, T> ToSym for T
where
T: Deref,
T::Target: ToSym
{
fn to_sym(&self) -> GResult<Sym> {
(**self).to_sym()
}
}
impl ToSym for Sym {
fn to_sym(&self) -> GResult<Sym> {
Ok(*self)
}
}
impl<'a> ToSym for str {
fn to_sym(&self) -> GResult<Sym> {
glsp::sym(self)
}
}
impl<'a> ToSym for Str {
fn to_sym(&self) -> GResult<Sym> {
glsp::sym(&self.to_string())
}
}
#[doc(hidden)]
#[derive(Clone, Copy, PartialEq)]
pub enum SymKind {
Normal,
StockSpecial,
StockKeyword,
StockTransform,
Gensym
}
/**
The `rfn` primitive type.
Rust functions are represented by a small `Copy` type (a 32-bit integer id).
Most of this type's methods belong to the `callable` abstract type, so they can be found in
the [`CallableOps`](trait.CallableOps.html) trait. To invoke an `RFn`, use
[`glsp::call`](fn.call.html).
To convert a function pointer or a closure into an `RFn`, you should usually call
[`glsp::bind_rfn`](fn.bind_rfn.html) or [`glsp::rfn`](fn.rfn.html).
*/
#[derive(PartialEq, Eq, Hash, Copy, Clone)]
pub struct RFn(NonZeroU32);
impl RFn {
pub(crate) fn set_name(&self, new_name: Option<Sym>) {
with_engine(|engine| {
engine.rfns.borrow_mut()[self.0.get() as usize].name = new_name;
})
}
}
impl CallableOps for RFn {
fn receive_call(&self, arg_count: usize) -> GResult<Val> {
glsp::call_rfn(*self, arg_count).map(|slot| slot.root())
}
fn name(&self) -> Option<Sym> {
with_engine(|engine| {
engine.rfns.borrow()[self.0.get() as usize].name
})
}
fn arg_limits(&self) -> (usize, Option<usize>) {
with_engine(|engine| {
engine.rfns.borrow()[self.0.get() as usize].wrapped_fn.arg_limits
})
}
}
#[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)]
pub struct Filename(NonZeroU32);
/**
Define a struct which contains a collection of symbols.
Caching symbols in a struct has better performance than calling [`glsp::sym`](fn.sym.html), and
it's more convenient than storing `Sym` fields in your own structs directly.
The struct defines a method `fn new() -> GResult<Self>` which initializes each field by passing
the given string literal to [`glsp::sym`](fn.sym.html).
syms! {
#[derive(Clone)]
pub struct Syms {
pub width: "width",
pub set_width: "width=",
rectp: "rect?"
}
}
*/
#[macro_export]
macro_rules! syms {
(
$(#[$struct_attr:meta])*
$struct_vis:vis struct $struct_name:ident {
$($vis:vis $name:ident: $contents:literal),+
}
) => (
$crate::syms! {
$(#[$struct_attr])*
$struct_vis struct $struct_name {
$($vis $name: $contents,)+
}
}
);
(
$(#[$struct_attr:meta])*
$struct_vis:vis struct $struct_name:ident {
$($vis:vis $name:ident: $contents:literal,)*
}
) => (
$struct_vis struct $struct_name {
$($vis $name: Sym,)*
}
impl $struct_name {
#[allow(unused_variables)]
$struct_vis fn new() -> GResult<Syms> {
Ok($struct_name {
$($name: glsp::sym($contents)?,)*
})
}
}
);
}
//-------------------------------------------------------------------------------------------------
// Lib, RData, RRoot
//-------------------------------------------------------------------------------------------------
/**
A type which can be passed to [`glsp::add_lib`](fn.add_lib.html).
It's possible to implement this trait manually, but using the [`lib!` macro](macro.lib.html) is
strongly encouraged. Among other things, that macro will automatically implement
[`MakeArg`](trait.MakeArg.html) for the library type.
*/
pub trait Lib: 'static + Sized {
fn type_name() -> &'static str;
/**
Returns a shared reference to the instance of this type owned by the active
[`Runtime`](struct.Runtime.html).
Panics if a library of this type has not been registered with the active `Runtime`, or if
the library is currently mutably borrowed.
*/
fn borrow() -> LibRef<Self> {
glsp::lib::<Self>()
}
/**
Returns a mutable reference to the instance of this type owned by the active
[`Runtime`](struct.Runtime.html).
Panics if a library of this type has not been registered with the active `Runtime`, or if
the library is currently borrowed.
*/
fn borrow_mut() -> LibRefMut<Self> {
glsp::lib_mut::<Self>()
}
/**
Returns a shared reference to the instance of this type owned by the active
[`Runtime`](struct.Runtime.html).
Returns an `Err` if a library of this type has not been registered with the active `Runtime`,
or if the library is currently mutably borrowed.
*/
fn try_borrow() -> GResult<LibRef<Self>> {
glsp::try_lib::<Self>()
}
/**
Returns a mutable reference to the instance of this type owned by the active
[`Runtime`](struct.Runtime.html).
Returns an `Err` if a library of this type has not been registered with the active `Runtime`,
or if the library is currently borrowed.
*/
fn try_borrow_mut() -> GResult<LibRefMut<Self>> {
glsp::try_lib_mut::<Self>()
}
}
/**
A reference to a [library](trait.Lib.html).
Created using [`Lib::borrow`](trait.Lib.html#method.borrow) or
[`Lib::try_borrow`](trait.Lib.html#method.try_borrow).
*/
pub struct LibRef<T: Lib> {
handle: OwningHandle<Rc<RefCell<T>>, Ref<'static, T>>
}
impl<T: Lib> Deref for LibRef<T> {
type Target = T;
fn deref(&self) -> &T {
&*self.handle
}
}
/**
A mutable reference to a [library](trait.Lib.html).
Created using [`Lib::borrow_mut`](trait.Lib.html#method.borrow_mut) or
[`Lib::try_borrow_mut`](trait.Lib.html#method.try_borrow_mut).
*/
pub struct LibRefMut<T: Lib> {
handle: OwningHandle<Rc<RefCell<T>>, RefMut<'static, T>>
}
impl<T: Lib> Deref for LibRefMut<T> {
type Target = T;
fn deref(&self) -> &T {
&*self.handle
}
}
impl<T: Lib> DerefMut for LibRefMut<T> {
fn deref_mut(&mut self) -> &mut T {
&mut *self.handle
}
}
trait RAllocate: GStore + 'static {
fn type_name(&self) -> &'static str;
fn size_of(&self) -> usize;
fn as_any(&self) -> &dyn Any;
fn as_rc_any(self: Rc<Self>) -> Rc<dyn Any>;
}
impl<T: RStore> RAllocate for RefCell<T> {
fn type_name(&self) -> &'static str {
T::type_name()
}
fn size_of(&self) -> usize {
T::size_of()
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_rc_any(self: Rc<Self>) -> Rc<dyn Any> {
self
}
}
/**
A type which can be moved onto the garbage-collected heap as an [`RData`](struct.RData.html).
It's possible to implement this trait manually, but using the [`rdata!` macro](macro.rdata.html)
is strongly encouraged. Among other things, that macro will automatically implement
[`MakeArg`](trait.MakeArg.html) and [`IntoResult`](trait.IntoResult.html) for your type.
*/
pub trait RStore: GStore + 'static {
fn type_name() -> &'static str;
//ideally we would provide a `fn owned_memory_usage(&self)` for this trait, but it's not clear
//what the syntax would be for implementing it, or how we would document it. for now we just
//report the size of the stored struct itself.
fn size_of() -> usize;
fn rclass() -> GResult<RClass>;
}
/**
An implementation detail of the [`RStore` trait](trait.RStore.html) and the
[`rdata!` macro](macro.rdata.html).
*/
pub struct RClass {
name: Sym,
bindings: FnvHashMap<Sym, RBinding>
}
enum RBinding {
Meth(RFn),
Prop(Option<RFn>, Option<RFn>)
}
impl RClass {
pub fn from_vec(
class_name: &'static str,
raw_bindings: Vec<(&'static str, &'static str, WrappedFn)>
) -> GResult<RClass> {
let class_name = glsp::sym(class_name)?;
let mut bindings = FnvHashMap::with_capacity_and_hasher(
raw_bindings.len(),
Default::default()
);
for (kind, key, wrapped_fn) in raw_bindings {
let name = glsp::sym(key)?;
let rfn = glsp::rfn(wrapped_fn);
if rfn.name().is_none() {
rfn.set_name(Some(name));
}
match (kind, bindings.entry(name)) {
("", Vacant(entry)) => { entry.insert(RBinding::Meth(rfn)); }
("get", Vacant(entry)) => { entry.insert(RBinding::Prop(Some(rfn), None)); }
("set", Vacant(entry)) => { entry.insert(RBinding::Prop(None, Some(rfn))); }
("", Occupied(_)) => bail!("duplicate meth name {}", name),
("get", Occupied(mut entry)) => {
match entry.get_mut() {
RBinding::Meth(_) => bail!("{} is bound to both a meth and a prop", name),
RBinding::Prop(Some(_), _) => bail!("duplicate getter {}", name),
RBinding::Prop(ref mut none, _) => *none = Some(rfn)
}
}
("set", Occupied(mut entry)) => {
match entry.get_mut() {
RBinding::Meth(_) => bail!("{} is bound to both a meth and a prop", name),
RBinding::Prop(_, Some(_)) => bail!("duplicate setter {}", name),
RBinding::Prop(_, ref mut none) => *none = Some(rfn)
}
}
(kind, _) => bail!("{} is not a valid tag for an RData meth", kind)
}
}
Ok(RClass {
name: class_name,
bindings
})
}
}
/**
The `rdata` primitive type.
This is a Rust value which has been moved onto the garbage-collected heap. It can be constructed
using the [`glsp::rdata`](fn.rdata.html) function.
`RData` has several convenience features:
- It supports interior mutability, like a
[`RefCell`](https://doc.rust-lang.org/std/cell/struct.RefCell.html).
- It can be manually deallocated, or taken back from the garbage-collected heap, using
[`free`](#method.free) and [`take`](#method.take). Any attempts to access a deallocated `RData`
from GameLisp will trigger an error.
- It's dynamically typed: a `Vec<Root<RData>>` could refer to several different Rust types.
(If this is undesirable, consider using [`RRoot`](struct.RRoot.html) instead.)
- The [`rdata!` macro](macro.rdata.html) enables Rust functions to be associated with an `RData`
as its methods and properties. They can be accessed from GameLisp code, or accessed from Rust
code using an API similar to [`Obj`](struct.Obj.html).
*/
pub struct RData {
header: GcHeader,
storage: RefCell<Option<Rc<dyn RAllocate>>>,
pub(crate) class: Rc<RClass>,
//just like Obj, we need this field so that we can generate a `self` argument when
//rdata.call() is invoked from rust code
gc_self: Cell<Option<Gc<RData>>>
}
impl Allocate for RData {
fn header(&self) -> &GcHeader {
&self.header
}
fn visit_gcs<V: Visitor>(&self, visitor: &mut V) {
visitor.visit_gc(&self.gc_self());
}
fn clear_gcs(&self) {
self.gc_self.set(None);
}
fn owned_memory_usage(&self) -> usize {
match self.storage.borrow().as_ref() {
Some(rc_ref) => rc_ref.size_of(),
None => 0
}
}
}
/**
A shared reference to an [`RData`](struct.RData.html).
Created using [`RData::borrow`](struct.RData.html#method.borrow) or
[`RData::try_borrow`](struct.RData.html#method.try_borrow).
*/
pub struct RRef<T: RStore>(OwningHandle<Rc<RefCell<T>>, Ref<'static, T>>);
impl<T: RStore> Deref for RRef<T> {
type Target = T;
fn deref(&self) -> &T {
&*self.0
}
}
/**
A mutable reference to an [`RData`](struct.RData.html).
Created using [`RData::borrow_mut`](struct.RData.html#method.borrow_mut) or
[`RData::try_borrow_mut`](struct.RData.html#method.try_borrow_mut).
*/
pub struct RRefMut<T: RStore>(OwningHandle<Rc<RefCell<T>>, RefMut<'static, T>>);
impl<T: RStore> Deref for RRefMut<T> {
type Target = T;
fn deref(&self) -> &T {
&*self.0
}
}
impl<T: RStore> DerefMut for RRefMut<T> {
fn deref_mut(&mut self) -> &mut T {
&mut *self.0
}
}
impl RData {
pub(crate) fn new<T: RStore>(rdata: T, class: Rc<RClass>) -> RData {
RData {
header: GcHeader::new(),
storage: RefCell::new(Some(Rc::new(RefCell::new(rdata)))),
class,
gc_self: Cell::new(None)
}
}
pub fn type_name(&self) -> &'static str {
match self.storage.borrow().as_ref() {
Some(rc_ref) => rc_ref.type_name(),
None => ""
}
}
pub fn class_name(&self) -> Sym {
self.class.name
}
/**
Returns `true` if this `RData` is currently storing a value of type `T`.
*/
pub fn is<T: RStore>(&self) -> bool {
self.storage.borrow().as_ref().unwrap().as_any().is::<RefCell<T>>()
}
/**
Returns a shared reference to the value being stored by this `RData`.
Panics if the `RData` is not storing a value of type `T`; if its value has been freed; or
if the value is currently mutably borrowed.
*/
pub fn borrow<T: RStore>(&self) -> RRef<T> {
self.try_borrow::<T>().unwrap()
}
/**
Returns a shared reference to the value being stored by this `RData`.
Returns an `Err` if the `RData` is not storing a value of type `T`; if its value has
been freed; or if the value is currently mutably borrowed.
*/
pub fn try_borrow<T: RStore>(&self) -> GResult<RRef<T>> {
let borrow = match self.storage.try_borrow() {
Ok(borrow) => borrow,
Err(_) => {
//this is unreachable because the only time we *mutably* borrow the
//outer RData is when we're about to free it
unreachable!()
}
};
if let Some(ref rc) = *borrow {
match Rc::downcast::<RefCell<T>>(rc.clone().as_rc_any()) {
Ok(rc_ref_cell) => {
ensure!(rc_ref_cell.try_borrow().is_ok(),
"try_borrow<{}> failed: value is mutably borrowed", T::type_name());
Ok(RRef(OwningHandle::new(rc_ref_cell)))
}
Err(_) => bail!("type mismatch in try_borrow<{}>()", T::type_name())
}
} else {
bail!("try_borrow<{}> failed: attempted to access a freed RData", T::type_name())
}
}
/**
Returns a mutable reference to the value being stored by this `RData`.
Panics if the `RData` is not storing a value of type `T`; if its value has been freed; or
if the value is currently borrowed.
*/
pub fn borrow_mut<T: RStore>(&self) -> RRefMut<T> {
self.try_borrow_mut::<T>().unwrap()
}
/**
Returns a mutable reference to the value being stored by this `RData`.
Returns an `Err` if the `RData` is not storing a value of type `T`; if its value has
been freed; or if the value is currently borrowed.
*/
pub fn try_borrow_mut<T: RStore>(&self) -> GResult<RRefMut<T>> {
let borrow = match self.storage.try_borrow() {
Ok(borrow) => borrow,
Err(_) => {
//this is unreachable because the only time we *mutably* borrow the
//outer RefCell is when we're about to free it
unreachable!()
}
};
if let Some(ref rc) = *borrow {
match Rc::downcast::<RefCell<T>>(rc.clone().as_rc_any()) {
Ok(rc_ref_cell) => {
ensure!(rc_ref_cell.try_borrow_mut().is_ok(),
"try_borrow_mut<{}> failed: value is currently borrowed",
T::type_name());
Ok(RRefMut(OwningHandle::new_mut(rc_ref_cell)))
}
Err(_) => bail!("type mismatch in try_borrow<{}>()", T::type_name())
}
} else {
bail!("try_borrow_mut<{}> failed: attempted to access a freed RData", T::type_name())
}
}
/**
Takes the value stored in this `RData` and returns it.
Any future attempts to access the value will gracefully fail.
Returns an `Err` if the `RData` is not storing a value of type `T`; if its value has already
been freed; or if it's currently borrowed.
*/
pub fn take<T: RStore>(&self) -> GResult<T> {
//freeing the stored data changes our owned_memory_usage(), so we need to write-barrier it.
let prev_usage = self.owned_memory_usage();
match self.storage.try_borrow_mut() {
Ok(mut borrow_mut) => {
match *borrow_mut {
Some(ref rc) if Rc::strong_count(rc) == 1 => {
drop(rc);
let rc_any = (*borrow_mut).take().unwrap().as_rc_any();
drop(borrow_mut);
let rc = match Rc::downcast::<RefCell<T>>(rc_any) {
Ok(rc) => rc,
Err(_) => {
bail!("type mismatch when calling take::<{}>()", T::type_name())
}
};
let cur_usage = self.owned_memory_usage();
with_heap(|heap| heap.memory_usage_barrier(self, prev_usage, cur_usage));
let ref_cell = Rc::try_unwrap(rc).ok().unwrap();
Ok(ref_cell.into_inner())
}
Some(_) => bail!("called take() on an RData which is currently borrowed"),
None => bail!("called take() on an RData which has already been freed")
}
}
Err(_) => bail!("called take() on an RData which is currently borrowed")
}
}
/**
Drops the value stored by this `RData`.
Any future attempts to access the value will gracefully fail.
Returns an `Err` if the `RData` is not storing a value of type `T`; if its value has already
been freed; or if it's currently borrowed.
*/
pub fn free(&self) -> GResult<()> {
//freeing the stored data changes our owned_memory_usage(), so we need to write-barrier it.
let prev_usage = self.owned_memory_usage();
match self.storage.try_borrow_mut() {
Ok(mut borrow_mut) => {
match *borrow_mut {
Some(ref rc) if Rc::strong_count(rc) == 1 => {
drop(rc);
*borrow_mut = None;
drop(borrow_mut);
let cur_usage = self.owned_memory_usage();
with_heap(|heap| heap.memory_usage_barrier(self, prev_usage, cur_usage));
Ok(())
}
Some(_) => bail!("called free() on an RData which is currently borrowed"),
None => bail!("called free() on an RData which has already been freed")
}
}
Err(_) => bail!("called take() on an RData which is currently borrowed")
}
}
///Returns `true` if this `RData`'s value has been taken or freed.
pub fn is_freed(&self) -> bool {
match self.storage.try_borrow() {
Ok(borrow) => borrow.is_none(),
Err(_) => unreachable!()
}
}
fn gc_self(&self) -> Gc<RData> {
let gc_self = self.gc_self.take();
self.gc_self.set(gc_self.clone());
gc_self.unwrap()
}
/**
Creates an indexing iterator for this collection.
Equivalent to [`[rdata iter]`](https://gamelisp.rs/std/access).
*/
pub fn access_giter(rdata: &Root<RData>, giter: &Root<GIter>) -> Root<GIter> {
glsp::giter(GIterState::AccessRData(rdata.to_gc(), giter.to_gc()))
}
/**
Accesses the value of a field or property.
Equivalent to [`[rdata key]`](https://gamelisp.rs/std/access).
*/
pub fn get<S, R>(&self, key: S) -> GResult<R>
where
S: ToSym,
R: FromVal
{
let sym = key.to_sym()?;
match self.get_if_present(sym)? {
Some(r) => Ok(r),
None => bail!("attempted to access nonexistent prop getter '{}'", sym)
}
}
/**
Accesses the value of a field or property, if it exists.
Equivalent to [`[rdata (? key)]`](https://gamelisp.rs/std/access).
*/
pub fn get_if_present<S, R>(&self, key: S) -> GResult<Option<R>>
where
S: ToSym,
R: FromVal
{
let sym = key.to_sym()?;
match self.class.bindings.get(&sym) {
Some(RBinding::Prop(Some(rfn), _)) => {
with_vm(|vm| {
vm.stacks.borrow_mut().regs.push(Slot::RData(self.gc_self()));
Ok(Some(R::from_val(&rfn.receive_call(1)?)?))
})
}
_ => Ok(None)
}
}
/**
Mutates the field or property bound to the given name.
Equivalent to [`(= [rdata key] val)`](https://gamelisp.rs/std/set-access).
*/
pub fn set<S, V>(&self, key: S, val: V) -> GResult<()>
where
S: ToSym,
V: ToVal
{
let sym = key.to_sym()?;
ensure!(self.set_if_present(sym, val)?, "attempted to assign to nonexistent or \
readonly prop '{}'", sym);
Ok(())
}
/**
Mutates the field or property bound to the given name, if any. Returns `true` if the
field or property exists.
Equivalent to [`(= [rdata (? key)] val)`](https://gamelisp.rs/std/set-access).
*/
pub fn set_if_present<S, V>(&self, key: S, val: V) -> GResult<bool>
where
S: ToSym,
V: ToVal
{
let sym = key.to_sym()?;
match self.class.bindings.get(&sym) {
Some(RBinding::Prop(_, Some(rfn))) => {
with_vm(|vm| {
let mut stacks = vm.stacks.borrow_mut();
stacks.regs.push(Slot::RData(self.gc_self()));
stacks.regs.push(val.to_slot()?);
drop(stacks);
rfn.receive_call(2)?;
Ok(true)
})
}
_ => Ok(false)
}
}
/**
Invokes a method.
Equivalent to [`(call-meth rdata key ..args)`](https://gamelisp.rs/std/call-meth).
*/
pub fn call<S, A, R>(&self, key: S, args: &A) -> GResult<R>
where
S: ToSym,
A: ToCallArgs + ?Sized,
R: FromVal
{
let sym = key.to_sym()?;
match self.call_if_present(sym, args)? {
Some(r) => Ok(r),
None => bail!("attempted to call nonexistent method '{}'", sym)
}
}
/**
Invokes a method, if it exists.
Equivalent to [`(call-meth rdata (? key) ..args)`](https://gamelisp.rs/std/call-meth).
*/
pub fn call_if_present<S, A, R>(&self, key: S, args: &A) -> GResult<Option<R>>
where
S: ToSym,
A: ToCallArgs + ?Sized,
R: FromVal
{
let sym = key.to_sym()?;
match self.class.bindings.get(&sym) {
Some(RBinding::Meth(rfn)) => {
with_vm(|vm| {
let mut stacks = vm.stacks.borrow_mut();
let starting_len = stacks.regs.len();
stacks.regs.push(Slot::RData(self.gc_self()));
args.to_call_args(&mut stacks.regs)?;
let arg_count = stacks.regs.len() - starting_len;
drop(stacks);
let val = rfn.receive_call(arg_count)?;
Ok(Some(R::from_val(&val)?))
})
}
_ => Ok(None)
}
}
/**
Returns `true` if the given name is bound to a method.
Equivalent to [`(has-meth? rdata key)`](https://gamelisp.rs/std/has-meth-p).
*/
pub fn has_meth<S: ToSym>(&self, key: S) -> GResult<bool> {
let sym = key.to_sym()?;
match self.class.bindings.get(&sym) {
Some(RBinding::Meth(_)) => Ok(true),
_ => Ok(false)
}
}
//designed to imitate Obj::get_method(). used in vm.rs
pub(crate) fn get_method(&self, key: Sym) -> Option<(Slot, bool, bool, Slot)> {
match self.class.bindings.get(&key) {
Some(&RBinding::Meth(rfn)) => Some((Slot::RFn(rfn), true, false, Slot::Nil)),
_ => None
}
}
/**
Equivalent to [`(eq? self other)`](https://gamelisp.rs/std/eq-p).
Note that, because this may invoke an `op-eq?` method, it can potentially fail.
The same is true for `PartialEq` comparisons between `RData` using Rust's `==` operator.
In that case, if an error occurs, the operator will panic.
*/
pub fn try_eq(&self, other: &Root<RData>) -> GResult<bool> {
if !Rc::ptr_eq(&self.class, &other.class) {
return Ok(false)
}
let val: Option<Val> = self.call_if_present(OP_EQP_SYM, &[other])?;
match val {
Some(val) => Ok(val.is_truthy()),
None => Ok(false)
}
}
}
impl PartialEq<Root<RData>> for RData {
fn eq(&self, other: &Root<RData>) -> bool {
self.try_eq(other).unwrap()
}
}
/**
A strongly-typed reference to an [`RData`](struct.RData.html).
Equivalent to a [`Root<RData>`](struct.Root.html), but it enforces that the `RData` must contain
a value of type `T`.
`RRoot` tends to be more self-documenting than `Root<RData>`, and it has a slightly more
convenient API.
//using Root
let mesh = player_mesh.borrow::<Mesh>();
let mesh2 = enemy_mesh.take::<Mesh>();
//using RRoot
let mesh = player_mesh.borrow();
let mesh2 = enemy_mesh.take();
*/
pub struct RRoot<T: RStore>(Root<RData>, PhantomData<Rc<RefCell<T>>>);
impl<T: RStore> Clone for RRoot<T> {
fn clone(&self) -> RRoot<T> {
RRoot(self.0.clone(), PhantomData)
}
}
impl<T: RStore> Debug for RRoot<T> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
Debug::fmt(&self.0, f)
}
}
impl<T: RStore> Display for RRoot<T> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
Display::fmt(&self.0, f)
}
}
impl<T: RStore> Pointer for RRoot<T> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
Pointer::fmt(&self.0, f)
}
}
impl<T: RStore> RRoot<T> {
/**
Constructs an `RRoot<T>` from a `Root<RData>`.
Panics if the `RData`'s value does not belong to the type `T`.
*/
pub fn new(root: Root<RData>) -> RRoot<T> {
assert!(root.is::<T>(), "type mismatch when constructing an RRoot<{}>", T::type_name());
RRoot(root, PhantomData)
}
///Returns a copy of the underlying `Root<RData>`.
pub fn to_root(&self) -> Root<RData> {
self.0.clone()
}
///Drops the `RRoot`, returning the wrapped `Root<RData>`.
pub fn into_root(self) -> Root<RData> {
self.0
}
///Returns `true` if both `RRoots` refer to the same `RData`.
pub fn ptr_eq(rr0: &RRoot<T>, rr1: &RRoot<T>) -> bool {
Root::ptr_eq(&rr0.0, &rr1.0)
}
pub(crate) fn to_gc(&self) -> Gc<RData> {
self.0.to_gc()
}
#[allow(dead_code)]
pub(crate) fn into_gc(self) -> Gc<RData> {
self.0.into_gc()
}
///Equivalent to [`RData::borrow`](struct.RData.html#method.borrow).
pub fn borrow(&self) -> RRef<T> {
self.0.borrow()
}
///Equivalent to [`RData::borrow_mut`](struct.RData.html#method.borrow_mut).
pub fn borrow_mut(&self) -> RRefMut<T> {
self.0.borrow_mut()
}
///Equivalent to [`RData::try_borrow`](struct.RData.html#method.try_borrow).
pub fn try_borrow(&self) -> GResult<RRef<T>> {
self.0.try_borrow()
}
///Equivalent to [`RData::try_borrow_mut`](struct.RData.html#method.try_borrow_mut).
pub fn try_borrow_mut(&self) -> GResult<RRefMut<T>> {
self.0.try_borrow_mut()
}
///Equivalent to [`RData::take`](struct.RData.html#method.take).
pub fn take(&self) -> GResult<T> {
self.0.take()
}
///Equivalent to [`RData::free`](struct.RData.html#method.free).
pub fn free(&self) -> GResult<()> {
self.0.free()
}
///Equivalent to [`RData::is_freed`](struct.RData.html#method.is_freed).
pub fn is_freed(&self) -> bool {
self.0.is_freed()
}
}
//-------------------------------------------------------------------------------------------------
// Span, SpanStorage and Frame
//-------------------------------------------------------------------------------------------------
//all arrs are tagged with a Span, indicating where they were created. we use this information
//for reporting line numbers when an error occurs.
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub(crate) enum SpanStorage {
//this arr was parsed from the text of a file which was passed to (load) or glsp.load().
//the Filename identifies the file, and the usize is the 1-indexed line number.
Loaded(Filename, usize),
//this arr was allocated within a macro expander. the Sym is the macro's name, the first Span
//identifies the macro's callsite (i.e. the Span of the arr from which it was expanded), and
//the second Span identifies the form's construction site (i.e. the Span of the (arr) or
//(clone) call, within a macro expander, which created the form).
Expanded(Option<Sym>, Span, Span),
//a broad category for any other arr. in practice, arrs which aren't loaded from a file or
//created within a macro expander are very unlikely to be used as syntax. when they are,
//the user is unlikely to care exactly where they were generated.
Generated
}
#[doc(hidden)]
#[derive(Default, PartialEq, Eq, Hash, Copy, Clone)]
pub struct Span(u32);
//-------------------------------------------------------------------------------------------------
// glsp:: functions
//-------------------------------------------------------------------------------------------------
pub mod glsp {
use super::*;
//---------------------------------------------------------------------------------------------
// syms
//---------------------------------------------------------------------------------------------
/** Equivalent to [`(sym name)`](https://gamelisp.rs/std/sym). */
pub fn sym(name: &str) -> GResult<Sym> {
ensure!(glsp::is_valid_sym_str(name), "invalid sym '{}'", name);
glsp::sym_impl(name, SymKind::Normal)
}
fn sym_impl(name: &str, kind: SymKind) -> GResult<Sym> {
with_engine(|engine| {
let mut syms_map = engine.syms_map.borrow_mut();
if let Some(sym) = syms_map.get(name) {
Ok(*sym)
} else {
let name = Rc::<str>::from(name);
let mut syms = engine.syms.borrow_mut();
syms.push(SymEntry {
name: name.clone(),
kind,
bound_global: None,
bound_macro: None
});
//we panic rather than returning an Err here, becuase we consider running out of
//Syms to be an unrecoverable error, similar to out-of-memory in a Rust program
assert!(syms.len() - 1 <= MAX_SYM as usize,
"program requires more than {} unique symbols", MAX_SYM + 1);
let sym = Sym((syms.len() - 1) as u32);
syms_map.insert(name, sym);
Ok(sym)
}
})
}
/** Equivalent to [`(valid-sym-str? st)`](https://gamelisp.rs/std/valid-sym-str-p). */
pub fn is_valid_sym_str(st: &str) -> bool {
//one or more of the valid sym chars, optionally with a '#' suffix
let mut rev_iter = st.chars().rev();
match rev_iter.next() {
None => false,
Some('#') => st.len() > 1 && rev_iter.all(|ch| lex::is_valid_sym_char(ch)),
Some(last_char) => {
lex::is_valid_sym_char(last_char) && rev_iter.all(|ch| {
lex::is_valid_sym_char(ch)
})
}
}
}
/** Equivalent to [`(valid-sym-char? ch)`](https://gamelisp.rs/std/valid-sym-char-p). */
pub fn is_valid_sym_char(ch: char) -> bool {
lex::is_valid_sym_char(ch)
}
/** Equivalent to [`(gensym)`](https://gamelisp.rs/std/gensym). */
pub fn gensym() -> Sym {
glsp::gensym_impl(None)
}
/** Equivalent to [`(gensym tag)`](https://gamelisp.rs/std/gensym). */
pub fn gensym_with_tag(tag: &str) -> GResult<Sym> {
ensure!(glsp::is_valid_sym_str(tag) && !tag.ends_with("#"),
"invalid gensym tag '{}': tags should be a valid sym without a trailing '#'",
tag);
Ok(glsp::gensym_impl(Some(tag)))
}
fn gensym_impl(tag: Option<&str>) -> Sym {
with_engine(|engine| {
let counter = engine.gensym_counter.get();
let seed = engine.gensym_seed.borrow();
let mut bytes = SmallVec::<[u8; 64]>::new();
write!(&mut bytes, "#<gs").unwrap();
if let Some(tag) = tag {
write!(&mut bytes, ":{}", tag).unwrap();
}
write!(&mut bytes, ":{}", counter).unwrap();
if let Some(ref seed) = *seed {
write!(&mut bytes, ":{}", seed).unwrap();
}
write!(&mut bytes, ">").unwrap();
engine.gensym_counter.set(counter + 1);
drop(seed);
let name = str::from_utf8(&bytes[..]).unwrap();
glsp::sym_impl(name, SymKind::Gensym).unwrap()
})
}
/**
Makes future gensyms globally unique.
When code is expanded in one Runtime and then evaluated in another (as for the
[`compile!`](macro.compile.html) and [`eval!`](macro.eval.html) macros, and the
[`glsp::load_and_compile`](fn.load_and_compile.html) function), gensym collisions may occur,
because the gensym counter will have been reset.
`glsp::seed_gensym` mitigates this by appending a 128-bit ID (derived from the current
wall-clock time) to all future gensyms produced by this `Runtime`. We don't switch it on by
default, because it makes gensyms' printed representation harder to read. However, it's
automatically switched on within [`glsp::load_and_compile`](fn.load_and_compile.html).
prn!("{}", glsp::gensym()); //prints #<gs:0>
glsp::seed_gensym();
prn!("{}", glsp::gensym()); //prints #<gs:1:wTz8iriBJYB>
*/
pub fn seed_gensym() {
with_engine(|engine| {
//this seems to have at least 100ns resolution
let nanos = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos();
//to keep it as concise as possible, we use base64
static CHARS: [char; 64] = [
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '_'
];
//this reverses the order of the characters, but it doesn't matter
let mut seed = String::new();
let mut bits = nanos;
while bits > 0 {
seed.push(CHARS[(bits & 0x3f) as usize]);
bits >>= 6;
}
*engine.gensym_seed.borrow_mut() = Some(seed);
})
}
//---------------------------------------------------------------------------------------------
// globals
//---------------------------------------------------------------------------------------------
/** Equivalent to [`(global s)`](https://gamelisp.rs/std/global). */
pub fn global<S, T>(s: S) -> GResult<T>
where
S: ToSym,
T: FromVal
{
with_engine(|engine| {
let sym = s.to_sym()?;
let syms = engine.syms.borrow();
let entry = &syms[sym.0 as usize];
match entry.bound_global {
Some(ref global) => T::from_val(&global.val),
None => bail!("symbol {} is not bound to a global", entry.name)
}
})
}
pub(crate) fn try_global<S, T>(s: S) -> GResult<Option<T>>
where
S: ToSym,
T: FromVal
{
with_engine(|engine| {
let sym = s.to_sym()?;
match engine.syms.borrow()[sym.0 as usize].bound_global {
Some(ref global) => T::from_val(&global.val).map(|t| Some(t)),
None => Ok(None)
}
})
}
/** Equivalent to [`(= (global s) val)`](https://gamelisp.rs/std/set-global). */
pub fn set_global<S, T>(s: S, val: T) -> GResult<()>
where
S: ToSym,
T: ToVal
{
with_engine(|engine| {
let sym = s.to_sym()?;
let val = val.to_val()?;
let mut syms = engine.syms.borrow_mut();
let entry = &mut syms[sym.0 as usize];
match entry.bound_global {
Some(ref mut global) => {
if global.frozen {
let name = entry.name.clone();
drop(global);
drop(entry);
drop(syms);
bail!("attempted to mutate frozen global {}", name);
}
global.val = val;
Ok(())
}
None => {
let name = entry.name.clone();
drop(entry);
drop(syms);
bail!("symbol {} is not bound to a global", name)
}
}
})
}
pub(crate) enum TrySetGlobalOutcome {
Success,
NotBound,
Frozen
}
pub(crate) fn try_set_global<S, T>(s: S, t: T) -> GResult<TrySetGlobalOutcome>
where
S: ToSym,
T: ToVal
{
with_engine(|engine| {
let sym = s.to_sym()?;
let val = t.to_val()?;
let mut syms = engine.syms.borrow_mut();
let entry = &mut syms[sym.0 as usize];
match entry.bound_global {
Some(ref mut global) => {
if global.frozen {
return Ok(TrySetGlobalOutcome::Frozen)
}
global.val = val;
Ok(TrySetGlobalOutcome::Success)
}
None => Ok(TrySetGlobalOutcome::NotBound)
}
})
}
/** Equivalent to [`(freeze-global! s)`](https://gamelisp.rs/std/freeze-global-mut). */
pub fn freeze_global<S>(s: S) -> GResult<()>
where
S: ToSym
{
with_engine(|engine| {
let sym = s.to_sym()?;
let mut syms = engine.syms.borrow_mut();
let entry = &mut syms[sym.0 as usize];
match entry.bound_global {
Some(ref mut global) => {
global.frozen = true;
Ok(())
}
None => {
let name = entry.name.clone();
drop(entry);
drop(syms);
bail!("attempted to freeze the unbound global {}", name)
}
}
})
}
//freezes each global which might be caught by the op-transforms pass, like "+". we can't do
//this in the Engine constructor because the stdlib initialization code needs to be able to
//bind new rfns to these syms.
#[doc(hidden)]
pub fn freeze_transform_fns() {
with_engine(|engine| {
let mut syms = engine.syms.borrow_mut();
for sym in STOCK_SYMS_BY_KIND[2] {
let entry = &mut syms[sym.0 as usize];
if entry.kind != SymKind::StockTransform {
panic!()
}
if let Some(ref mut global) = entry.bound_global {
global.frozen = true;
} else {
panic!("transform fn {} is not bound", entry.name)
}
}
})
}
/** Equivalent to [`(has-global? s)`](https://gamelisp.rs/std/has-global-p). */
pub fn has_global<S>(s: S) -> GResult<bool>
where
S: ToSym
{
with_engine(|engine| {
let sym = s.to_sym()?;
Ok(engine.syms.borrow()[sym.0 as usize].bound_global.is_some())
})
}
/** Equivalent to [`(bind-global! s)`](https://gamelisp.rs/std/bind-global-mut). */
pub fn bind_global<S, T>(s: S, t: T) -> GResult<()>
where
S: ToSym,
T: ToVal
{
with_engine(|engine| {
let sym = s.to_sym()?;
ensure!(sym.is_bindable(), "unable to bind name '{}' to global", sym);
let val = t.to_val()?;
let mut syms = engine.syms.borrow_mut();
let entry = &mut syms[sym.0 as usize];
if entry.bound_global.is_none() {
entry.bound_global = Some(GlobalEntry {
val,
frozen: false
});
Ok(())
} else {
let name = entry.name.clone();
drop(entry);
drop(syms);
bail!("attempted to bind the global '{}', which is already bound", name)
}
})
}
/** Equivalent to [`(del-global! s)`](https://gamelisp.rs/std/del-global-mut). */
pub fn del_global<S>(s: S) -> GResult<()>
where
S: ToSym
{
with_engine(|engine| {
let sym = s.to_sym()?;
let mut syms = engine.syms.borrow_mut();
let entry = &mut syms[sym.0 as usize];
if let Some(ref mut global) = entry.bound_global {
ensure!(!global.frozen, "attempted to unbind '{}', which is frozen", entry.name);
entry.bound_global = None;
Ok(())
} else {
let name = entry.name.clone();
drop(entry);
drop(syms);
bail!("attempted to unbind '{}', which is not bound to a global", name)
}
})
}
//---------------------------------------------------------------------------------------------
// macros
//---------------------------------------------------------------------------------------------
/** Equivalent to [`(macro s)`](https://gamelisp.rs/std/macro). */
pub fn get_macro<S: ToSym>(s: S) -> GResult<Expander> {
with_engine(|engine| {
let sym = s.to_sym()?;
match engine.syms.borrow()[sym.0 as usize].bound_macro {
Some(ref expander) => Ok(expander.clone()),
None => bail!("symbol {} is not bound to a macro", sym)
}
})
}
/** Equivalent to [`(= (macro s) expander)`](https://gamelisp.rs/std/set-macro). */
pub fn set_macro<S: ToSym>(s: S, expander: Expander) -> GResult<()> {
with_engine(|engine| {
let sym = s.to_sym()?;
let mut syms = engine.syms.borrow_mut();
match syms[sym.0 as usize].bound_macro {
Some(ref mut storage) => {
*storage = expander;
Ok(())
}
None => {
drop(syms);
bail!("symbol {} is not bound to a macro", sym)
}
}
})
}
/** Equivalent to [`(has-macro? s)`](https://gamelisp.rs/std/has-macro-p). */
pub fn has_macro<S: ToSym>(s: S) -> GResult<bool> {
with_engine(|engine| {
let sym = s.to_sym()?;
Ok(engine.syms.borrow()[sym.0 as usize].bound_macro.is_some())
})
}
/** Equivalent to [`(bind-macro! s)`](https://gamelisp.rs/std/bind-macro-mut). */
pub fn bind_macro<S: ToSym>(s: S, expander: Expander) -> GResult<()> {
with_engine(|engine| {
let sym = s.to_sym()?;
let mut syms = engine.syms.borrow_mut();
match syms[sym.0 as usize].bound_macro {
Some(_) => {
drop(syms);
bail!("attempted to bind the macro {}, which is already bound", sym)
}
ref mut storage @ None => {
*storage = Some(expander);
Ok(())
}
}
})
}
/** Equivalent to [`(del-macro! s)`](https://gamelisp.rs/std/del-macro-mut). */
pub fn del_macro<S: ToSym>(s: S) -> GResult<()> {
with_engine(|engine| {
let sym = s.to_sym()?;
let mut syms = engine.syms.borrow_mut();
match syms[sym.0 as usize].bound_macro {
ref mut storage @ Some(_) => {
*storage = None;
Ok(())
}
None => {
drop(syms);
bail!("attempted to unbind the macro {}, which is not bound", sym)
}
}
})
}
//---------------------------------------------------------------------------------------------
// filenames
//---------------------------------------------------------------------------------------------
#[doc(hidden)]
pub fn filename(st: &str) -> Filename {
with_engine(|engine| {
let mut filenames_map = engine.filenames_map.borrow_mut();
if let Some(filename) = filenames_map.get(st) {
*filename
} else {
let mut filenames = engine.filenames.borrow_mut();
//see glsp::sym() for the rationale behind panicking here
assert!(filenames.len() <= u32::MAX as usize,
"cannot load more than {} unique files", (u32::MAX as u64) + 1);
let rc = Rc::<str>::from(st);
filenames.push(Rc::clone(&rc));
let id = u32::try_from(filenames.len() - 1).unwrap();
let filename = Filename(NonZeroU32::new(id).unwrap());
filenames_map.insert(rc, filename);
filename
}
})
}
pub(crate) fn filename_str(filename: Filename) -> Rc<str> {
with_engine(|engine| {
Rc::clone(&engine.filenames.borrow()[filename.0.get() as usize])
})
}
//---------------------------------------------------------------------------------------------
// libs, rdata
//---------------------------------------------------------------------------------------------
/**
Moves a Rust value onto the garbage-collected heap.
Rust types are automatically registered with the `Runtime` when `glsp::rdata` is first called
for a value of that type. If two types share the same unprefixed name, like
`video::Clip` and `audio::Clip`, it's an error.
*/
pub fn rdata<T: RStore>(rdata: T) -> GResult<Root<RData>> {
with_engine(|engine| {
let class_rc = match engine.rclasses.borrow_mut().entry(rdata.type_id()) {
Vacant(entry) => {
let type_name = T::type_name();
ensure!(engine.rclass_names.borrow_mut().insert(&type_name),
"multiple distinct RData types share the same name: {}", type_name);
let class = Rc::new(T::rclass()?);
entry.insert(Rc::clone(&class));
class
}
Occupied(entry) => {
Rc::clone(&*entry.get())
}
};
let root = glsp::alloc(RData::new(rdata, class_rc));
root.gc_self.set(Some(root.to_gc()));
Ok(root)
})
}
/**
Moves a Rust value onto the garbage-collected heap, returning a typed pointer.
This function is a shorthand for
[`RRoot::<T>::new(glsp::rdata(rdata)?)`](struct.RRoot.html#method.new).
*/
pub fn rroot<T: RStore>(rdata: T) -> GResult<RRoot<T>> {
Ok(RRoot::new(glsp::rdata(rdata)?))
}
/**
Registers an instance of a library type.
Library types are singletons: if the active `Runtime` already contains a library of type
`T`, this function will panic.
When the active `Runtime` is dropped, each of its libraries will be dropped in the
reverse order that they were registered.
Once registered, it's possible to remove a library from the `Runtime` with
[`glsp::take_lib`](fn.take_lib.html), or borrow it with [`glsp::lib`](fn.lib.html),
[`glsp::lib_mut`](fn.lib_mut.html), [`glsp::try_lib`](fn.try_lib.html) and
[`glsp::try_lib_mut`](fn.try_lib_mut.html).
It can be more convenient to borrow a library by calling
[`T::borrow()`](trait.Lib.html#method.borrow), and other similar methods on the
[`Lib` trait](trait.Lib.html).
*/
pub fn add_lib<T: Lib>(lib: T) {
with_engine(|engine| {
let rc = Rc::new(RefCell::new(lib)) as Rc<dyn Any>;
if engine.libs.borrow_mut().insert(TypeId::of::<T>(), rc).is_some() {
panic!("glsp.add_lib() called twice for the same type");
}
engine.libs_ordering.borrow_mut().push(TypeId::of::<T>());
})
}
/**
Unregisters a value previously registered using [`glsp::add_lib`](fn.add_lib.html), and
returns it.
Returns `Err` if no library is registered for the type `T`, or if a library exists but it's
currently borrowed.
*/
pub fn take_lib<T: Lib>() -> GResult<T> {
with_engine(|engine| {
let rc = match engine.libs.borrow_mut().remove(&TypeId::of::<T>()) {
Some(rc) => rc.downcast::<RefCell<T>>().unwrap(),
None => bail!("attempted to take nonexistent lib {}", type_name::<T>())
};
match Rc::try_unwrap(rc) {
Ok(ref_cell) => Ok(ref_cell.into_inner()),
Err(_) => bail!("called take_lib for {}, which is currently borrowed",
type_name::<T>())
}
})
}
///Equivalent to [`Lib::borrow`](trait.Lib.html#method.borrow).
pub fn lib<T: Lib>() -> LibRef<T> {
match glsp::try_lib::<T>() {
Ok(lib_ref) => lib_ref,
Err(_) => panic!("attempted to access nonexistent lib {}", type_name::<T>())
}
}
///Equivalent to [`Lib::borrow_mut`](trait.Lib.html#method.borrow_mut).
pub fn lib_mut<T: Lib>() -> LibRefMut<T> {
match glsp::try_lib_mut::<T>() {
Ok(lib_ref_mut) => lib_ref_mut,
Err(_) => panic!("attempted to access nonexistent lib {}", type_name::<T>())
}
}
///Equivalent to [`Lib::try_borrow`](trait.Lib.html#method.try_borrow).
pub fn try_lib<T: Lib>() -> GResult<LibRef<T>> {
with_engine(|engine| {
let libs = engine.libs.borrow();
let rc = match libs.get(&TypeId::of::<T>()) {
Some(rc) => rc.clone(),
None => bail!("lib type {} was never registered, or has been \
dropped", type_name::<T>())
};
let rc_ref_cell = rc.downcast::<RefCell<T>>().unwrap();
if rc_ref_cell.try_borrow().is_err() {
bail!("attempted to borrow lib {} during a mutable borrow", type_name::<T>())
}
Ok(LibRef {
handle: OwningHandle::new(rc_ref_cell)
})
})
}
///Equivalent to [`Lib::try_borrow_mut`](trait.Lib.html#method.try_borrow_mut).
pub fn try_lib_mut<T: Lib>() -> GResult<LibRefMut<T>> {
with_engine(|engine| {
let libs = engine.libs.borrow();
let rc = match libs.get(&TypeId::of::<T>()) {
Some(rc) => rc.clone(),
None => bail!("lib type {} was never registered, or has been \
dropped", type_name::<T>())
};
let rc_ref_cell = rc.downcast::<RefCell<T>>().unwrap();
if rc_ref_cell.try_borrow_mut().is_err() {
bail!("attempted to mutably borrow {}, which is already borrowed", type_name::<T>())
}
Ok(LibRefMut {
handle: OwningHandle::new_mut(rc_ref_cell)
})
})
}
//---------------------------------------------------------------------------------------------
// rfns
//---------------------------------------------------------------------------------------------
/**
Creates a GameLisp value which represents a Rust function.
The `wrapped_fn` parameter should be constructed using the [`rfn!()`](macro.rfn.html) macro.
When binding a Rust function to a global variable, it's usually more convenient to use
[`glsp::bind_rfn`](fn.bind_rfn.html) instead.
Functions at the same address are deduplicated. For example, repeated calls to
`glsp::rfn("swap-bytes", i32::swap_bytes)` will return the same `RFn` every time.
*/
pub fn rfn(wrapped_fn: WrappedFn) -> RFn {
with_engine(|engine| {
let address = wrapped_fn.as_usize();
let mut rfns_map = engine.rfns_map.borrow_mut();
if let Some(rfn) = rfns_map.get(&address) {
*rfn
} else {
let mut rfns = engine.rfns.borrow_mut();
rfns.push(RFnEntry {
name: None,
wrapped_fn
});
let id = u32::try_from(rfns.len() - 1).unwrap();
let rfn = RFn(NonZeroU32::new(id).unwrap());
rfns_map.insert(address, rfn);
rfn
}
})
}
/**
Creates a GameLisp value which represents a Rust function, with a name.
This is equivalent to [`glsp::rfn`](fn.rfn.html), but
[`(fn-name rfn)`](https://gamelisp.rs/std/fn-name) will return the given symbol,
rather than returning `#n`.
*/
pub fn named_rfn(name: Sym, wrapped_fn: WrappedFn) -> RFn {
let rfn = glsp::rfn(wrapped_fn);
rfn.set_name(Some(name));
rfn
}
/**
Binds a Rust function to a global variable.
`glsp::bind_rfn(name, rfn!(f))?` is equivalent to:
let sym = name.to_sym()?
let rfn = glsp::named_rfn(sym, rfn!(f));
glsp::bind_global(sym, rfn)?;
Ok(rfn)
*/
pub fn bind_rfn<S: ToSym>(name: S, wrapped_fn: WrappedFn) -> GResult<RFn> {
let sym = name.to_sym()?;
let rfn = glsp::named_rfn(sym, wrapped_fn);
glsp::bind_global(sym, rfn)?;
Ok(rfn)
}
/**
Binds a Rust function to a global macro.
`glsp::bind_rfn_macro(name, rfn!(f))?` is equivalent to:
let sym = name.to_sym()?
let rfn = glsp::named_rfn(sym, rfn!(f));
glsp::bind_macro(sym, Expander::RFn(rfn))?;
Ok(rfn)
*/
pub fn bind_rfn_macro<S: ToSym>(name: S, wrapped_fn: WrappedFn) -> GResult<RFn> {
let sym = name.to_sym()?;
let rfn = glsp::named_rfn(sym, wrapped_fn);
glsp::bind_macro(sym, Expander::RFn(rfn))?;
Ok(rfn)
}
pub(crate) fn call_rfn(rfn: RFn, arg_count: usize) -> GResult<Slot> {
with_engine(|engine| {
/*
when invoking a wrapped rfn, we borrow the vm's reg stack, copy the useful parts of
it to the Rust callstack (as the Temps type), drop the borrow, and then invoke the
rfn. we only pop the regs after the call returns, so that they remain rooted.
*/
let stacks = engine.vm.stacks.borrow();
let base_reg = stacks.regs.len() - arg_count;
let _guard = Guard::new(|| {
let mut stacks = engine.vm.stacks.borrow_mut();
stacks.regs.truncate(base_reg);
});
let regs = Ref::map(stacks, |stacks| &stacks.regs[base_reg..]);
let wrapped_fn = engine.rfns.borrow()[rfn.0.get() as usize].wrapped_fn;
let result = panic::catch_unwind(AssertUnwindSafe(|| {
wrapped_fn.call(regs)
}));
/*
for the time being, we don't go through the rigmarole of trying to set a custom panic
hook. it's a global resource, and managing that would be annoying. instead, we allow
the normal panic hook to print its usual message, and we convert the caught panic
into a generic message without any details.
*/
match result {
Ok(glsp_result) => glsp_result,
Err(payload) => {
let rfn_description = match rfn.name() {
Some(sym) => format!("rfn ({})", sym),
None => format!("anonymous rfn")
};
if let Some(msg) = payload.downcast_ref::<&str>() {
bail!("{} panicked, '{}'", rfn_description, msg)
} else if let Some(msg) = payload.downcast_ref::<String>() {
bail!("{} panicked, '{}'", rfn_description, msg)
} else {
bail!("{} panicked", rfn_description)
}
}
}
})
}
//---------------------------------------------------------------------------------------------
// parsing and printing
//---------------------------------------------------------------------------------------------
/** Equivalent to [`(parse text filename)`](https://gamelisp.rs/std/parse). */
pub fn parse(text: &mut &str, filename: Option<&str>) -> GResult<Option<Val>> {
let file_id = filename.map(|path| glsp::filename(path));
let mut parser = Parser::new(file_id);
glsp::push_frame(Frame::GlspApi(GlspApiName::Parse, file_id));
let _guard = Guard::new(|| glsp::pop_frame());
while text.len() > 0 {
if let Some(form) = parser.parse(text)? {
return Ok(Some(form))
}
}
parser.ensure_finished()?;
Ok(None)
}
/** Equivalent to [`(parse-all text filename)`](https://gamelisp.rs/std/parse-all). */
pub fn parse_all(mut text: &str, filename: Option<&str>) -> GResult<Vec<Val>> {
let file_id = filename.map(|path| glsp::filename(path));
glsp::push_frame(Frame::GlspApi(GlspApiName::ParseAll, file_id));
let _guard = Guard::new(|| glsp::pop_frame());
let mut parser = Parser::new(file_id);
let mut results = Vec::new();
while text.len() > 0 {
if let Some(form) = parser.parse(&mut text)? {
results.push(form);
}
}
parser.ensure_finished()?;
Ok(results)
}
/** Equivalent to [`(parse-1 text filename)`](https://gamelisp.rs/std/parse-1). */
pub fn parse_1(mut text: &str, filename: Option<&str>) -> GResult<Val> {
let file_id = filename.map(|path| glsp::filename(path));
glsp::push_frame(Frame::GlspApi(GlspApiName::Parse1, file_id));
let _guard = Guard::new(|| glsp::pop_frame());
let mut parser = Parser::new(file_id);
while text.len() > 0 {
if let Some(form) = parser.parse(&mut text)? {
while text.len() > 0 {
if let Some(_) = parser.parse(&mut text)? {
bail!("parse-1 produced multiple forms")
}
}
return Ok(form)
}
}
bail!("parse-1 did not produce a form")
}
/**
Changes the output writer used by [`pr`](https://gamelisp.rs/std/pr),
[`prn`](https://gamelisp.rs/std/prn), [`pr!`](macro.pr.html) and
[`prn!`](macro.prn.html).
The default writer is [`Stdout`](https://doc.rust-lang.org/std/io/struct.Stdout.html). Note
that calling `glsp::set_pr_writer` will not redirect the output of Rust macros like
[`println!`](https://doc.rust-lang.org/std/macro.println.html): for that, you would need
to use the undocumented feature [`set_print`](https://github.com/rust-lang/rust/issues/31343).
//silences pr!(), prn!(), pr and prn
glsp::set_pr_writer(Box::new(std::io::sink()));
*/
pub fn set_pr_writer(pr_writer: Box<dyn Write>) {
with_engine(|engine| {
*engine.pr_writer.borrow_mut() = pr_writer;
})
}
/**
Changes the output writer used by [`epr`](https://gamelisp.rs/std/epr),
[`eprn`](https://gamelisp.rs/std/eprn), [`epr!`](macro.epr.html) and
[`eprn!`](macro.eprn.html).
That same writer is also used by GameLisp to print a stack trace when an error is
not caught.
The default writer is [`Stderr`](https://doc.rust-lang.org/std/io/struct.Stderr.html). Note
that calling `glsp::set_epr_writer` will not redirect the output of Rust macros like
[`panic!`](https://doc.rust-lang.org/std/macro.panic.html) or
[`eprintln!`](https://doc.rust-lang.org/std/macro.eprintln.html): for that, you would need
to use the undocumented feature [`set_panic`](https://github.com/rust-lang/rust/issues/31343).
//silences error-reporting, epr!(), eprn!(), epr and eprn
glsp::set_pr_writer(Box::new(std::io::sink()));
*/
pub fn set_epr_writer(epr_writer: Box<dyn Write>) {
with_engine(|engine| {
*engine.epr_writer.borrow_mut() = epr_writer;
})
}
//---------------------------------------------------------------------------------------------
// spans and stack-tracing
//---------------------------------------------------------------------------------------------
pub(crate) fn push_frame(frame: Frame) {
with_engine(|engine| {
engine.vm.push_frame(frame);
})
}
pub(crate) fn pop_frame() {
with_engine(|engine| {
engine.vm.pop_frame();
})
}
pub(crate) fn enter_expander(arr: &Arr, env: Rc<Env>) -> Option<(Option<Sym>, Span, Rc<Env>)> {
with_engine(|engine| {
let name = if arr.len() >= 1 && arr.get::<Val>(0).unwrap().is_sym() {
Some(arr.get::<Sym>(0).unwrap())
} else {
None
};
let callsite = arr.span();
let prev_in_expander = engine.in_expander.borrow().clone();
*engine.in_expander.borrow_mut() = Some((name, callsite, env));
prev_in_expander
})
}
pub(crate) fn env() -> Option<Rc<Env>> {
with_engine(|engine| {
match *engine.in_expander.borrow() {
Some((_, _, ref env)) => Some(Rc::clone(env)),
None => None
}
})
}
pub(crate) fn leave_expander(prev: Option<(Option<Sym>, Span, Rc<Env>)>) {
with_engine(|engine| {
*engine.in_expander.borrow_mut() = prev;
})
}
pub(crate) fn span(storage: SpanStorage) -> Span {
with_engine(|engine| {
if storage == SpanStorage::Generated {
Span(0)
} else {
let mut spans_map = engine.spans_map.borrow_mut();
match spans_map.entry(storage) {
Occupied(entry) => *entry.get(),
Vacant(entry) => {
let mut spans = engine.spans.borrow_mut();
spans.push(storage);
let span = Span((spans.len() - 1) as u32);
entry.insert(span);
span
}
}
}
})
}
pub(crate) fn generated_span() -> Span {
Span(0)
}
pub(crate) fn span_storage(span: Span) -> SpanStorage {
with_engine(|engine| {
engine.spans.borrow()[span.0 as usize]
})
}
//simplifies a Span into a brief file location, e.g. "scripts/main.glsp:10". only used by (try)
//and (file-location). if this span was Loaded from a file, or transitively expanded from a
//macro callsite which was itself Loaded from a file, writes the file location to `f` and
//returns Ok(true). otherwise, returns Ok(false).
pub(crate) fn span_file_location<F>(f: &mut F, mut span: Span) -> Result<bool, fmt::Error>
where
F: fmt::Write
{
loop {
match glsp::span_storage(span) {
SpanStorage::Expanded(_, macro_invocation_span, _) => {
span = macro_invocation_span;
}
SpanStorage::Loaded(file_id, line) => {
write!(f, "{}:{}", &glsp::filename_str(file_id), line)?;
return Ok(true)
}
SpanStorage::Generated => {
return Ok(false)
}
}
}
}
//span_context outputs a description of a single Span to surround a gfn call, rfn call, or
//bail_at!() in a stack trace. e.g.:
//
// (some-macro) at scripts/main.glsp:10
// expanded to (other-macro) at scripts/main.glsp:20
// expanded to (some-call) at scripts/main.glsp:30
//
pub(crate) fn span_context<F, C>(
f: &mut F,
span: Span,
callback: &C
) -> fmt::Result
where
F: fmt::Write,
C: ?Sized + Fn(&mut F) -> fmt::Result
{
match glsp::span_storage(span) {
SpanStorage::Generated => {
callback(f)?;
}
SpanStorage::Loaded(file_id, line_number) => {
callback(f)?;
write!(f, " at {}:{}", &glsp::filename_str(file_id), line_number)?;
}
SpanStorage::Expanded(macro_name, expander_callsite, mut constructor_callsite) => {
let print_macro_name: &dyn Fn(&mut F) -> fmt::Result = &|f| {
match macro_name {
Some(macro_name) => write!(f, "({})", macro_name),
None => write!(f, "an anonymous macro")
}
};
span_context(f, expander_callsite, print_macro_name)?;
write!(f, "\n expanded to ")?;
callback(f)?;
//within a macro, it's possible that arr constructors may be themselves expanded
//from a macro. we could potentially recurse in that case, but for now we just
//report the macro invocation's own constructor site as the construction site.
while let SpanStorage::Expanded(_, _, meta) =
glsp::span_storage(constructor_callsite) {
constructor_callsite = meta;
}
match glsp::span_storage(constructor_callsite) {
SpanStorage::Generated => (),
SpanStorage::Loaded(file_id, line_number) => {
write!(f, " at {}:{}", &glsp::filename_str(file_id), line_number)?;
}
SpanStorage::Expanded(..) => unreachable!()
}
}
}
Ok(())
}
/** Equivalent to [`(file-location)`](https://gamelisp.rs/std/file-location). */
//error messages can be stringified in either a short form, or a long form (a stack trace).
//the short form is a brief file location, followed by the stringification of the arguments
//passed to bail!(), ensure!() or (err). this method generates that brief file location.
//the user can also generate this directly using the (file-location) builtin fn.
pub fn file_location() -> Option<String> {
with_engine(|engine| {
let mut builder = String::new();
if engine.vm.file_location(&mut builder).unwrap() {
Some(builder)
} else {
None
}
})
}
/** Equivalent to [`(stack-trace)`](https://gamelisp.rs/std/stack-trace). */
//this method generates the long form: a full stack trace. we don't emit any leading or
//trailing linebreaks.
pub fn stack_trace() -> String {
with_engine(|engine| {
let mut builder = String::new();
engine.vm.stack_trace(&mut builder).unwrap();
builder
})
}
//---------------------------------------------------------------------------------------------
// try
//---------------------------------------------------------------------------------------------
/**
Calls a function with either verbose or brief error-reporting.
[`try`](https://gamelisp.rs/std/try) and [`try-verbose`](https://gamelisp.rs/std/try-verbose)
work by invoking `glsp::try_call`.
The default error-reporting style is verbose.
*/
pub fn try_call<R, A>(is_verbose: bool, receiver: &R, args: &A) -> GResult<Val>
where
R: CallableOps,
A: ToCallArgs + ?Sized
{
with_engine(|engine| {
let prev = engine.errors_verbose.get();
engine.errors_verbose.set(is_verbose);
let _guard = Guard::new(|| engine.errors_verbose.set(prev));
glsp::call(receiver, args)
})
}
pub(crate) fn errors_verbose() -> bool {
with_engine(|engine| {
engine.errors_verbose.get()
})
}
//---------------------------------------------------------------------------------------------
// allocation
//---------------------------------------------------------------------------------------------
pub(crate) fn alloc<T: Allocate>(t: T) -> Root<T> {
with_engine(|engine| {
engine.heap.alloc(t)
})
}
#[doc(hidden)]
pub fn alloc_gc<T: Allocate>(t: T) -> Gc<T> {
with_engine(|engine| {
engine.heap.alloc_gc(t)
})
}
//returns the Span which should be assigned to a newly-allocated arr, allocated at `callsite`
pub(crate) fn new_arr_span(callsite: Option<Span>) -> Span {
with_engine(|engine| {
if let Some(callsite) = callsite {
if let Some((expander_name, expander_callsite, _)) = *engine.in_expander.borrow() {
glsp::span(SpanStorage::Expanded(expander_name, expander_callsite, callsite))
} else {
Span::default()
}
} else {
if engine.vm.in_expander() {
//when `callsite` is None, that means the arr is being allocated by a call
//to glsp::arr(), glsp::call(), etc., rather than an OpArr instr or something
//else which can pass in an explicit "current span". under those circumstances,
//the innermost available Span will be the callsite of the innermost active
//gfn/rfn call, if any, within the innermost expander - or the callsite of
//the expander itself, otherwise.
//possible future extension (todo) would be to add a type of Span which refers
//to a line of rust code, rather than a line of glsp code. couldn't use this
//for glsp::call, but we could use it for macros like arr![] and backquote!().
engine.vm.expander_cur_span()
} else {
Span::default()
}
}
})
}
///Constructs an empty [array](struct.Arr.html).
pub fn arr() -> Root<Arr> {
let arr = with_heap(|heap| heap.recycler.arr());
arr.set_span(glsp::new_arr_span(None));
arr
}
///Constructs an empty [array](struct.Arr.html) with space for at least `capacity` elements.
pub fn arr_with_capacity(capacity: usize) -> Root<Arr> {
let arr = with_heap(|heap| heap.recycler.arr_with_capacity(capacity));
arr.set_span(glsp::new_arr_span(None));
arr
}
/**
Constructs an [array](struct.Arr.html) which contains `reps` repetitions of `elem`.
Returns an `Err` if [type conversion](trait.ToVal.html) fails.
*/
pub fn arr_from_elem<T: ToVal>(elem: T, reps: usize) -> GResult<Root<Arr>> {
let arr = with_heap(|heap| heap.recycler.arr_from_elem(elem, reps))?;
arr.set_span(glsp::new_arr_span(None));
Ok(arr)
}
/**
Constructs an [array](struct.Arr.html) from the contents of a Rust iterator.
Returns an `Err` if [type conversion](trait.ToVal.html) fails for any element.
*/
pub fn arr_from_iter<T>(iter: T) -> GResult<Root<Arr>>
where
T: IntoIterator,
T::Item: ToVal
{
let arr = with_heap(|heap| heap.recycler.arr_from_iter(iter))?;
arr.set_span(glsp::new_arr_span(None));
Ok(arr)
}
///Constructs an empty [string](struct.Str.html).
pub fn str() -> Root<Str> {
glsp::alloc(Str::new())
}
///Constructs an empty [string](struct.Str.html) with the same contents as a Rust string slice.
pub fn str_from_rust_str(src: &str) -> Root<Str> {
glsp::alloc(Str::from_rust_str(src))
}
/**
Constructs a [string](struct.Str.html) from the characters in a Rust iterator.
Returns an `Err` if [type conversion](trait.IntoElement.html) fails for any element.
*/
pub fn str_from_iter<T>(iter: T) -> GResult<Root<Str>>
where
T: IntoIterator,
T::Item: IntoElement<char>
{
Ok(glsp::alloc(Str::from_iter(iter)?))
}
///Constructs an empty [string](struct.Str.html) with space for at least `capacity` characters.
pub fn str_with_capacity(capacity: usize) -> Root<Str> {
glsp::alloc(Str::with_capacity(capacity))
}
///Constructs an empty [table](struct.Tab.html).
pub fn tab() -> Root<Tab> {
glsp::alloc(Tab::new())
}
/**
Constructs a [table](struct.Tab.html) from the key/value pairs in a Rust iterator.
Duplicate keys are permitted.
Returns an `Err` if [type conversion](trait.ToVal.html) fails for any key or value.
*/
pub fn tab_from_iter<T, K, V>(iter: T) -> GResult<Root<Tab>>
where
T: IntoIterator<Item = (K, V)>,
K: ToVal,
V: ToVal
{
Ok(glsp::alloc(Tab::from_iter(iter)?))
}
///Constructs an empty [table](struct.Tab.html) with space for at least `capacity` elements.
pub fn tab_with_capacity(capacity: usize) -> Root<Tab> {
glsp::alloc(Tab::with_capacity(capacity))
}
#[doc(hidden)]
pub fn class(raw_class: &Tab) -> GResult<Root<Class>> {
Ok(glsp::alloc(Class::new(raw_class)?))
}
pub(crate) fn call_class(class: &Root<Class>, arg_count: usize) -> GResult<Root<Obj>> {
with_engine(|engine| {
//the simplest way to implement this (but not the most performant - todo fix) is
//to collect the arguments into a SmallVec. we leave them on the stack until the
//constructor returns, so that they stay rooted.
let stacks = engine.vm.stacks.borrow();
let base_reg = stacks.regs.len() - arg_count;
let _guard = Guard::new(|| {
let mut stacks = engine.vm.stacks.borrow_mut();
stacks.regs.truncate(base_reg);
});
let mut args = SmallVec::<[Slot; 16]>::new();
for i in base_reg .. stacks.regs.len() {
//this particular incantation is much faster than iter().cloned() for some reason
args.push(stacks.regs[i].clone());
}
drop(stacks);
Obj::new(class, &args[..])
})
}
//---------------------------------------------------------------------------------------------
// iterators
//---------------------------------------------------------------------------------------------
pub(crate) fn giter(state: GIterState) -> Root<GIter> {
with_heap(|heap| heap.recycler.giter(state))
}
/** Equivalent to [`(rn start end step-by)`](https://gamelisp.rs/std/rn). */
pub fn rn(start: Num, end: Option<Num>, step_by: Num) -> GResult<Root<GIter>> {
ensure!(step_by != Num::Int(0), "a range can't be stepped by 0");
match (start, end, step_by) {
(Num::Int(start), Some(Num::Int(end)), Num::Int(step_by)) => {
Ok(glsp::giter(GIterState::RnExclusive(start, end, step_by)))
}
(Num::Int(start), None, Num::Int(step_by)) => {
Ok(glsp::giter(GIterState::RnOpen(start, step_by)))
}
(start, Some(end), step_by) => {
Ok(glsp::giter(GIterState::FRnExclusive(
start.into_f32(),
end.into_f32(),
step_by.into_f32())))
}
(start, None, step_by) => {
Ok(glsp::giter(GIterState::FRnOpen(start.into_f32(), step_by.into_f32())))
}
}
}
/** Equivalent to [`(rni start end step-by)`](https://gamelisp.rs/std/rni). */
pub fn rni(start: Num, end: Option<Num>, step_by: Num) -> GResult<Root<GIter>> {
ensure!(step_by != Num::Int(0), "a range can't be stepped by 0");
match (start, end, step_by) {
(Num::Int(start), Some(Num::Int(end)), Num::Int(step_by)) => {
Ok(glsp::giter(GIterState::RnInclusive(start, end, step_by)))
}
(Num::Int(start), None, Num::Int(step_by)) => {
Ok(glsp::giter(GIterState::RnOpen(start, step_by)))
}
(start, Some(end), step_by) => {
Ok(glsp::giter(GIterState::FRnInclusive(
start.into_f32(),
end.into_f32(),
step_by.into_f32())))
}
(start, None, step_by) => {
Ok(glsp::giter(GIterState::FRnOpen(start.into_f32(), step_by.into_f32())))
}
}
}
/** Equivalent to [`(once ..args)`](https://gamelisp.rs/std/once). */
pub fn once(args: &[Val]) -> Root<GIter> {
match args.len() {
0 => glsp::giter(GIterState::Empty),
1 => glsp::giter(GIterState::Once1(Slot::from_val(&args[0]))),
_ => {
let arr = glsp::arr_from_iter(args.iter()).unwrap();
glsp::giter(GIterState::OnceN(arr.to_gc()))
}
}
}
/** Equivalent to [`(once-with f)`](https://gamelisp.rs/std/once-with). */
pub fn once_with(callable: Callable) -> Root<GIter> {
glsp::giter(GIterState::OnceWith(GcCallable::from_callable(&callable)))
}
/** Equivalent to [`(repeat ..args)`](https://gamelisp.rs/std/repeat). */
pub fn repeat(args: &[Val]) -> GResult<Root<GIter>> {
match args.len() {
0 => bail!("the repeat iterator requires at least one argument"),
1 => Ok(glsp::giter(GIterState::Repeat1(Slot::from_val(&args[0])))),
_ => {
let arr = glsp::arr_from_iter(args.iter()).unwrap();
Ok(glsp::giter(GIterState::RepeatN(arr.to_gc(), 0, (arr.len() - 1) as u32)))
}
}
}
/** Equivalent to [`(repeat-with f)`](https://gamelisp.rs/std/repeat-with). */
pub fn repeat_with(callable: Callable) -> Root<GIter> {
glsp::giter(GIterState::RepeatWith(GcCallable::from_callable(&callable)))
}
/** Equivalent to [`(chunks len src-arr)`](https://gamelisp.rs/std/chunks). */
pub fn chunks(chunk_len: usize, src_arr: &Root<Arr>) -> GResult<Root<GIter>> {
ensure!(chunk_len > 0, "cannot split an array into chunks of length 0");
Ok(glsp::giter(GIterState::Chunks(chunk_len as u32, src_arr.shallow_clone().to_gc())))
}
/** Equivalent to [`(chunks-exact len src-arr)`](https://gamelisp.rs/std/chunks-exact). */
pub fn chunks_exact(chunk_len: usize, src_arr: &Root<Arr>) -> GResult<Root<GIter>> {
ensure!(chunk_len > 0, "cannot split an array into chunks of length 0");
let len = src_arr.len() - (src_arr.len() % chunk_len);
let arr = glsp::arr_from_iter(src_arr.iter().take(len)).unwrap();
Ok(glsp::giter(GIterState::Chunks(chunk_len as u32, arr.to_gc())))
}
/** Equivalent to [`(rchunks len src-arr)`](https://gamelisp.rs/std/rchunks). */
pub fn rchunks(chunk_len: usize, src_arr: &Root<Arr>) -> GResult<Root<GIter>> {
ensure!(chunk_len > 0, "cannot split an array into chunks of length 0");
Ok(glsp::giter(GIterState::RChunks(chunk_len as u32, src_arr.shallow_clone().to_gc())))
}
/** Equivalent to [`(rchunks-exact len src-arr)`](https://gamelisp.rs/std/rchunks-exact). */
pub fn rchunks_exact(chunk_len: usize, src_arr: &Root<Arr>) -> GResult<Root<GIter>> {
ensure!(chunk_len > 0, "cannot split an array into chunks of length 0");
let to_skip = src_arr.len() % chunk_len;
let arr = glsp::arr_from_iter(src_arr.iter().skip(to_skip)).unwrap();
Ok(glsp::giter(GIterState::RChunks(chunk_len as u32, arr.to_gc())))
}
/** Equivalent to [`(windows len src-arr)`](https://gamelisp.rs/std/windows). */
pub fn windows(window_len: usize, src_arr: &Root<Arr>) -> GResult<Root<GIter>> {
ensure!(window_len > 0, "cannot split an array into windows of length 0");
Ok(glsp::giter(GIterState::Windows(window_len as u32, src_arr.shallow_clone().to_gc())))
}
/** Equivalent to [`(lines st)`](https://gamelisp.rs/std/lines). */
pub fn lines(st: &Root<Str>) -> Root<GIter> {
glsp::giter(GIterState::Lines(st.shallow_clone().to_gc()))
}
/** Equivalent to [`(split st split-at)`](https://gamelisp.rs/std/split). */
pub fn split(src: &Root<Str>, split_at: &Root<Str>) -> Root<GIter> {
glsp::giter(GIterState::Split(src.shallow_clone().to_gc(),
split_at.shallow_clone().to_gc()))
}
/** Equivalent to [`(rev base)`](https://gamelisp.rs/std/rev). */
pub fn rev(base: &Root<GIter>) -> GResult<Root<GIter>> {
ensure!(base.is_double_ended(), "{} iterators are not double-ended", base.state_name());
Ok(glsp::giter(GIterState::Rev(base.to_gc())))
}
/** Equivalent to [`(enumerate base)`](https://gamelisp.rs/std/enumerate). */
pub fn enumerate(base: &Root<GIter>) -> Root<GIter> {
glsp::giter(GIterState::Enumerate(base.to_gc(), 0))
}
/** Equivalent to [`(cloned base)`](https://gamelisp.rs/std/cloned). */
pub fn cloned(base: &Root<GIter>) -> Root<GIter> {
glsp::giter(GIterState::Cloned(base.to_gc()))
}
/** Equivalent to [`(deep-cloned base)`](https://gamelisp.rs/std/deep-cloned). */
pub fn deep_cloned(base: &Root<GIter>) -> Root<GIter> {
glsp::giter(GIterState::DeepCloned(base.to_gc()))
}
/** Equivalent to [`(step-by n base)`](https://gamelisp.rs/std/step-by). */
pub fn step_by(step_by: usize, base: &Root<GIter>) -> GResult<Root<GIter>> {
ensure!(step_by > 0, "cannot step an iterator by 0");
Ok(glsp::giter(GIterState::StepBy(step_by as u32, base.to_gc())))
}
/** Equivalent to [`(map f base)`](https://gamelisp.rs/std/map). */
pub fn map(callable: &Callable, base: &Root<GIter>) -> Root<GIter> {
glsp::giter(GIterState::Map(GcCallable::from_callable(callable), base.to_gc()))
}
/** Equivalent to [`(filter f base)`](https://gamelisp.rs/std/filter). */
pub fn filter(callable: &Callable, base: &Root<GIter>) -> Root<GIter> {
glsp::giter(GIterState::Filter(GcCallable::from_callable(callable), base.to_gc()))
}
/** Equivalent to [`(zip ..args)`](https://gamelisp.rs/std/zip). */
pub fn zip(iterables: &[Iterable]) -> Root<GIter> {
let arr = glsp::arr_from_iter(iterables.iter().map(|iterable| iterable.giter())).unwrap();
glsp::giter(GIterState::Zip(arr.to_gc()))
}
/** Equivalent to [`(chain ..args)`](https://gamelisp.rs/std/chain). */
pub fn chain(iterables: &[Iterable]) -> Root<GIter> {
let arr = glsp::arr_from_iter(iterables.iter().map(|iterable| iterable.giter())).unwrap();
glsp::giter(GIterState::Chain(arr.to_gc()))
}
/** Equivalent to [`(flatten base)`](https://gamelisp.rs/std/flatten). */
pub fn flatten(base: &Root<GIter>) -> Root<GIter> {
glsp::giter(GIterState::Flatten(base.to_gc(), None))
}
/** Equivalent to [`(cycle base)`](https://gamelisp.rs/std/cycle). */
pub fn cycle(base: &Root<GIter>) -> Root<GIter> {
glsp::giter(GIterState::Cycle(Some(base.to_gc()), glsp::arr().to_gc(), 0))
}
/** Equivalent to [`(take n base)`](https://gamelisp.rs/std/take). */
pub fn take(n: usize, base: &Root<GIter>) -> Root<GIter> {
glsp::giter(GIterState::Take(n as u32, base.to_gc()))
}
/** Equivalent to [`(take-while f base)`](https://gamelisp.rs/std/take-while). */
pub fn take_while(callable: &Callable, base: &Root<GIter>) -> Root<GIter> {
glsp::giter(GIterState::TakeWhile(GcCallable::from_callable(callable), base.to_gc()))
}
/** Equivalent to [`(skip n base)`](https://gamelisp.rs/std/skip). */
pub fn skip(n: usize, base: &Root<GIter>) -> Root<GIter> {
glsp::giter(GIterState::Skip(n as u32, base.to_gc()))
}
/** Equivalent to [`(skip-while f base)`](https://gamelisp.rs/std/skip-while). */
pub fn skip_while(callable: &Callable, base: &Root<GIter>) -> Root<GIter> {
let gc_callable = GcCallable::from_callable(callable);
glsp::giter(GIterState::SkipWhile(Some(gc_callable), base.to_gc()))
}
//---------------------------------------------------------------------------------------------
// garbage collection
//---------------------------------------------------------------------------------------------
/** Equivalent to [`(gc)`](https://gamelisp.rs/std/gc). */
pub fn gc() {
with_engine(|engine| {
engine.vm.traverse_stacks();
engine.heap.step()
})
}
/** Equivalent to [`(gc-value 'ratio)`](https://gamelisp.rs/std/gc-value). */
pub fn gc_ratio() -> f32 {
with_engine(|engine| {
engine.heap.ratio()
})
}
/** Equivalent to [`(= (gc-value 'ratio) ratio)`](https://gamelisp.rs/std/set-gc-value). */
pub fn gc_set_ratio(ratio: f32) {
with_engine(|engine| {
engine.heap.set_ratio(ratio)
})
}
/** Equivalent to [`(gc-value 'young-bytes)`](https://gamelisp.rs/std/gc-value). */
pub fn gc_young_bytes() -> usize {
with_engine(|engine| {
engine.heap.young_memory_usage()
})
}
/** Equivalent to [`(gc-value 'old-bytes)`](https://gamelisp.rs/std/gc-value). */
pub fn gc_old_bytes() -> usize {
with_engine(|engine| {
engine.heap.old_memory_usage()
})
}
/** Equivalent to [`(gc-value 'ghost-bytes)`](https://gamelisp.rs/std/gc-value). */
pub fn gc_ghost_bytes() -> usize {
with_engine(|engine| {
engine.heap.ghost_memory_usage()
})
}
//---------------------------------------------------------------------------------------------
// evaluation and expansion
//---------------------------------------------------------------------------------------------
/** Equivalent to [`(eval val env-mode)`](https://gamelisp.rs/std/eval). */
pub fn eval(val: &Val, env_mode: Option<EnvMode>) -> GResult<Val> {
glsp::push_frame(Frame::GlspApi(GlspApiName::Eval, None));
let _guard = Guard::new(|| glsp::pop_frame());
eval::eval(&[val.clone()], env_mode, false)
}
/** Equivalent to [`(eval-multi vals env-mode)`](https://gamelisp.rs/std/eval-multi). */
pub fn eval_multi(vals: &[Val], env_mode: Option<EnvMode>) -> GResult<Val> {
glsp::push_frame(Frame::GlspApi(GlspApiName::EvalMulti, None));
let _guard = Guard::new(|| glsp::pop_frame());
eval::eval(vals, env_mode, false)
}
/** Equivalent to [`(load filename)`](https://gamelisp.rs/std/load). */
pub fn load(filename: &str) -> GResult<Val> {
let file_id = glsp::filename(filename);
glsp::push_frame(Frame::GlspApi(GlspApiName::Load, Some(file_id)));
let _guard = Guard::new(|| glsp::pop_frame());
#[cfg(feature = "compiler")] {
if is_playing_back() {
return glsp::load_playback(filename)
} else {
glsp::record_action(Action::StartLoad(file_id));
}
}
#[cfg(feature = "compiler")]
let _guard = Guard::new(|| glsp::record_action(Action::EndLoad));
let text = match fs::read_to_string(&filename) {
Ok(text) => text,
Err(err) => return Err(error!("unable to load file '{}'", filename).with_source(err))
};
let vals = glsp::parse_all(&text, Some(filename))?;
eval::eval(&vals, None, true)
}
/** Equivalent to [`(require filename)`](https://gamelisp.rs/std/require). */
pub fn require(filename: &str) -> GResult<Val> {
let file_id = glsp::filename(filename);
glsp::push_frame(Frame::GlspApi(GlspApiName::Require, Some(file_id)));
let _guard = Guard::new(|| glsp::pop_frame());
let path = match PathBuf::from(filename).canonicalize() {
Ok(path) => path,
Err(err) => {
let msg = error!("invalid filename '{}' passed to glsp::require", filename);
return Err(msg.with_source(err))
}
};
let already_seen = with_engine(|engine| {
let mut required = engine.required.borrow_mut();
if required.contains(&path) {
return true
} else {
required.insert(path);
return false
}
});
if already_seen {
Ok(Val::Nil)
} else {
glsp::load(filename)
}
}
/**
Loads a file and serializes its compiled bytecode to a `Vec<u8>`.
See the [Compilation](https://gamelisp.rs/reference/compilation.html) chapter of the
manual for more details.
*/
#[cfg(feature = "compiler")]
pub fn load_and_compile(filename: &str) -> GResult<(Val, Vec<u8>)> {
let file_id = glsp::filename(filename);
glsp::push_frame(Frame::GlspApi(GlspApiName::LoadAndCompile, Some(file_id)));
let _guard = Guard::new(|| glsp::pop_frame());
let text = match fs::read_to_string(&filename) {
Ok(text) => text,
Err(err) => return Err(error!("unable to load file '{}'", filename).with_source(err))
};
glsp::load_and_compile_str(&text, filename)
}
#[doc(hidden)]
#[cfg(feature = "compiler")]
pub fn load_and_compile_str(
content: &str,
filename: &str
) -> GResult<(Val, Vec<u8>)> {
let file_id = glsp::filename(filename);
glsp::push_frame(Frame::GlspApi(GlspApiName::LoadAndCompileStr, Some(file_id)));
let _guard = Guard::new(|| glsp::pop_frame());
let vals = glsp::parse_all(content, Some(filename))?;
glsp::load_and_compile_vals(&vals[..], filename)
}
#[doc(hidden)]
#[cfg(feature = "compiler")]
pub fn load_and_compile_vals(
vals: &[Val],
filename: &str
) -> GResult<(Val, Vec<u8>)> {
let file_id = glsp::filename(filename);
glsp::push_frame(Frame::GlspApi(GlspApiName::LoadAndCompileVals, Some(file_id)));
let _guard = Guard::new(|| glsp::pop_frame());
with_engine(|engine| {
ensure!(engine.playing_back.borrow().is_none(),
"cannot load_and_compile and load_compiled simultaneously");
let mut recording = engine.recording.borrow_mut();
ensure!(recording.is_none(), "multiple simultaneous calls to load_and_compile");
*recording = Some(Recording::new());
Ok(())
})?;
let recording_guard = Guard::new(|| {
with_engine(|engine| {
*engine.recording.borrow_mut() = None;
})
});
glsp::seed_gensym();
glsp::record_action(Action::StartLoad(file_id));
let end_load_guard = Guard::new(|| glsp::record_action(Action::EndLoad));
let result = eval::eval(vals, None, true)?;
forget(recording_guard);
drop(end_load_guard);
let bytes = with_engine(|engine| {
engine.recording.borrow_mut().take().unwrap().into_bytes()
});
Ok((result, bytes))
}
#[cfg(feature = "compiler")]
pub(crate) fn record_action(action: Action) {
with_engine(|engine| {
let mut recording = engine.recording.borrow_mut();
if let Some(ref mut recording) = *recording {
recording.add_action(action);
}
});
}
#[cfg(feature = "compiler")]
pub(crate) fn is_playing_back() -> bool {
with_engine(|engine| {
engine.playing_back.borrow().is_some()
})
}
#[cfg(feature = "compiler")]
pub(crate) fn pop_action() -> GResult<Action> {
with_engine(|engine| {
engine.playing_back.borrow_mut().as_mut().unwrap().pop()
})
}
/**
Loads a file which was previously serialized using
[`glsp::load_and_compile`](fn.load_and_compile.html).
See the [Compilation](https://gamelisp.rs/reference/compilation.html) chapter of the
manual for more details.
*/
#[cfg(feature = "compiler")]
pub fn load_compiled(bytes: &[u8]) -> GResult<Val> {
glsp::push_frame(Frame::GlspApi(GlspApiName::LoadCompiled, None));
let _guard = Guard::new(|| glsp::pop_frame());
let recording = Recording::from_bytes(bytes)?;
let root_filename = match recording.peek()? {
&Action::StartLoad(filename) => filename,
_ => bail!("invalid Recording: first Action must be StartLoad")
};
with_engine(|engine| {
ensure!(engine.recording.borrow().is_none(),
"cannot load_and_compile and load_compiled simultaneously");
let mut playing_back = engine.playing_back.borrow_mut();
ensure!(playing_back.is_none(), "multiple simultaneous calls to load_compiled");
*playing_back = Some(recording);
Ok(())
})?;
let playing_back_guard = Guard::new(|| {
with_engine(|engine| {
*engine.playing_back.borrow_mut() = None;
});
});
let result = glsp::load_playback(&glsp::filename_str(root_filename))?;
forget(playing_back_guard);
let recording = with_engine(|engine| {
engine.playing_back.borrow_mut().take().unwrap()
});
ensure!(recording.is_empty(), "invalid Recording: some Actions are unused");
Ok(result)
}
//glsp::load delegates to this function when glsp::is_playing_back() is true.
#[cfg(feature = "compiler")]
pub(crate) fn load_playback(expected_filename: &str) -> GResult<Val> {
assert!(glsp::is_playing_back());
match glsp::pop_action()? {
Action::StartLoad(recorded_filename)
if expected_filename == &*glsp::filename_str(recorded_filename) => (),
_ => bail!("invalid Recording: unexpected call to (load {:?})", expected_filename)
}
let mut result = Val::Nil;
let mut toplevel_let: Option<Root<Stay>> = None;
loop {
match glsp::pop_action()? {
Action::Execute(bytecode) => {
with_vm(|vm| {
result = vm.exec_bytecode(&bytecode)?;
Ok(())
})?;
if let Some(stay) = toplevel_let.take() {
stay.set(Slot::from_val(&result));
result = Val::Nil;
}
}
Action::ToplevelLet(stay) => {
ensure!(toplevel_let.is_none(), "invalid Recording: unexpected ToplevelLet");
toplevel_let = Some(stay);
}
Action::StartLoad(filename) => {
bail!("invalid Recording: unexpected StartLoad({})",
glsp::filename_str(filename))
}
Action::EndLoad => {
ensure!(toplevel_let.is_none(), "invalid Recording: unexpected ToplevelLet");
return Ok(result)
}
}
}
}
/**
Invokes a callable value: an [`RFn`](struct.RFn.html), [`GFn`](struct.GFn.html) or
[`Class`](struct.Class.html).
Note that both the `receiver` and the `args` are passed by reference. The `args` should be
a reference to `()`, a tuple, a slice, or a fixed-size array.
let rect: Root<Obj> = glsp::call(&rect_class, &[10, 10, 50, 50])?;
*/
pub fn call<C, A, R>(receiver: &C, args: &A) -> GResult<R>
where
C: CallableOps,
A: ToCallArgs + ?Sized,
R: FromVal
{
glsp::push_frame(Frame::GlspCall(receiver.name()));
let _guard = Guard::new(|| glsp::pop_frame());
with_engine(|engine| {
let mut stacks = engine.vm.stacks.borrow_mut();
let starting_len = stacks.regs.len();
args.to_call_args(&mut stacks.regs)?;
let arg_count = stacks.regs.len() - starting_len;
drop(stacks);
R::from_val(&receiver.receive_call(arg_count)?)
})
}
pub(crate) fn call_gfn(gfn: &Root<GFn>, arg_count: usize) -> GResult<Val> {
with_engine(|engine| {
Ok(engine.vm.exec_gfn(gfn, arg_count)?)
})
}
/** Equivalent to [`(coro-run co arg)`](https://gamelisp.rs/std/coro-run). */
pub fn coro_run(coro: &Root<Coro>, resume_arg: Option<Val>) -> GResult<Val> {
glsp::push_frame(Frame::GlspCoroRun(coro.to_gc()));
let _guard = Guard::new(|| glsp::pop_frame());
with_engine(|engine| {
Ok(engine.vm.coro_run(coro, resume_arg)?)
})
}
/** Equivalent to [`(coro-finish! co)`](https://gamelisp.rs/std/coro-finish-mut). */
pub fn coro_finish(coro: &Root<Coro>) -> GResult<()> {
glsp::push_frame(Frame::GlspApi(GlspApiName::CoroFinish, None));
let _guard = Guard::new(|| glsp::pop_frame());
with_engine(|engine| {
Ok(engine.vm.coro_finish(coro)?)
})
}
/** Equivalent to [`(expand val env-mode)`](https://gamelisp.rs/std/expand) */
pub fn expand(val: &Val, env_mode: Option<EnvMode>) -> GResult<Val> {
glsp::push_frame(Frame::GlspApi(GlspApiName::Expand, None));
let _guard = Guard::new(|| glsp::pop_frame());
let mut expanded = eval::expand(&[val.clone()], env_mode, true)?;
assert!(expanded.len() == 1);
Ok(expanded.pop().unwrap())
}
/** Equivalent to [`(expand-multi vals env-mode)`](https://gamelisp.rs/std/expand-multi) */
pub fn expand_multi(vals: &[Val], env_mode: Option<EnvMode>) -> GResult<Vec<Val>> {
glsp::push_frame(Frame::GlspApi(GlspApiName::ExpandMulti, None));
let _guard = Guard::new(|| glsp::pop_frame());
eval::expand(vals, env_mode, false)
}
/** Equivalent to [`(expand-1 env-mode val expander)`](https://gamelisp.rs/std/expand-1) */
pub fn expand_1(
form: &Val,
expander: Option<Expander>,
env_mode: Option<EnvMode>
) -> GResult<Expansion> {
glsp::push_frame(Frame::GlspApi(GlspApiName::Expand1, None));
let _guard = Guard::new(|| glsp::pop_frame());
eval::expand_1(form, expander, env_mode)
}
}
//-------------------------------------------------------------------------------------------------
// stock_syms
//-------------------------------------------------------------------------------------------------
macro_rules! define_stock_syms(
($($kind:ident : $(($sym_str:literal, $sym_name:ident)),+),+) => (
#[derive(Copy, Clone, Debug)]
#[allow(non_camel_case_types)]
pub(crate) enum StockSym {
$($($sym_name),+),+,
STOCK_SYM_COUNT
}
static STOCK_SYMS: [(&str, SymKind); StockSym::STOCK_SYM_COUNT as usize] = [
$($(($sym_str, SymKind::$kind)),+),+
];
static STOCK_SYMS_BY_KIND: [&[Sym]; 3] = [
$(&[$(Sym(StockSym::$sym_name as u32)),+]),+
];
#[doc(hidden)]
pub mod stock_syms {
use super::{StockSym, Sym};
$($(
pub const $sym_name: Sym = Sym(StockSym::$sym_name as u32);
)+)+
}
);
);
define_stock_syms!(
StockSpecial:
("do", DO_SYM),
("quote", QUOTE_SYM),
("if", IF_SYM),
("let", LET_SYM),
("fn", FN_SYM),
("return", RETURN_SYM),
("yield", YIELD_SYM),
("defer", DEFER_SYM),
("defer-yield", DEFER_YIELD_SYM),
("block", BLOCK_SYM),
("finish-block", FINISH_BLOCK_SYM),
("restart-block", RESTART_BLOCK_SYM),
("=", ASSIGNMENT_SYM),
StockKeyword:
("&name", FLAG_NAME_SYM),
("&arg-limits", FLAG_ARG_LIMITS_SYM),
("?", QUESTION_MARK_SYM),
(":", COLON_SYM),
("_", UNDERSCORE_SYM),
("at", AT_SYM),
("and", AND_SYM),
("or", OR_SYM),
("def", DEF_SYM),
("with-global", WITH_GLOBAL_SYM),
("template-str", TEMPLATE_STR_SYM),
("newborn", NEWBORN_SYM),
("running", RUNNING_SYM),
("paused", PAUSED_SYM),
("finished", FINISHED_SYM),
("poisoned", POISONED_SYM),
("splice", SPLICE_SYM),
("let-macro", LET_MACRO_SYM),
("expanded-to", EXPANDED_TO_SYM),
("macro-no-op", MACRO_NO_OP_SYM),
("not-a-macro", NOT_A_MACRO_SYM),
("fresh", FRESH_SYM),
("copied", COPIED_SYM),
("ok", OK_SYM),
("err", ERR_SYM),
("brief", BRIEF_SYM),
("verbose", VERBOSE_SYM),
("end-of-input", END_OF_INPUT_SYM),
("else", ELSE_SYM),
("same?", SAMEP_SYM),
("eq?", EQP_SYM),
("cond", COND_SYM),
("any-of", ANY_OF_SYM),
("in", IN_SYM),
("backquote", BACKQUOTE_SYM),
("unquote", UNQUOTE_SYM),
("splay", SPLAY_SYM),
("meth-name", METH_NAME_SYM),
("atsign", ATSIGN_SYM),
("atsign=", SET_ATSIGN_SYM),
("atsign-opt", ATSIGN_OPT_SYM),
("atsign-opt=", SET_ATSIGN_OPT_SYM),
("access-opt=", SET_ACCESS_OPT_SYM),
("nil", NIL_SYM),
("char", CHAR_SYM),
("sym", SYM_SYM),
("rfn", RFN_SYM),
("str", STR_SYM),
("tab", TAB_SYM),
("obj", OBJ_SYM),
("class", CLASS_SYM),
("coro", CORO_SYM),
("rdata", RDATA_SYM),
("infinite", INFINITE_SYM),
("unknown", UNKNOWN_SYM),
("field", FIELD_SYM),
("const", CONST_SYM),
("meth", METH_SYM),
("wrap", WRAP_SYM),
("wildcard-wrap", WILDCARD_WRAP_SYM),
("prop", PROP_SYM),
("wrap-prop", WRAP_PROP_SYM),
("wildcard-wrap-prop", WILDCARD_WRAP_PROP_SYM),
("get", GET_SYM),
("set", SET_SYM),
("init", INIT_SYM),
("init-mixin", INIT_MIXIN_SYM),
("init-state", INIT_STATE_SYM),
("inits", INITS_SYM),
("fini", FINI_SYM),
("fini-mixin", FINI_MIXIN_SYM),
("fini-state", FINI_STATE_SYM),
("finis", FINIS_SYM),
("mixin", MIXIN_SYM),
("mixin?", MIXINP_SYM),
("name", NAME_SYM),
("class-name", CLASS_NAME_SYM),
("state-name", STATE_NAME_SYM),
("self", SELF_SYM),
("base", BASE_SYM),
("Main", MAIN_SYM),
("states", STATES_SYM),
("state", STATE_SYM),
("state*", STATEX_SYM),
("enab!", ENAB_SYM),
("enab?", ENABP_SYM),
("disab!", DISAB_SYM),
("fsm", FSM_SYM),
("fsm-siblings", FSM_SIBLINGS_SYM),
("parent", PARENT_SYM),
("children", CHILDREN_SYM),
("enabled-by-default?", ENABLED_BY_DEFAULTP_SYM),
("bindings", BINDINGS_SYM),
("op-clone", OP_CLONE_SYM),
("op-deep-clone", OP_DEEP_CLONE_SYM),
("op-eq?", OP_EQP_SYM),
("ratio", RATIO_SYM),
("min-ratio", MIN_RATIO_SYM),
("default-ratio", DEFAULT_RATIO_SYM),
("young-bytes", YOUNG_BYTES_SYM),
("old-bytes", OLD_BYTES_SYM),
("ghost-bytes", GHOST_BYTES_SYM),
StockTransform:
("+", ADD_SYM),
("-", SUB_SYM),
("*", MUL_SYM),
("/", DIV_SYM),
("%", REM_SYM),
("abs", ABS_SYM),
("bitand", BITAND_SYM),
("bitor", BITOR_SYM),
("bitxor", BITXOR_SYM),
("sign", SIGN_SYM),
("min", MIN_SYM),
("max", MAX_SYM),
("nil?", NILP_SYM),
("num?", NUMP_SYM),
("int?", INTP_SYM),
("flo?", FLOP_SYM),
("nan?", NANP_SYM),
("inf?", INFP_SYM),
("bool?", BOOLP_SYM),
("sym?", SYMP_SYM),
("deque?", DEQUEP_SYM),
("arr?", ARRP_SYM),
("str?", STRP_SYM),
("tab?", TABP_SYM),
("iter?", ITERP_SYM),
("iterable?", ITERABLEP_SYM),
("obj?", OBJP_SYM),
("class?", CLASSP_SYM),
("fn?", FNP_SYM),
("rfn?", RFNP_SYM),
("coro?", COROP_SYM),
("rdata?", RDATAP_SYM),
("callable?", CALLABLEP_SYM),
("expander?", EXPANDERP_SYM),
("int", INT_SYM),
("flo", FLO_SYM),
("bool", BOOL_SYM),
("==", NUM_EQ_SYM),
("<", LT_SYM),
("<=", LTE_SYM),
(">", GT_SYM),
(">=", GTE_SYM),
("not", NOT_SYM),
("iter", ITER_SYM),
("iter-next!", ITER_NEXT_SYM),
("iter-next-back!", ITER_NEXT_BACK_SYM),
("iter-finished?", ITER_FINISHEDP_SYM),
("len", LEN_SYM),
("has?", HASP_SYM),
("access", ACCESS_SYM),
("access=", SET_ACCESS_SYM),
("arr", ARR_SYM),
("call-meth", CALL_METH_SYM),
("call-meth-opt", CALL_METH_OPT_SYM),
("call-base-raw", CALL_BASE_RAW_SYM),
("global", GLOBAL_SYM),
("global=", SET_GLOBAL_SYM)
);
| 29.660793 | 100 | 0.597452 |
39ad766a90f7919f559abcb4dc618dfd3c093c73 | 7,501 | // cargo-deps: ieee754="0.2.1"
/*!
Experimentally derives, for each (int, float) pair, the largest and smallest integer values that survive round-tripping through the float types.
This is to verify *exactly* what the safe range for float-to-int conversions is.
*/
extern crate ieee754;
use std::fmt;
use ieee754::Ieee754;
macro_rules! limits {
($src:ty => $dst:ident; < $min:expr, > $max:expr) => {
limits!($src => $dst; < $min);
limits!($src => $dst; > $max);
};
($src:ty => $dst:ident; > $max:expr) => {
{
let mut cur: $src = $max;
if ((cur as $dst) as $src) != cur {
panic!("safe {} max: not found; initial limit too high!", stringify!($src => $dst));
}
loop {
let next = (cur + 1.0).max(cur.next());
let next_int = next as $dst;
let next_rnd = next_int as $src;
if next_rnd != next {
println!("safe {} max: {}, {:e}, {:+x}",
stringify!($src => $dst), cur, cur, FloatHex(cur));
break;
} else {
cur = next;
}
}
}
};
($src:ty => $dst:ident; < $min:expr) => {
{
let mut cur: $src = $min;
if ((cur as $dst) as $src) != cur {
panic!("safe {} min: not found; initial limit too low!", stringify!($src => $dst));
}
loop {
let next = (cur - 1.0).min(cur.prev());
let next_int = next as $dst;
let next_rnd = next_int as $src;
if next_rnd != next {
println!("\rsafe {} min: {:+}, {:+e}, {:+x}",
stringify!($src => $dst), cur, cur, FloatHex(cur));
break;
} else {
cur = next;
}
}
}
};
}
fn main() {
limits!(f32 => i8; < -120.0, > 120.0);
limits!(f32 => i16; < -32000.0, > 32000.0);
limits!(f32 => i32; < -2147480000.0, > 2147480000.0);
limits!(f32 => i64; < -9223300000000000000.0, > 9223300000000000000.0);
limits!(f32 => u8; > 250.0);
limits!(f32 => u16; > 64000.0);
limits!(f32 => u32; > 4290000000.0);
limits!(f32 => u64; > 18446700000000000000.0);
limits!(f64 => i8; < -120.0, > 120.0);
limits!(f64 => i16; < -32000.0, > 32000.0);
limits!(f64 => i32; < -2147480000.0, > 2147480000.0);
limits!(f64 => i64; < -9223372036854770000.0, > 9223372036854700000.0);
limits!(f64 => u8; > 250.0);
limits!(f64 => u16; > 64000.0);
limits!(f64 => u32; > 4290000000.0);
limits!(f64 => u64; > 18446744073709500000.0);
}
struct FloatHex<T>(pub T);
impl fmt::LowerHex for FloatHex<f32> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
use std::num::FpCategory;
fn write_sig(fmt: &mut fmt::Formatter, sig: u32) -> fmt::Result {
let mut sig = sig << 9;
loop {
let nib = sig >> 28;
try!(fmt.write_str(match nib {
0 => "0", 1 => "1", 2 => "2", 3 => "3",
4 => "4", 5 => "5", 6 => "6", 7 => "7",
8 => "8", 9 => "9", 10 => "a", 11 => "b",
12 => "c", 13 => "d", 14 => "e", _ => "f",
}));
sig <<= 4;
if sig == 0 { break; }
}
Ok(())
}
fn write_exp(fmt: &mut fmt::Formatter, exp: i16) -> fmt::Result {
try!(write!(fmt, "p{}", exp));
Ok(())
}
let v = self.0;
match v.classify() {
FpCategory::Nan => {
try!(fmt.write_str("nan"));
},
FpCategory::Infinite => {
if v.is_sign_negative() {
try!(fmt.write_str("-"));
} else if fmt.sign_plus() {
try!(fmt.write_str("+"));
}
try!(fmt.write_str("infinity"));
},
FpCategory::Zero => {
if v.is_sign_negative() {
try!(fmt.write_str("-"));
} else if fmt.sign_plus() {
try!(fmt.write_str("+"));
}
try!(fmt.write_str("0x0p0"));
},
FpCategory::Subnormal => {
let (neg, exp, sig) = v.decompose();
if neg { try!(fmt.write_str("-")); }
else if fmt.sign_plus() { try!(fmt.write_str("+")); }
try!(fmt.write_str("0x0."));
try!(write_sig(fmt, sig));
try!(write_exp(fmt, exp));
},
FpCategory::Normal => {
let (neg, exp, sig) = v.decompose();
if neg { try!(fmt.write_str("-")); }
else if fmt.sign_plus() { try!(fmt.write_str("+")); }
try!(fmt.write_str("0x1."));
try!(write_sig(fmt, sig));
try!(write_exp(fmt, exp));
},
}
Ok(())
}
}
impl fmt::LowerHex for FloatHex<f64> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
use std::num::FpCategory;
fn write_sig(fmt: &mut fmt::Formatter, sig: u64) -> fmt::Result {
let mut sig = sig << 13;
loop {
let nib = sig >> 60;
try!(fmt.write_str(match nib {
0 => "0", 1 => "1", 2 => "2", 3 => "3",
4 => "4", 5 => "5", 6 => "6", 7 => "7",
8 => "8", 9 => "9", 10 => "a", 11 => "b",
12 => "c", 13 => "d", 14 => "e", _ => "f",
}));
sig <<= 4;
if sig == 0 { break; }
}
Ok(())
}
fn write_exp(fmt: &mut fmt::Formatter, exp: i16) -> fmt::Result {
try!(write!(fmt, "p{}", exp));
Ok(())
}
let v = self.0;
match v.classify() {
FpCategory::Nan => {
try!(fmt.write_str("nan"));
},
FpCategory::Infinite => {
if v.is_sign_negative() {
try!(fmt.write_str("-"));
} else if fmt.sign_plus() {
try!(fmt.write_str("+"));
}
try!(fmt.write_str("infinity"));
},
FpCategory::Zero => {
if v.is_sign_negative() {
try!(fmt.write_str("-"));
} else if fmt.sign_plus() {
try!(fmt.write_str("+"));
}
try!(fmt.write_str("0x0p0"));
},
FpCategory::Subnormal => {
let (neg, exp, sig) = v.decompose();
if neg { try!(fmt.write_str("-")); }
else if fmt.sign_plus() { try!(fmt.write_str("+")); }
try!(fmt.write_str("0x0."));
try!(write_sig(fmt, sig));
try!(write_exp(fmt, exp));
},
FpCategory::Normal => {
let (neg, exp, sig) = v.decompose();
if neg { try!(fmt.write_str("-")); }
else if fmt.sign_plus() { try!(fmt.write_str("+")); }
try!(fmt.write_str("0x1."));
try!(write_sig(fmt, sig));
try!(write_exp(fmt, exp));
},
}
Ok(())
}
}
| 34.56682 | 144 | 0.399147 |
230d5e7557a08ef2bce549cad2a0eefe60a28ac1 | 1,599 | #![allow(dead_code)]
use std::{
fs::File,
io::{prelude::*, BufReader, Error},
path::Path,
};
pub fn cost_lin(x: i64, pos: &Vec<i64>) -> i64 {
return pos.into_iter().map(|elem| i64::abs(elem - x)).sum::<i64>();
}
pub fn cost_quad(x: i64, pos: &Vec<i64>) -> i64 {
let distances = pos.into_iter().map(|elem| i64::abs(elem - x));
return distances
.map(|elem| (elem.pow(2) + elem) as f64 / 2.0)
.sum::<f64>() as i64;
}
pub fn get_lin_consumption(path: impl AsRef<Path>) -> Result<i64, Error> {
let file = File::open(path)?;
let br = BufReader::new(file);
let pos: Vec<i64> = br
.lines()
.next()
.unwrap()
.unwrap()
.split(",")
.map(|x| x.parse::<i64>().unwrap())
.collect();
let mut costs = Vec::<i64>::new();
let min = pos.iter().min().unwrap();
let max = pos.iter().max().unwrap();
for x in *min..*max {
costs.push(cost_lin(x, &pos));
}
return Ok(*costs.iter().min().unwrap());
}
pub fn get_quad_consumption(path: impl AsRef<Path>) -> Result<i64, Error> {
let file = File::open(path)?;
let br = BufReader::new(file);
let pos: Vec<i64> = br
.lines()
.next()
.unwrap()
.unwrap()
.split(",")
.map(|x| x.parse::<i64>().unwrap())
.collect();
let mut costs = Vec::<i64>::new();
let min = pos.iter().min().unwrap();
let max = pos.iter().max().unwrap();
for x in *min..*max {
costs.push(cost_quad(x, &pos));
}
return Ok(*costs.iter().min().unwrap());
}
| 22.521127 | 75 | 0.514071 |
034091306d121ad3bfda503ce226c5255bfd373c | 1,285 | #![feature(async_await)]
/// An example of how to run a Tide service on top of `runtime`, this also shows the pieces
/// necessary if you wish to run a service on some other executor/IO source.
#[runtime::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
// First, we create a simple hello world application
let mut app = tide::App::new();
app.at("/").get(|_| async move { "Hello, world!" });
// Instead of using `App::run` to start the application, which implicitly uses a default
// http-service server, we need to configure a custom server with the executor and IO source we
// want it to use and then run the Tide service on it.
// Turn the `tide::App` into a generic `http_service::HttpService`
let http_service = app.into_http_service();
// Build an `http_service_hyper::Server` using runtime's `TcpListener` and `Spawn` instances
// instead of hyper's defaults.
let mut listener = runtime::net::TcpListener::bind("127.0.0.1:8000")?;
let server = http_service_hyper::Server::builder(listener.incoming())
.with_spawner(runtime::task::Spawner::new());
// Serve the Tide service on the configured server, and wait for it to complete
server.serve(http_service).await?;
Ok(())
}
| 42.833333 | 99 | 0.68249 |
0123d7940a911a878b1861f2231e24959d981bd7 | 11,851 | // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
/// Service config.
///
///
/// Service configuration allows for customization of endpoints, region, credentials providers,
/// and retry configuration. Generally, it is constructed automatically for you from a shared
/// configuration loaded by the `aws-config` crate. For example:
///
/// ```ignore
/// // Load a shared config from the environment
/// let shared_config = aws_config::from_env().load().await;
/// // The client constructor automatically converts the shared config into the service config
/// let client = Client::new(&shared_config);
/// ```
///
/// The service config can also be constructed manually using its builder.
///
pub struct Config {
app_name: Option<aws_types::app_name::AppName>,
pub(crate) timeout_config: Option<aws_smithy_types::timeout::Config>,
pub(crate) sleep_impl: Option<std::sync::Arc<dyn aws_smithy_async::rt::sleep::AsyncSleep>>,
pub(crate) retry_config: Option<aws_smithy_types::retry::RetryConfig>,
pub(crate) endpoint_resolver: ::std::sync::Arc<dyn aws_endpoint::ResolveAwsEndpoint>,
pub(crate) region: Option<aws_types::region::Region>,
pub(crate) credentials_provider: aws_types::credentials::SharedCredentialsProvider,
}
impl std::fmt::Debug for Config {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut config = f.debug_struct("Config");
config.finish()
}
}
impl Config {
/// Constructs a config builder.
pub fn builder() -> Builder {
Builder::default()
}
/// Returns the name of the app that is using the client, if it was provided.
///
/// This _optional_ name is used to identify the application in the user agent that
/// gets sent along with requests.
pub fn app_name(&self) -> Option<&aws_types::app_name::AppName> {
self.app_name.as_ref()
}
/// Creates a new [service config](crate::Config) from a [shared `config`](aws_types::sdk_config::SdkConfig).
pub fn new(config: &aws_types::sdk_config::SdkConfig) -> Self {
Builder::from(config).build()
}
/// The signature version 4 service signing name to use in the credential scope when signing requests.
///
/// The signing service may be overridden by the `Endpoint`, or by specifying a custom
/// [`SigningService`](aws_types::SigningService) during operation construction
pub fn signing_service(&self) -> &'static str {
"iot1click"
}
}
/// Builder for creating a `Config`.
#[derive(Default)]
pub struct Builder {
app_name: Option<aws_types::app_name::AppName>,
timeout_config: Option<aws_smithy_types::timeout::Config>,
sleep_impl: Option<std::sync::Arc<dyn aws_smithy_async::rt::sleep::AsyncSleep>>,
retry_config: Option<aws_smithy_types::retry::RetryConfig>,
endpoint_resolver: Option<::std::sync::Arc<dyn aws_endpoint::ResolveAwsEndpoint>>,
region: Option<aws_types::region::Region>,
credentials_provider: Option<aws_types::credentials::SharedCredentialsProvider>,
}
impl Builder {
/// Constructs a config builder.
pub fn new() -> Self {
Self::default()
}
/// Sets the name of the app that is using the client.
///
/// This _optional_ name is used to identify the application in the user agent that
/// gets sent along with requests.
pub fn app_name(mut self, app_name: aws_types::app_name::AppName) -> Self {
self.set_app_name(Some(app_name));
self
}
/// Sets the name of the app that is using the client.
///
/// This _optional_ name is used to identify the application in the user agent that
/// gets sent along with requests.
pub fn set_app_name(&mut self, app_name: Option<aws_types::app_name::AppName>) -> &mut Self {
self.app_name = app_name;
self
}
/// Set the timeout_config for the builder
///
/// # Examples
///
/// ```no_run
/// # use std::time::Duration;
/// use aws_sdk_iot1clickdevices::config::Config;
/// use aws_smithy_types::{timeout, tristate::TriState};
///
/// let api_timeouts = timeout::Api::new()
/// .with_call_attempt_timeout(TriState::Set(Duration::from_secs(1)));
/// let timeout_config = timeout::Config::new()
/// .with_api_timeouts(api_timeouts);
/// let config = Config::builder().timeout_config(timeout_config).build();
/// ```
pub fn timeout_config(mut self, timeout_config: aws_smithy_types::timeout::Config) -> Self {
self.set_timeout_config(Some(timeout_config));
self
}
/// Set the timeout_config for the builder
///
/// # Examples
///
/// ```no_run
/// # use std::time::Duration;
/// use aws_sdk_iot1clickdevices::config::{Builder, Config};
/// use aws_smithy_types::{timeout, tristate::TriState};
///
/// fn set_request_timeout(builder: &mut Builder) {
/// let api_timeouts = timeout::Api::new()
/// .with_call_attempt_timeout(TriState::Set(Duration::from_secs(1)));
/// let timeout_config = timeout::Config::new()
/// .with_api_timeouts(api_timeouts);
/// builder.set_timeout_config(Some(timeout_config));
/// }
///
/// let mut builder = Config::builder();
/// set_request_timeout(&mut builder);
/// let config = builder.build();
/// ```
pub fn set_timeout_config(
&mut self,
timeout_config: Option<aws_smithy_types::timeout::Config>,
) -> &mut Self {
self.timeout_config = timeout_config;
self
}
/// Set the sleep_impl for the builder
///
/// # Examples
///
/// ```no_run
/// use aws_sdk_iot1clickdevices::config::Config;
/// use aws_smithy_async::rt::sleep::AsyncSleep;
/// use aws_smithy_async::rt::sleep::Sleep;
///
/// #[derive(Debug)]
/// pub struct ForeverSleep;
///
/// impl AsyncSleep for ForeverSleep {
/// fn sleep(&self, duration: std::time::Duration) -> Sleep {
/// Sleep::new(std::future::pending())
/// }
/// }
///
/// let sleep_impl = std::sync::Arc::new(ForeverSleep);
/// let config = Config::builder().sleep_impl(sleep_impl).build();
/// ```
pub fn sleep_impl(
mut self,
sleep_impl: std::sync::Arc<dyn aws_smithy_async::rt::sleep::AsyncSleep>,
) -> Self {
self.set_sleep_impl(Some(sleep_impl));
self
}
/// Set the sleep_impl for the builder
///
/// # Examples
///
/// ```no_run
/// use aws_sdk_iot1clickdevices::config::{Builder, Config};
/// use aws_smithy_async::rt::sleep::AsyncSleep;
/// use aws_smithy_async::rt::sleep::Sleep;
///
/// #[derive(Debug)]
/// pub struct ForeverSleep;
///
/// impl AsyncSleep for ForeverSleep {
/// fn sleep(&self, duration: std::time::Duration) -> Sleep {
/// Sleep::new(std::future::pending())
/// }
/// }
///
/// fn set_never_ending_sleep_impl(builder: &mut Builder) {
/// let sleep_impl = std::sync::Arc::new(ForeverSleep);
/// builder.set_sleep_impl(Some(sleep_impl));
/// }
///
/// let mut builder = Config::builder();
/// set_never_ending_sleep_impl(&mut builder);
/// let config = builder.build();
/// ```
pub fn set_sleep_impl(
&mut self,
sleep_impl: Option<std::sync::Arc<dyn aws_smithy_async::rt::sleep::AsyncSleep>>,
) -> &mut Self {
self.sleep_impl = sleep_impl;
self
}
/// Set the retry_config for the builder
///
/// # Examples
/// ```no_run
/// use aws_sdk_iot1clickdevices::config::Config;
/// use aws_smithy_types::retry::RetryConfig;
///
/// let retry_config = RetryConfig::new().with_max_attempts(5);
/// let config = Config::builder().retry_config(retry_config).build();
/// ```
pub fn retry_config(mut self, retry_config: aws_smithy_types::retry::RetryConfig) -> Self {
self.set_retry_config(Some(retry_config));
self
}
/// Set the retry_config for the builder
///
/// # Examples
/// ```no_run
/// use aws_sdk_iot1clickdevices::config::{Builder, Config};
/// use aws_smithy_types::retry::RetryConfig;
///
/// fn disable_retries(builder: &mut Builder) {
/// let retry_config = RetryConfig::new().with_max_attempts(1);
/// builder.set_retry_config(Some(retry_config));
/// }
///
/// let mut builder = Config::builder();
/// disable_retries(&mut builder);
/// let config = builder.build();
/// ```
pub fn set_retry_config(
&mut self,
retry_config: Option<aws_smithy_types::retry::RetryConfig>,
) -> &mut Self {
self.retry_config = retry_config;
self
}
// TODO(docs): include an example of using a static endpoint
/// Sets the endpoint resolver to use when making requests.
pub fn endpoint_resolver(
mut self,
endpoint_resolver: impl aws_endpoint::ResolveAwsEndpoint + 'static,
) -> Self {
self.endpoint_resolver = Some(::std::sync::Arc::new(endpoint_resolver));
self
}
/// Sets the AWS region to use when making requests.
///
/// # Examples
/// ```no_run
/// use aws_types::region::Region;
/// use aws_sdk_iot1clickdevices::config::{Builder, Config};
///
/// let config = aws_sdk_iot1clickdevices::Config::builder()
/// .region(Region::new("us-east-1"))
/// .build();
/// ```
pub fn region(mut self, region: impl Into<Option<aws_types::region::Region>>) -> Self {
self.region = region.into();
self
}
/// Sets the credentials provider for this service
pub fn credentials_provider(
mut self,
credentials_provider: impl aws_types::credentials::ProvideCredentials + 'static,
) -> Self {
self.credentials_provider = Some(aws_types::credentials::SharedCredentialsProvider::new(
credentials_provider,
));
self
}
/// Sets the credentials provider for this service
pub fn set_credentials_provider(
&mut self,
credentials_provider: Option<aws_types::credentials::SharedCredentialsProvider>,
) -> &mut Self {
self.credentials_provider = credentials_provider;
self
}
/// Builds a [`Config`].
pub fn build(self) -> Config {
Config {
app_name: self.app_name,
timeout_config: self.timeout_config,
sleep_impl: self.sleep_impl,
retry_config: self.retry_config,
endpoint_resolver: self
.endpoint_resolver
.unwrap_or_else(|| ::std::sync::Arc::new(crate::aws_endpoint::endpoint_resolver())),
region: self.region,
credentials_provider: self.credentials_provider.unwrap_or_else(|| {
aws_types::credentials::SharedCredentialsProvider::new(
crate::no_credentials::NoCredentials,
)
}),
}
}
}
impl From<&aws_types::sdk_config::SdkConfig> for Builder {
fn from(input: &aws_types::sdk_config::SdkConfig) -> Self {
let mut builder = Builder::default();
builder = builder.region(input.region().cloned());
builder.set_retry_config(input.retry_config().cloned());
builder.set_timeout_config(input.timeout_config().cloned());
builder.set_sleep_impl(input.sleep_impl().clone());
builder.set_credentials_provider(input.credentials_provider().cloned());
builder.set_app_name(input.app_name().cloned());
builder
}
}
impl From<&aws_types::sdk_config::SdkConfig> for Config {
fn from(sdk_config: &aws_types::sdk_config::SdkConfig) -> Self {
Builder::from(sdk_config).build()
}
}
| 37.034375 | 113 | 0.626614 |
33595428ed9dcc120bffaa249f27afeac9ab4cff | 2,339 | use crate::app::components::{screen_add_css_provider, Component};
use crate::app::dispatch::Worker;
use crate::app::loader::ImageLoader;
use crate::app::models::AlbumModel;
use gladis::Gladis;
use gtk::prelude::*;
use gtk::RevealerExt;
#[derive(Gladis, Clone)]
struct AlbumWidget {
root: gtk::Widget,
revealer: gtk::Revealer,
album_label: gtk::Label,
artist_label: gtk::Label,
cover_btn: gtk::Button,
cover_image: gtk::Image,
}
impl AlbumWidget {
pub fn new() -> Self {
screen_add_css_provider(resource!("/components/album.css"));
Self::from_resource(resource!("/components/album.ui")).unwrap()
}
}
pub struct Album {
widget: AlbumWidget,
model: AlbumModel,
}
impl Album {
pub fn new(album_model: &AlbumModel, worker: Worker) -> Self {
let widget = AlbumWidget::new();
let image = widget.cover_image.downgrade();
let revealer = widget.revealer.downgrade();
if let Some(url) = album_model.cover_url() {
worker.send_local_task(async move {
if let (Some(image), Some(revealer)) = (image.upgrade(), revealer.upgrade()) {
let loader = ImageLoader::new();
let result = loader.load_remote(&url, "jpg", 200, 200).await;
image.set_from_pixbuf(result.as_ref());
revealer.set_reveal_child(true);
}
});
} else {
widget.revealer.set_reveal_child(true);
}
album_model
.bind_property("album", &widget.album_label, "label")
.flags(glib::BindingFlags::DEFAULT | glib::BindingFlags::SYNC_CREATE)
.build();
album_model
.bind_property("artist", &widget.artist_label, "label")
.flags(glib::BindingFlags::DEFAULT | glib::BindingFlags::SYNC_CREATE)
.build();
Self {
widget,
model: album_model.clone(),
}
}
pub fn connect_album_pressed<F: Fn(&AlbumModel) + 'static>(&self, f: F) {
self.widget
.cover_btn
.connect_clicked(clone!(@weak self.model as model => move |_| {
f(&model);
}));
}
}
impl Component for Album {
fn get_root_widget(&self) -> >k::Widget {
&self.widget.root
}
}
| 29.2375 | 94 | 0.579307 |
69b30f8908c1cc3ba6c1603b8947bd160c0b95c5 | 9,799 | use crate::attributes::with_named_constraints;
use crate::common::*;
use datamodel::{render_datamodel_to_string, IndexDefinition, IndexType};
#[test]
fn basic_unique_index_must_work() {
let dml = r#"
model User {
id Int @id
firstName String
lastName String
@@unique([firstName,lastName])
}
"#;
let schema = parse(dml);
let user_model = schema.assert_has_model("User");
user_model.assert_has_index(IndexDefinition {
name: None,
db_name: Some("User.firstName_lastName_unique".to_string()),
fields: vec!["firstName".to_string(), "lastName".to_string()],
tpe: IndexType::Unique,
defined_on_field: false,
});
}
#[test]
fn must_succeed_on_model_with_unique_criteria() {
let dml1 = r#"
model Model {
id String @id
}
"#;
let _ = parse(dml1);
let dml2 = r#"
model Model {
a String
b String
@@id([a,b])
}
"#;
let _ = parse(dml2);
let dml3 = r#"
model Model {
unique String @unique
}
"#;
let _ = parse(dml3);
let dml4 = r#"
model Model {
a String
b String
@@unique([a,b])
}
"#;
let _ = parse(dml4);
}
#[test]
fn single_field_unique_on_enum_field_must_work() {
let dml = r#"
model User {
id Int @id
role Role @unique
}
enum Role {
Admin
Member
}
"#;
let schema = parse(dml);
let model = schema.assert_has_model("User");
model.assert_has_scalar_field("role");
assert!(model.field_is_unique("role"));
}
#[test]
fn the_name_argument_must_work() {
let dml = r#"
model User {
id Int @id
firstName String
lastName String
@@unique([firstName,lastName], name: "MyIndexName")
}
"#;
let schema = parse(dml);
let user_model = schema.assert_has_model("User");
user_model.assert_has_index(IndexDefinition {
name: Some("MyIndexName".to_string()),
db_name: Some("MyIndexName".to_string()),
fields: vec!["firstName".to_string(), "lastName".to_string()],
tpe: IndexType::Unique,
defined_on_field: false,
});
}
#[test]
fn multiple_unique_must_work() {
let dml = r#"
model User {
id Int @id
firstName String
lastName String
@@unique([firstName,lastName])
@@unique([firstName,lastName], name: "MyIndexName")
}
"#;
let schema = parse(dml);
let user_model = schema.assert_has_model("User");
user_model.assert_has_index(IndexDefinition {
name: None,
db_name: Some("User.firstName_lastName_unique".to_string()),
fields: vec!["firstName".to_string(), "lastName".to_string()],
tpe: IndexType::Unique,
defined_on_field: false,
});
user_model.assert_has_index(IndexDefinition {
name: Some("MyIndexName".to_string()),
db_name: Some("MyIndexName".to_string()),
fields: vec!["firstName".to_string(), "lastName".to_string()],
tpe: IndexType::Unique,
defined_on_field: false,
});
}
#[test]
fn multi_field_unique_on_native_type_fields_fields_must_work() {
let dml = r#"
datasource ds {
provider = "mysql"
url = "mysql://"
}
model User {
id Int @id
role Bytes
role2 Bytes @ds.VarBinary(40)
@@unique([role2, role])
}
"#;
parse(dml);
}
#[test]
fn multi_field_unique_indexes_on_enum_fields_must_work() {
let dml = r#"
model User {
id Int @id
role Role
@@unique([role])
}
enum Role {
Admin
Member
}
"#;
let schema = parse(dml);
let user_model = schema.assert_has_model("User");
user_model.assert_has_index(IndexDefinition {
name: None,
db_name: Some("User.role_unique".to_string()),
fields: vec!["role".to_string()],
tpe: IndexType::Unique,
defined_on_field: false,
});
}
#[test]
fn single_field_unique_indexes_on_enum_fields_must_work() {
let dml = r#"
model User {
id Int @id
role Role @unique
}
enum Role {
Admin
Member
}
"#;
let schema = parse(dml);
let user_model = schema.assert_has_model("User");
user_model.assert_has_index(IndexDefinition {
name: None,
db_name: Some("User.role_unique".to_string()),
fields: vec!["role".to_string()],
tpe: IndexType::Unique,
defined_on_field: true,
});
}
#[test]
fn unique_attributes_must_serialize_to_valid_dml() {
let dml = r#"
model User {
id Int @id
firstName String
lastName String
@@unique([firstName,lastName], name: "customName")
}
"#;
let schema = parse(dml);
assert!(datamodel::parse_datamodel(&render_datamodel_to_string(&schema, None)).is_ok());
}
#[test]
fn named_multi_field_unique_must_work() {
//Compatibility case
let dml = with_named_constraints(
r#"
model User {
a String
b Int
@@unique([a,b], name:"ClientName")
}
"#,
);
let datamodel = parse(&dml);
let user_model = datamodel.assert_has_model("User");
user_model.assert_has_index(IndexDefinition {
name: Some("ClientName".to_string()),
db_name: Some("User_a_b_key".to_string()),
fields: vec!["a".to_string(), "b".to_string()],
tpe: IndexType::Unique,
defined_on_field: false,
});
}
#[test]
fn mapped_multi_field_unique_must_work() {
let dml = with_named_constraints(
r#"
model User {
a String
b Int
@@unique([a,b], map:"dbname")
}
"#,
);
let datamodel = parse(&dml);
let user_model = datamodel.assert_has_model("User");
user_model.assert_has_index(IndexDefinition {
name: None,
db_name: Some("dbname".to_string()),
fields: vec!["a".to_string(), "b".to_string()],
tpe: IndexType::Unique,
defined_on_field: false,
});
}
#[test]
fn mapped_singular_unique_must_work() {
let dml = with_named_constraints(
r#"
model Model {
a String @unique(map: "test")
}
model Model2 {
a String @unique(map: "test2")
}
"#,
);
let datamodel = parse(&dml);
let model = datamodel.assert_has_model("Model");
model.assert_has_index(IndexDefinition {
name: None,
db_name: Some("test".to_string()),
fields: vec!["a".to_string()],
tpe: IndexType::Unique,
defined_on_field: true,
});
let model2 = datamodel.assert_has_model("Model2");
model2.assert_has_index(IndexDefinition {
name: None,
db_name: Some("test2".to_string()),
fields: vec!["a".to_string()],
tpe: IndexType::Unique,
defined_on_field: true,
});
}
#[test]
fn named_and_mapped_multi_field_unique_must_work() {
let dml = with_named_constraints(
r#"
model Model {
a String
b Int
@@unique([a,b], name: "compoundId", map:"dbname")
}
"#,
);
let datamodel = parse(&dml);
let model = datamodel.assert_has_model("Model");
model.assert_has_index(IndexDefinition {
name: Some("compoundId".to_string()),
db_name: Some("dbname".to_string()),
fields: vec!["a".to_string(), "b".to_string()],
tpe: IndexType::Unique,
defined_on_field: false,
});
}
#[test]
fn implicit_names_must_work() {
let dml = with_named_constraints(
r#"
model Model {
a String @unique
b Int
@@unique([a,b])
}
"#,
);
let datamodel = parse(&dml);
let model = datamodel.assert_has_model("Model");
model.assert_has_index(IndexDefinition {
name: None,
db_name: Some("Model_a_b_key".to_string()),
fields: vec!["a".to_string(), "b".to_string()],
tpe: IndexType::Unique,
defined_on_field: false,
});
model.assert_has_index(IndexDefinition {
name: None,
db_name: Some("Model_a_key".to_string()),
fields: vec!["a".to_string()],
tpe: IndexType::Unique,
defined_on_field: true,
});
}
#[test]
fn defined_on_field_must_work() {
let dml = with_named_constraints(
r#"
model Model {
a String @unique
b Int
@@unique([b])
}
"#,
);
let datamodel = parse(&dml);
let model = datamodel.assert_has_model("Model");
model.assert_has_index(IndexDefinition {
name: None,
db_name: Some("Model_a_key".to_string()),
fields: vec!["a".to_string()],
tpe: IndexType::Unique,
defined_on_field: true,
});
model.assert_has_index(IndexDefinition {
name: None,
db_name: Some("Model_b_key".to_string()),
fields: vec!["b".to_string()],
tpe: IndexType::Unique,
defined_on_field: false,
});
}
#[test]
fn naming_unique_to_a_field_name_should_work() {
let dml = r#"
model User {
used Int
name String
identification Int
@@unique([name, identification], name: "used")
}
"#;
let datamodel = parse(&dml);
let model = datamodel.assert_has_model("User");
model.assert_has_index(IndexDefinition {
name: Some("used".to_string()),
db_name: Some("used".to_string()),
fields: vec!["name".to_string(), "identification".to_string()],
tpe: IndexType::Unique,
defined_on_field: false,
});
}
| 23.669082 | 92 | 0.568834 |
dbc32f4dbddced6ba557b44fc23b62ebee91ab35 | 78,477 | // Copyright 2016 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 session::{self, DataTypeKind};
use ty::{self, Ty, TyCtxt, TypeFoldable, ReprOptions};
use syntax::ast::{self, FloatTy, IntTy, UintTy};
use syntax::attr;
use syntax_pos::DUMMY_SP;
use std::cmp;
use std::fmt;
use std::i128;
use std::mem;
use ich::StableHashingContext;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher,
StableHasherResult};
pub use rustc_target::abi::*;
pub trait IntegerExt {
fn to_ty<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, signed: bool) -> Ty<'tcx>;
fn from_attr<C: HasDataLayout>(cx: C, ity: attr::IntType) -> Integer;
fn repr_discr<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
ty: Ty<'tcx>,
repr: &ReprOptions,
min: i128,
max: i128)
-> (Integer, bool);
}
impl IntegerExt for Integer {
fn to_ty<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, signed: bool) -> Ty<'tcx> {
match (*self, signed) {
(I8, false) => tcx.types.u8,
(I16, false) => tcx.types.u16,
(I32, false) => tcx.types.u32,
(I64, false) => tcx.types.u64,
(I128, false) => tcx.types.u128,
(I8, true) => tcx.types.i8,
(I16, true) => tcx.types.i16,
(I32, true) => tcx.types.i32,
(I64, true) => tcx.types.i64,
(I128, true) => tcx.types.i128,
}
}
/// Get the Integer type from an attr::IntType.
fn from_attr<C: HasDataLayout>(cx: C, ity: attr::IntType) -> Integer {
let dl = cx.data_layout();
match ity {
attr::SignedInt(IntTy::I8) | attr::UnsignedInt(UintTy::U8) => I8,
attr::SignedInt(IntTy::I16) | attr::UnsignedInt(UintTy::U16) => I16,
attr::SignedInt(IntTy::I32) | attr::UnsignedInt(UintTy::U32) => I32,
attr::SignedInt(IntTy::I64) | attr::UnsignedInt(UintTy::U64) => I64,
attr::SignedInt(IntTy::I128) | attr::UnsignedInt(UintTy::U128) => I128,
attr::SignedInt(IntTy::Isize) | attr::UnsignedInt(UintTy::Usize) => {
dl.ptr_sized_integer()
}
}
}
/// Find the appropriate Integer type and signedness for the given
/// signed discriminant range and #[repr] attribute.
/// N.B.: u128 values above i128::MAX will be treated as signed, but
/// that shouldn't affect anything, other than maybe debuginfo.
fn repr_discr<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
ty: Ty<'tcx>,
repr: &ReprOptions,
min: i128,
max: i128)
-> (Integer, bool) {
// Theoretically, negative values could be larger in unsigned representation
// than the unsigned representation of the signed minimum. However, if there
// are any negative values, the only valid unsigned representation is u128
// which can fit all i128 values, so the result remains unaffected.
let unsigned_fit = Integer::fit_unsigned(cmp::max(min as u128, max as u128));
let signed_fit = cmp::max(Integer::fit_signed(min), Integer::fit_signed(max));
let mut min_from_extern = None;
let min_default = I8;
if let Some(ity) = repr.int {
let discr = Integer::from_attr(tcx, ity);
let fit = if ity.is_signed() { signed_fit } else { unsigned_fit };
if discr < fit {
bug!("Integer::repr_discr: `#[repr]` hint too small for \
discriminant range of enum `{}", ty)
}
return (discr, ity.is_signed());
}
if repr.c() {
match &tcx.sess.target.target.arch[..] {
// WARNING: the ARM EABI has two variants; the one corresponding
// to `at_least == I32` appears to be used on Linux and NetBSD,
// but some systems may use the variant corresponding to no
// lower bound. However, we don't run on those yet...?
"arm" => min_from_extern = Some(I32),
_ => min_from_extern = Some(I32),
}
}
let at_least = min_from_extern.unwrap_or(min_default);
// If there are no negative values, we can use the unsigned fit.
if min >= 0 {
(cmp::max(unsigned_fit, at_least), false)
} else {
(cmp::max(signed_fit, at_least), true)
}
}
}
pub trait PrimitiveExt {
fn to_ty<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx>;
}
impl PrimitiveExt for Primitive {
fn to_ty<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
match *self {
Int(i, signed) => i.to_ty(tcx, signed),
F32 => tcx.types.f32,
F64 => tcx.types.f64,
Pointer => tcx.mk_mut_ptr(tcx.mk_nil()),
}
}
}
/// The first half of a fat pointer.
///
/// - For a trait object, this is the address of the box.
/// - For a slice, this is the base address.
pub const FAT_PTR_ADDR: usize = 0;
/// The second half of a fat pointer.
///
/// - For a trait object, this is the address of the vtable.
/// - For a slice, this is the length.
pub const FAT_PTR_EXTRA: usize = 1;
#[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
pub enum LayoutError<'tcx> {
Unknown(Ty<'tcx>),
SizeOverflow(Ty<'tcx>)
}
impl<'tcx> fmt::Display for LayoutError<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
LayoutError::Unknown(ty) => {
write!(f, "the type `{:?}` has an unknown layout", ty)
}
LayoutError::SizeOverflow(ty) => {
write!(f, "the type `{:?}` is too big for the current architecture", ty)
}
}
}
}
fn layout_raw<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
-> Result<&'tcx LayoutDetails, LayoutError<'tcx>>
{
ty::tls::with_related_context(tcx, move |icx| {
let rec_limit = *tcx.sess.recursion_limit.get();
let (param_env, ty) = query.into_parts();
if icx.layout_depth > rec_limit {
tcx.sess.fatal(
&format!("overflow representing the type `{}`", ty));
}
// Update the ImplicitCtxt to increase the layout_depth
let icx = ty::tls::ImplicitCtxt {
layout_depth: icx.layout_depth + 1,
..icx.clone()
};
ty::tls::enter_context(&icx, |_| {
let cx = LayoutCx { tcx, param_env };
cx.layout_raw_uncached(ty)
})
})
}
pub fn provide(providers: &mut ty::maps::Providers) {
*providers = ty::maps::Providers {
layout_raw,
..*providers
};
}
#[derive(Copy, Clone)]
pub struct LayoutCx<'tcx, C> {
pub tcx: C,
pub param_env: ty::ParamEnv<'tcx>
}
impl<'a, 'tcx> LayoutCx<'tcx, TyCtxt<'a, 'tcx, 'tcx>> {
fn layout_raw_uncached(self, ty: Ty<'tcx>)
-> Result<&'tcx LayoutDetails, LayoutError<'tcx>> {
let tcx = self.tcx;
let param_env = self.param_env;
let dl = self.data_layout();
let scalar_unit = |value: Primitive| {
let bits = value.size(dl).bits();
assert!(bits <= 128);
Scalar {
value,
valid_range: 0..=(!0 >> (128 - bits))
}
};
let scalar = |value: Primitive| {
tcx.intern_layout(LayoutDetails::scalar(self, scalar_unit(value)))
};
let scalar_pair = |a: Scalar, b: Scalar| {
let align = a.value.align(dl).max(b.value.align(dl)).max(dl.aggregate_align);
let b_offset = a.value.size(dl).abi_align(b.value.align(dl));
let size = (b_offset + b.value.size(dl)).abi_align(align);
LayoutDetails {
variants: Variants::Single { index: 0 },
fields: FieldPlacement::Arbitrary {
offsets: vec![Size::from_bytes(0), b_offset],
memory_index: vec![0, 1]
},
abi: Abi::ScalarPair(a, b),
align,
size
}
};
#[derive(Copy, Clone, Debug)]
enum StructKind {
/// A tuple, closure, or univariant which cannot be coerced to unsized.
AlwaysSized,
/// A univariant, the last field of which may be coerced to unsized.
MaybeUnsized,
/// A univariant, but with a prefix of an arbitrary size & alignment (e.g. enum tag).
Prefixed(Size, Align),
}
let univariant_uninterned = |fields: &[TyLayout], repr: &ReprOptions, kind| {
let packed = repr.packed();
if packed && repr.align > 0 {
bug!("struct cannot be packed and aligned");
}
let pack = {
let pack = repr.pack as u64;
Align::from_bytes(pack, pack).unwrap()
};
let mut align = if packed {
dl.i8_align
} else {
dl.aggregate_align
};
let mut sized = true;
let mut offsets = vec![Size::from_bytes(0); fields.len()];
let mut inverse_memory_index: Vec<u32> = (0..fields.len() as u32).collect();
let mut optimize = !repr.inhibit_struct_field_reordering_opt();
if let StructKind::Prefixed(_, align) = kind {
optimize &= align.abi() == 1;
}
if optimize {
let end = if let StructKind::MaybeUnsized = kind {
fields.len() - 1
} else {
fields.len()
};
let optimizing = &mut inverse_memory_index[..end];
let field_align = |f: &TyLayout| {
if packed { f.align.min(pack).abi() } else { f.align.abi() }
};
match kind {
StructKind::AlwaysSized |
StructKind::MaybeUnsized => {
optimizing.sort_by_key(|&x| {
// Place ZSTs first to avoid "interesting offsets",
// especially with only one or two non-ZST fields.
let f = &fields[x as usize];
(!f.is_zst(), cmp::Reverse(field_align(f)))
});
}
StructKind::Prefixed(..) => {
optimizing.sort_by_key(|&x| field_align(&fields[x as usize]));
}
}
}
// inverse_memory_index holds field indices by increasing memory offset.
// That is, if field 5 has offset 0, the first element of inverse_memory_index is 5.
// We now write field offsets to the corresponding offset slot;
// field 5 with offset 0 puts 0 in offsets[5].
// At the bottom of this function, we use inverse_memory_index to produce memory_index.
let mut offset = Size::from_bytes(0);
if let StructKind::Prefixed(prefix_size, prefix_align) = kind {
if packed {
let prefix_align = prefix_align.min(pack);
align = align.max(prefix_align);
} else {
align = align.max(prefix_align);
}
offset = prefix_size.abi_align(prefix_align);
}
for &i in &inverse_memory_index {
let field = fields[i as usize];
if !sized {
bug!("univariant: field #{} of `{}` comes after unsized field",
offsets.len(), ty);
}
if field.is_unsized() {
sized = false;
}
// Invariant: offset < dl.obj_size_bound() <= 1<<61
if packed {
let field_pack = field.align.min(pack);
offset = offset.abi_align(field_pack);
align = align.max(field_pack);
}
else {
offset = offset.abi_align(field.align);
align = align.max(field.align);
}
debug!("univariant offset: {:?} field: {:#?}", offset, field);
offsets[i as usize] = offset;
offset = offset.checked_add(field.size, dl)
.ok_or(LayoutError::SizeOverflow(ty))?;
}
if repr.align > 0 {
let repr_align = repr.align as u64;
align = align.max(Align::from_bytes(repr_align, repr_align).unwrap());
debug!("univariant repr_align: {:?}", repr_align);
}
debug!("univariant min_size: {:?}", offset);
let min_size = offset;
// As stated above, inverse_memory_index holds field indices by increasing offset.
// This makes it an already-sorted view of the offsets vec.
// To invert it, consider:
// If field 5 has offset 0, offsets[0] is 5, and memory_index[5] should be 0.
// Field 5 would be the first element, so memory_index is i:
// Note: if we didn't optimize, it's already right.
let mut memory_index;
if optimize {
memory_index = vec![0; inverse_memory_index.len()];
for i in 0..inverse_memory_index.len() {
memory_index[inverse_memory_index[i] as usize] = i as u32;
}
} else {
memory_index = inverse_memory_index;
}
let size = min_size.abi_align(align);
let mut abi = Abi::Aggregate { sized };
// Unpack newtype ABIs and find scalar pairs.
if sized && size.bytes() > 0 {
// All other fields must be ZSTs, and we need them to all start at 0.
let mut zst_offsets =
offsets.iter().enumerate().filter(|&(i, _)| fields[i].is_zst());
if zst_offsets.all(|(_, o)| o.bytes() == 0) {
let mut non_zst_fields =
fields.iter().enumerate().filter(|&(_, f)| !f.is_zst());
match (non_zst_fields.next(), non_zst_fields.next(), non_zst_fields.next()) {
// We have exactly one non-ZST field.
(Some((i, field)), None, None) => {
// Field fills the struct and it has a scalar or scalar pair ABI.
if offsets[i].bytes() == 0 &&
align.abi() == field.align.abi() &&
size == field.size {
match field.abi {
// For plain scalars, or vectors of them, we can't unpack
// newtypes for `#[repr(C)]`, as that affects C ABIs.
Abi::Scalar(_) | Abi::Vector { .. } if optimize => {
abi = field.abi.clone();
}
// But scalar pairs are Rust-specific and get
// treated as aggregates by C ABIs anyway.
Abi::ScalarPair(..) => {
abi = field.abi.clone();
}
_ => {}
}
}
}
// Two non-ZST fields, and they're both scalars.
(Some((i, &TyLayout {
details: &LayoutDetails { abi: Abi::Scalar(ref a), .. }, ..
})), Some((j, &TyLayout {
details: &LayoutDetails { abi: Abi::Scalar(ref b), .. }, ..
})), None) => {
// Order by the memory placement, not source order.
let ((i, a), (j, b)) = if offsets[i] < offsets[j] {
((i, a), (j, b))
} else {
((j, b), (i, a))
};
let pair = scalar_pair(a.clone(), b.clone());
let pair_offsets = match pair.fields {
FieldPlacement::Arbitrary {
ref offsets,
ref memory_index
} => {
assert_eq!(memory_index, &[0, 1]);
offsets
}
_ => bug!()
};
if offsets[i] == pair_offsets[0] &&
offsets[j] == pair_offsets[1] &&
align == pair.align &&
size == pair.size {
// We can use `ScalarPair` only when it matches our
// already computed layout (including `#[repr(C)]`).
abi = pair.abi;
}
}
_ => {}
}
}
}
if sized && fields.iter().any(|f| f.abi == Abi::Uninhabited) {
abi = Abi::Uninhabited;
}
Ok(LayoutDetails {
variants: Variants::Single { index: 0 },
fields: FieldPlacement::Arbitrary {
offsets,
memory_index
},
abi,
align,
size
})
};
let univariant = |fields: &[TyLayout], repr: &ReprOptions, kind| {
Ok(tcx.intern_layout(univariant_uninterned(fields, repr, kind)?))
};
assert!(!ty.has_infer_types());
Ok(match ty.sty {
// Basic scalars.
ty::TyBool => {
tcx.intern_layout(LayoutDetails::scalar(self, Scalar {
value: Int(I8, false),
valid_range: 0..=1
}))
}
ty::TyChar => {
tcx.intern_layout(LayoutDetails::scalar(self, Scalar {
value: Int(I32, false),
valid_range: 0..=0x10FFFF
}))
}
ty::TyInt(ity) => {
scalar(Int(Integer::from_attr(dl, attr::SignedInt(ity)), true))
}
ty::TyUint(ity) => {
scalar(Int(Integer::from_attr(dl, attr::UnsignedInt(ity)), false))
}
ty::TyFloat(FloatTy::F32) => scalar(F32),
ty::TyFloat(FloatTy::F64) => scalar(F64),
ty::TyFnPtr(_) => {
let mut ptr = scalar_unit(Pointer);
ptr.valid_range = 1..=*ptr.valid_range.end();
tcx.intern_layout(LayoutDetails::scalar(self, ptr))
}
// The never type.
ty::TyNever => {
tcx.intern_layout(LayoutDetails {
variants: Variants::Single { index: 0 },
fields: FieldPlacement::Union(0),
abi: Abi::Uninhabited,
align: dl.i8_align,
size: Size::from_bytes(0)
})
}
// Potentially-fat pointers.
ty::TyRef(_, pointee, _) |
ty::TyRawPtr(ty::TypeAndMut { ty: pointee, .. }) => {
let mut data_ptr = scalar_unit(Pointer);
if !ty.is_unsafe_ptr() {
data_ptr.valid_range = 1..=*data_ptr.valid_range.end();
}
let pointee = tcx.normalize_erasing_regions(param_env, pointee);
if pointee.is_sized(tcx.at(DUMMY_SP), param_env) {
return Ok(tcx.intern_layout(LayoutDetails::scalar(self, data_ptr)));
}
let unsized_part = tcx.struct_tail(pointee);
let metadata = match unsized_part.sty {
ty::TyForeign(..) => {
return Ok(tcx.intern_layout(LayoutDetails::scalar(self, data_ptr)));
}
ty::TySlice(_) | ty::TyStr => {
scalar_unit(Int(dl.ptr_sized_integer(), false))
}
ty::TyDynamic(..) => {
let mut vtable = scalar_unit(Pointer);
vtable.valid_range = 1..=*vtable.valid_range.end();
vtable
}
_ => return Err(LayoutError::Unknown(unsized_part))
};
// Effectively a (ptr, meta) tuple.
tcx.intern_layout(scalar_pair(data_ptr, metadata))
}
// Arrays and slices.
ty::TyArray(element, mut count) => {
if count.has_projections() {
count = tcx.normalize_erasing_regions(param_env, count);
if count.has_projections() {
return Err(LayoutError::Unknown(ty));
}
}
let element = self.layout_of(element)?;
let count = count.unwrap_usize(tcx);
let size = element.size.checked_mul(count, dl)
.ok_or(LayoutError::SizeOverflow(ty))?;
tcx.intern_layout(LayoutDetails {
variants: Variants::Single { index: 0 },
fields: FieldPlacement::Array {
stride: element.size,
count
},
abi: Abi::Aggregate { sized: true },
align: element.align,
size
})
}
ty::TySlice(element) => {
let element = self.layout_of(element)?;
tcx.intern_layout(LayoutDetails {
variants: Variants::Single { index: 0 },
fields: FieldPlacement::Array {
stride: element.size,
count: 0
},
abi: Abi::Aggregate { sized: false },
align: element.align,
size: Size::from_bytes(0)
})
}
ty::TyStr => {
tcx.intern_layout(LayoutDetails {
variants: Variants::Single { index: 0 },
fields: FieldPlacement::Array {
stride: Size::from_bytes(1),
count: 0
},
abi: Abi::Aggregate { sized: false },
align: dl.i8_align,
size: Size::from_bytes(0)
})
}
// Odd unit types.
ty::TyFnDef(..) => {
univariant(&[], &ReprOptions::default(), StructKind::AlwaysSized)?
}
ty::TyDynamic(..) | ty::TyForeign(..) => {
let mut unit = univariant_uninterned(&[], &ReprOptions::default(),
StructKind::AlwaysSized)?;
match unit.abi {
Abi::Aggregate { ref mut sized } => *sized = false,
_ => bug!()
}
tcx.intern_layout(unit)
}
// Tuples, generators and closures.
ty::TyGenerator(def_id, ref substs, _) => {
let tys = substs.field_tys(def_id, tcx);
univariant(&tys.map(|ty| self.layout_of(ty)).collect::<Result<Vec<_>, _>>()?,
&ReprOptions::default(),
StructKind::AlwaysSized)?
}
ty::TyClosure(def_id, ref substs) => {
let tys = substs.upvar_tys(def_id, tcx);
univariant(&tys.map(|ty| self.layout_of(ty)).collect::<Result<Vec<_>, _>>()?,
&ReprOptions::default(),
StructKind::AlwaysSized)?
}
ty::TyTuple(tys) => {
let kind = if tys.len() == 0 {
StructKind::AlwaysSized
} else {
StructKind::MaybeUnsized
};
univariant(&tys.iter().map(|ty| self.layout_of(ty)).collect::<Result<Vec<_>, _>>()?,
&ReprOptions::default(), kind)?
}
// SIMD vector types.
ty::TyAdt(def, ..) if def.repr.simd() => {
let element = self.layout_of(ty.simd_type(tcx))?;
let count = ty.simd_size(tcx) as u64;
assert!(count > 0);
let scalar = match element.abi {
Abi::Scalar(ref scalar) => scalar.clone(),
_ => {
tcx.sess.fatal(&format!("monomorphising SIMD type `{}` with \
a non-machine element type `{}`",
ty, element.ty));
}
};
let size = element.size.checked_mul(count, dl)
.ok_or(LayoutError::SizeOverflow(ty))?;
let align = dl.vector_align(size);
let size = size.abi_align(align);
tcx.intern_layout(LayoutDetails {
variants: Variants::Single { index: 0 },
fields: FieldPlacement::Array {
stride: element.size,
count
},
abi: Abi::Vector {
element: scalar,
count
},
size,
align,
})
}
// ADTs.
ty::TyAdt(def, substs) => {
// Cache the field layouts.
let variants = def.variants.iter().map(|v| {
v.fields.iter().map(|field| {
self.layout_of(field.ty(tcx, substs))
}).collect::<Result<Vec<_>, _>>()
}).collect::<Result<Vec<_>, _>>()?;
if def.is_union() {
let packed = def.repr.packed();
if packed && def.repr.align > 0 {
bug!("Union cannot be packed and aligned");
}
let pack = {
let pack = def.repr.pack as u64;
Align::from_bytes(pack, pack).unwrap()
};
let mut align = if packed {
dl.i8_align
} else {
dl.aggregate_align
};
if def.repr.align > 0 {
let repr_align = def.repr.align as u64;
align = align.max(
Align::from_bytes(repr_align, repr_align).unwrap());
}
let mut size = Size::from_bytes(0);
for field in &variants[0] {
assert!(!field.is_unsized());
if packed {
let field_pack = field.align.min(pack);
align = align.max(field_pack);
} else {
align = align.max(field.align);
}
size = cmp::max(size, field.size);
}
return Ok(tcx.intern_layout(LayoutDetails {
variants: Variants::Single { index: 0 },
fields: FieldPlacement::Union(variants[0].len()),
abi: Abi::Aggregate { sized: true },
align,
size: size.abi_align(align)
}));
}
// A variant is absent if it's uninhabited and only has ZST fields.
// Present uninhabited variants only require space for their fields,
// but *not* an encoding of the discriminant (e.g. a tag value).
// See issue #49298 for more details on the need to leave space
// for non-ZST uninhabited data (mostly partial initialization).
let absent = |fields: &[TyLayout]| {
let uninhabited = fields.iter().any(|f| f.abi == Abi::Uninhabited);
let is_zst = fields.iter().all(|f| f.is_zst());
uninhabited && is_zst
};
let (present_first, present_second) = {
let mut present_variants = (0..variants.len()).filter(|&v| {
!absent(&variants[v])
});
(present_variants.next(), present_variants.next())
};
if present_first.is_none() {
// Uninhabited because it has no variants, or only absent ones.
return tcx.layout_raw(param_env.and(tcx.types.never));
}
let is_struct = !def.is_enum() ||
// Only one variant is present.
(present_second.is_none() &&
// Representation optimizations are allowed.
!def.repr.inhibit_enum_layout_opt());
if is_struct {
// Struct, or univariant enum equivalent to a struct.
// (Typechecking will reject discriminant-sizing attrs.)
let v = present_first.unwrap();
let kind = if def.is_enum() || variants[v].len() == 0 {
StructKind::AlwaysSized
} else {
let param_env = tcx.param_env(def.did);
let last_field = def.variants[v].fields.last().unwrap();
let always_sized = tcx.type_of(last_field.did)
.is_sized(tcx.at(DUMMY_SP), param_env);
if !always_sized { StructKind::MaybeUnsized }
else { StructKind::AlwaysSized }
};
let mut st = univariant_uninterned(&variants[v], &def.repr, kind)?;
st.variants = Variants::Single { index: v };
// Exclude 0 from the range of a newtype ABI NonZero<T>.
if Some(def.did) == self.tcx.lang_items().non_zero() {
match st.abi {
Abi::Scalar(ref mut scalar) |
Abi::ScalarPair(ref mut scalar, _) => {
if *scalar.valid_range.start() == 0 {
scalar.valid_range = 1..=*scalar.valid_range.end();
}
}
_ => {}
}
}
return Ok(tcx.intern_layout(st));
}
// The current code for niche-filling relies on variant indices
// instead of actual discriminants, so dataful enums with
// explicit discriminants (RFC #2363) would misbehave.
let no_explicit_discriminants = def.variants.iter().enumerate()
.all(|(i, v)| v.discr == ty::VariantDiscr::Relative(i));
// Niche-filling enum optimization.
if !def.repr.inhibit_enum_layout_opt() && no_explicit_discriminants {
let mut dataful_variant = None;
let mut niche_variants = usize::max_value()..=0;
// Find one non-ZST variant.
'variants: for (v, fields) in variants.iter().enumerate() {
if absent(fields) {
continue 'variants;
}
for f in fields {
if !f.is_zst() {
if dataful_variant.is_none() {
dataful_variant = Some(v);
continue 'variants;
} else {
dataful_variant = None;
break 'variants;
}
}
}
niche_variants = *niche_variants.start().min(&v)..=v;
}
if niche_variants.start() > niche_variants.end() {
dataful_variant = None;
}
if let Some(i) = dataful_variant {
let count = (niche_variants.end() - niche_variants.start() + 1) as u128;
for (field_index, &field) in variants[i].iter().enumerate() {
let (offset, niche, niche_start) =
match self.find_niche(field, count)? {
Some(niche) => niche,
None => continue
};
let mut align = dl.aggregate_align;
let st = variants.iter().enumerate().map(|(j, v)| {
let mut st = univariant_uninterned(v,
&def.repr, StructKind::AlwaysSized)?;
st.variants = Variants::Single { index: j };
align = align.max(st.align);
Ok(st)
}).collect::<Result<Vec<_>, _>>()?;
let offset = st[i].fields.offset(field_index) + offset;
let size = st[i].size;
let mut abi = match st[i].abi {
Abi::Scalar(_) => Abi::Scalar(niche.clone()),
Abi::ScalarPair(ref first, ref second) => {
// We need to use scalar_unit to reset the
// valid range to the maximal one for that
// primitive, because only the niche is
// guaranteed to be initialised, not the
// other primitive.
if offset.bytes() == 0 {
Abi::ScalarPair(niche.clone(), scalar_unit(second.value))
} else {
Abi::ScalarPair(scalar_unit(first.value), niche.clone())
}
}
_ => Abi::Aggregate { sized: true },
};
if st.iter().all(|v| v.abi == Abi::Uninhabited) {
abi = Abi::Uninhabited;
}
return Ok(tcx.intern_layout(LayoutDetails {
variants: Variants::NicheFilling {
dataful_variant: i,
niche_variants,
niche,
niche_start,
variants: st,
},
fields: FieldPlacement::Arbitrary {
offsets: vec![offset],
memory_index: vec![0]
},
abi,
size,
align,
}));
}
}
}
let (mut min, mut max) = (i128::max_value(), i128::min_value());
let discr_type = def.repr.discr_type();
let bits = Integer::from_attr(tcx, discr_type).size().bits();
for (i, discr) in def.discriminants(tcx).enumerate() {
if variants[i].iter().any(|f| f.abi == Abi::Uninhabited) {
continue;
}
let mut x = discr.val as i128;
if discr_type.is_signed() {
// sign extend the raw representation to be an i128
x = (x << (128 - bits)) >> (128 - bits);
}
if x < min { min = x; }
if x > max { max = x; }
}
// We might have no inhabited variants, so pretend there's at least one.
if (min, max) == (i128::max_value(), i128::min_value()) {
min = 0;
max = 0;
}
assert!(min <= max, "discriminant range is {}...{}", min, max);
let (min_ity, signed) = Integer::repr_discr(tcx, ty, &def.repr, min, max);
let mut align = dl.aggregate_align;
let mut size = Size::from_bytes(0);
// We're interested in the smallest alignment, so start large.
let mut start_align = Align::from_bytes(256, 256).unwrap();
assert_eq!(Integer::for_abi_align(dl, start_align), None);
// repr(C) on an enum tells us to make a (tag, union) layout,
// so we need to grow the prefix alignment to be at least
// the alignment of the union. (This value is used both for
// determining the alignment of the overall enum, and the
// determining the alignment of the payload after the tag.)
let mut prefix_align = min_ity.align(dl);
if def.repr.c() {
for fields in &variants {
for field in fields {
prefix_align = prefix_align.max(field.align);
}
}
}
// Create the set of structs that represent each variant.
let mut layout_variants = variants.iter().enumerate().map(|(i, field_layouts)| {
let mut st = univariant_uninterned(&field_layouts,
&def.repr, StructKind::Prefixed(min_ity.size(), prefix_align))?;
st.variants = Variants::Single { index: i };
// Find the first field we can't move later
// to make room for a larger discriminant.
for field in st.fields.index_by_increasing_offset().map(|j| field_layouts[j]) {
if !field.is_zst() || field.align.abi() != 1 {
start_align = start_align.min(field.align);
break;
}
}
size = cmp::max(size, st.size);
align = align.max(st.align);
Ok(st)
}).collect::<Result<Vec<_>, _>>()?;
// Align the maximum variant size to the largest alignment.
size = size.abi_align(align);
if size.bytes() >= dl.obj_size_bound() {
return Err(LayoutError::SizeOverflow(ty));
}
let typeck_ity = Integer::from_attr(dl, def.repr.discr_type());
if typeck_ity < min_ity {
// It is a bug if Layout decided on a greater discriminant size than typeck for
// some reason at this point (based on values discriminant can take on). Mostly
// because this discriminant will be loaded, and then stored into variable of
// type calculated by typeck. Consider such case (a bug): typeck decided on
// byte-sized discriminant, but layout thinks we need a 16-bit to store all
// discriminant values. That would be a bug, because then, in codegen, in order
// to store this 16-bit discriminant into 8-bit sized temporary some of the
// space necessary to represent would have to be discarded (or layout is wrong
// on thinking it needs 16 bits)
bug!("layout decided on a larger discriminant type ({:?}) than typeck ({:?})",
min_ity, typeck_ity);
// However, it is fine to make discr type however large (as an optimisation)
// after this point – we’ll just truncate the value we load in codegen.
}
// Check to see if we should use a different type for the
// discriminant. We can safely use a type with the same size
// as the alignment of the first field of each variant.
// We increase the size of the discriminant to avoid LLVM copying
// padding when it doesn't need to. This normally causes unaligned
// load/stores and excessive memcpy/memset operations. By using a
// bigger integer size, LLVM can be sure about its contents and
// won't be so conservative.
// Use the initial field alignment
let mut ity = if def.repr.c() || def.repr.int.is_some() {
min_ity
} else {
Integer::for_abi_align(dl, start_align).unwrap_or(min_ity)
};
// If the alignment is not larger than the chosen discriminant size,
// don't use the alignment as the final size.
if ity <= min_ity {
ity = min_ity;
} else {
// Patch up the variants' first few fields.
let old_ity_size = min_ity.size();
let new_ity_size = ity.size();
for variant in &mut layout_variants {
match variant.fields {
FieldPlacement::Arbitrary { ref mut offsets, .. } => {
for i in offsets {
if *i <= old_ity_size {
assert_eq!(*i, old_ity_size);
*i = new_ity_size;
}
}
// We might be making the struct larger.
if variant.size <= old_ity_size {
variant.size = new_ity_size;
}
}
_ => bug!()
}
}
}
let tag_mask = !0u128 >> (128 - ity.size().bits());
let tag = Scalar {
value: Int(ity, signed),
valid_range: (min as u128 & tag_mask)..=(max as u128 & tag_mask),
};
let mut abi = Abi::Aggregate { sized: true };
if tag.value.size(dl) == size {
abi = Abi::Scalar(tag.clone());
} else if !tag.is_bool() {
// HACK(nox): Blindly using ScalarPair for all tagged enums
// where applicable leads to Option<u8> being handled as {i1, i8},
// which later confuses SROA and some loop optimisations,
// ultimately leading to the repeat-trusted-len test
// failing. We make the trade-off of using ScalarPair only
// for types where the tag isn't a boolean.
let mut common_prim = None;
for (field_layouts, layout_variant) in variants.iter().zip(&layout_variants) {
let offsets = match layout_variant.fields {
FieldPlacement::Arbitrary { ref offsets, .. } => offsets,
_ => bug!(),
};
let mut fields = field_layouts
.iter()
.zip(offsets)
.filter(|p| !p.0.is_zst());
let (field, offset) = match (fields.next(), fields.next()) {
(None, None) => continue,
(Some(pair), None) => pair,
_ => {
common_prim = None;
break;
}
};
let prim = match field.details.abi {
Abi::Scalar(ref scalar) => scalar.value,
_ => {
common_prim = None;
break;
}
};
if let Some(pair) = common_prim {
// This is pretty conservative. We could go fancier
// by conflating things like i32 and u32, or even
// realising that (u8, u8) could just cohabit with
// u16 or even u32.
if pair != (prim, offset) {
common_prim = None;
break;
}
} else {
common_prim = Some((prim, offset));
}
}
if let Some((prim, offset)) = common_prim {
let pair = scalar_pair(tag.clone(), scalar_unit(prim));
let pair_offsets = match pair.fields {
FieldPlacement::Arbitrary {
ref offsets,
ref memory_index
} => {
assert_eq!(memory_index, &[0, 1]);
offsets
}
_ => bug!()
};
if pair_offsets[0] == Size::from_bytes(0) &&
pair_offsets[1] == *offset &&
align == pair.align &&
size == pair.size {
// We can use `ScalarPair` only when it matches our
// already computed layout (including `#[repr(C)]`).
abi = pair.abi;
}
}
}
if layout_variants.iter().all(|v| v.abi == Abi::Uninhabited) {
abi = Abi::Uninhabited;
}
tcx.intern_layout(LayoutDetails {
variants: Variants::Tagged {
tag,
variants: layout_variants,
},
fields: FieldPlacement::Arbitrary {
offsets: vec![Size::from_bytes(0)],
memory_index: vec![0]
},
abi,
align,
size
})
}
// Types with no meaningful known layout.
ty::TyProjection(_) | ty::TyAnon(..) => {
let normalized = tcx.normalize_erasing_regions(param_env, ty);
if ty == normalized {
return Err(LayoutError::Unknown(ty));
}
tcx.layout_raw(param_env.and(normalized))?
}
ty::TyParam(_) => {
return Err(LayoutError::Unknown(ty));
}
ty::TyGeneratorWitness(..) | ty::TyInfer(_) | ty::TyError => {
bug!("LayoutDetails::compute: unexpected type `{}`", ty)
}
})
}
/// This is invoked by the `layout_raw` query to record the final
/// layout of each type.
#[inline]
fn record_layout_for_printing(self, layout: TyLayout<'tcx>) {
// If we are running with `-Zprint-type-sizes`, record layouts for
// dumping later. Ignore layouts that are done with non-empty
// environments or non-monomorphic layouts, as the user only wants
// to see the stuff resulting from the final codegen session.
if
!self.tcx.sess.opts.debugging_opts.print_type_sizes ||
layout.ty.has_param_types() ||
layout.ty.has_self_ty() ||
!self.param_env.caller_bounds.is_empty()
{
return;
}
self.record_layout_for_printing_outlined(layout)
}
fn record_layout_for_printing_outlined(self, layout: TyLayout<'tcx>) {
// (delay format until we actually need it)
let record = |kind, packed, opt_discr_size, variants| {
let type_desc = format!("{:?}", layout.ty);
self.tcx.sess.code_stats.borrow_mut().record_type_size(kind,
type_desc,
layout.align,
layout.size,
packed,
opt_discr_size,
variants);
};
let adt_def = match layout.ty.sty {
ty::TyAdt(ref adt_def, _) => {
debug!("print-type-size t: `{:?}` process adt", layout.ty);
adt_def
}
ty::TyClosure(..) => {
debug!("print-type-size t: `{:?}` record closure", layout.ty);
record(DataTypeKind::Closure, false, None, vec![]);
return;
}
_ => {
debug!("print-type-size t: `{:?}` skip non-nominal", layout.ty);
return;
}
};
let adt_kind = adt_def.adt_kind();
let adt_packed = adt_def.repr.packed();
let build_variant_info = |n: Option<ast::Name>,
flds: &[ast::Name],
layout: TyLayout<'tcx>| {
let mut min_size = Size::from_bytes(0);
let field_info: Vec<_> = flds.iter().enumerate().map(|(i, &name)| {
match layout.field(self, i) {
Err(err) => {
bug!("no layout found for field {}: `{:?}`", name, err);
}
Ok(field_layout) => {
let offset = layout.fields.offset(i);
let field_end = offset + field_layout.size;
if min_size < field_end {
min_size = field_end;
}
session::FieldInfo {
name: name.to_string(),
offset: offset.bytes(),
size: field_layout.size.bytes(),
align: field_layout.align.abi(),
}
}
}
}).collect();
session::VariantInfo {
name: n.map(|n|n.to_string()),
kind: if layout.is_unsized() {
session::SizeKind::Min
} else {
session::SizeKind::Exact
},
align: layout.align.abi(),
size: if min_size.bytes() == 0 {
layout.size.bytes()
} else {
min_size.bytes()
},
fields: field_info,
}
};
match layout.variants {
Variants::Single { index } => {
debug!("print-type-size `{:#?}` variant {}",
layout, adt_def.variants[index].name);
if !adt_def.variants.is_empty() {
let variant_def = &adt_def.variants[index];
let fields: Vec<_> =
variant_def.fields.iter().map(|f| f.name).collect();
record(adt_kind.into(),
adt_packed,
None,
vec![build_variant_info(Some(variant_def.name),
&fields,
layout)]);
} else {
// (This case arises for *empty* enums; so give it
// zero variants.)
record(adt_kind.into(), adt_packed, None, vec![]);
}
}
Variants::NicheFilling { .. } |
Variants::Tagged { .. } => {
debug!("print-type-size `{:#?}` adt general variants def {}",
layout.ty, adt_def.variants.len());
let variant_infos: Vec<_> =
adt_def.variants.iter().enumerate().map(|(i, variant_def)| {
let fields: Vec<_> =
variant_def.fields.iter().map(|f| f.name).collect();
build_variant_info(Some(variant_def.name),
&fields,
layout.for_variant(self, i))
})
.collect();
record(adt_kind.into(), adt_packed, match layout.variants {
Variants::Tagged { ref tag, .. } => Some(tag.value.size(self)),
_ => None
}, variant_infos);
}
}
}
}
/// Type size "skeleton", i.e. the only information determining a type's size.
/// While this is conservative, (aside from constant sizes, only pointers,
/// newtypes thereof and null pointer optimized enums are allowed), it is
/// enough to statically check common usecases of transmute.
#[derive(Copy, Clone, Debug)]
pub enum SizeSkeleton<'tcx> {
/// Any statically computable Layout.
Known(Size),
/// A potentially-fat pointer.
Pointer {
/// If true, this pointer is never null.
non_zero: bool,
/// The type which determines the unsized metadata, if any,
/// of this pointer. Either a type parameter or a projection
/// depending on one, with regions erased.
tail: Ty<'tcx>
}
}
impl<'a, 'tcx> SizeSkeleton<'tcx> {
pub fn compute(ty: Ty<'tcx>,
tcx: TyCtxt<'a, 'tcx, 'tcx>,
param_env: ty::ParamEnv<'tcx>)
-> Result<SizeSkeleton<'tcx>, LayoutError<'tcx>> {
assert!(!ty.has_infer_types());
// First try computing a static layout.
let err = match tcx.layout_of(param_env.and(ty)) {
Ok(layout) => {
return Ok(SizeSkeleton::Known(layout.size));
}
Err(err) => err
};
match ty.sty {
ty::TyRef(_, pointee, _) |
ty::TyRawPtr(ty::TypeAndMut { ty: pointee, .. }) => {
let non_zero = !ty.is_unsafe_ptr();
let tail = tcx.struct_tail(pointee);
match tail.sty {
ty::TyParam(_) | ty::TyProjection(_) => {
assert!(tail.has_param_types() || tail.has_self_ty());
Ok(SizeSkeleton::Pointer {
non_zero,
tail: tcx.erase_regions(&tail)
})
}
_ => {
bug!("SizeSkeleton::compute({}): layout errored ({}), yet \
tail `{}` is not a type parameter or a projection",
ty, err, tail)
}
}
}
ty::TyAdt(def, substs) => {
// Only newtypes and enums w/ nullable pointer optimization.
if def.is_union() || def.variants.is_empty() || def.variants.len() > 2 {
return Err(err);
}
// Get a zero-sized variant or a pointer newtype.
let zero_or_ptr_variant = |i: usize| {
let fields = def.variants[i].fields.iter().map(|field| {
SizeSkeleton::compute(field.ty(tcx, substs), tcx, param_env)
});
let mut ptr = None;
for field in fields {
let field = field?;
match field {
SizeSkeleton::Known(size) => {
if size.bytes() > 0 {
return Err(err);
}
}
SizeSkeleton::Pointer {..} => {
if ptr.is_some() {
return Err(err);
}
ptr = Some(field);
}
}
}
Ok(ptr)
};
let v0 = zero_or_ptr_variant(0)?;
// Newtype.
if def.variants.len() == 1 {
if let Some(SizeSkeleton::Pointer { non_zero, tail }) = v0 {
return Ok(SizeSkeleton::Pointer {
non_zero: non_zero ||
Some(def.did) == tcx.lang_items().non_zero(),
tail,
});
} else {
return Err(err);
}
}
let v1 = zero_or_ptr_variant(1)?;
// Nullable pointer enum optimization.
match (v0, v1) {
(Some(SizeSkeleton::Pointer { non_zero: true, tail }), None) |
(None, Some(SizeSkeleton::Pointer { non_zero: true, tail })) => {
Ok(SizeSkeleton::Pointer {
non_zero: false,
tail,
})
}
_ => Err(err)
}
}
ty::TyProjection(_) | ty::TyAnon(..) => {
let normalized = tcx.normalize_erasing_regions(param_env, ty);
if ty == normalized {
Err(err)
} else {
SizeSkeleton::compute(normalized, tcx, param_env)
}
}
_ => Err(err)
}
}
pub fn same_size(self, other: SizeSkeleton) -> bool {
match (self, other) {
(SizeSkeleton::Known(a), SizeSkeleton::Known(b)) => a == b,
(SizeSkeleton::Pointer { tail: a, .. },
SizeSkeleton::Pointer { tail: b, .. }) => a == b,
_ => false
}
}
}
pub trait HasTyCtxt<'tcx>: HasDataLayout {
fn tcx<'a>(&'a self) -> TyCtxt<'a, 'tcx, 'tcx>;
}
impl<'a, 'gcx, 'tcx> HasDataLayout for TyCtxt<'a, 'gcx, 'tcx> {
fn data_layout(&self) -> &TargetDataLayout {
&self.data_layout
}
}
impl<'a, 'gcx, 'tcx> HasTyCtxt<'gcx> for TyCtxt<'a, 'gcx, 'tcx> {
fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'gcx> {
self.global_tcx()
}
}
impl<'tcx, T: HasDataLayout> HasDataLayout for LayoutCx<'tcx, T> {
fn data_layout(&self) -> &TargetDataLayout {
self.tcx.data_layout()
}
}
impl<'gcx, 'tcx, T: HasTyCtxt<'gcx>> HasTyCtxt<'gcx> for LayoutCx<'tcx, T> {
fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'gcx> {
self.tcx.tcx()
}
}
pub trait MaybeResult<T> {
fn from_ok(x: T) -> Self;
fn map_same<F: FnOnce(T) -> T>(self, f: F) -> Self;
}
impl<T> MaybeResult<T> for T {
fn from_ok(x: T) -> Self {
x
}
fn map_same<F: FnOnce(T) -> T>(self, f: F) -> Self {
f(self)
}
}
impl<T, E> MaybeResult<T> for Result<T, E> {
fn from_ok(x: T) -> Self {
Ok(x)
}
fn map_same<F: FnOnce(T) -> T>(self, f: F) -> Self {
self.map(f)
}
}
pub type TyLayout<'tcx> = ::rustc_target::abi::TyLayout<'tcx, Ty<'tcx>>;
impl<'a, 'tcx> LayoutOf for LayoutCx<'tcx, TyCtxt<'a, 'tcx, 'tcx>> {
type Ty = Ty<'tcx>;
type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
/// Computes the layout of a type. Note that this implicitly
/// executes in "reveal all" mode.
fn layout_of(self, ty: Ty<'tcx>) -> Self::TyLayout {
let param_env = self.param_env.with_reveal_all();
let ty = self.tcx.normalize_erasing_regions(param_env, ty);
let details = self.tcx.layout_raw(param_env.and(ty))?;
let layout = TyLayout {
ty,
details
};
// NB: This recording is normally disabled; when enabled, it
// can however trigger recursive invocations of `layout_of`.
// Therefore, we execute it *after* the main query has
// completed, to avoid problems around recursive structures
// and the like. (Admittedly, I wasn't able to reproduce a problem
// here, but it seems like the right thing to do. -nmatsakis)
self.record_layout_for_printing(layout);
Ok(layout)
}
}
impl<'a, 'tcx> LayoutOf for LayoutCx<'tcx, ty::maps::TyCtxtAt<'a, 'tcx, 'tcx>> {
type Ty = Ty<'tcx>;
type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
/// Computes the layout of a type. Note that this implicitly
/// executes in "reveal all" mode.
fn layout_of(self, ty: Ty<'tcx>) -> Self::TyLayout {
let param_env = self.param_env.with_reveal_all();
let ty = self.tcx.normalize_erasing_regions(param_env, ty);
let details = self.tcx.layout_raw(param_env.and(ty))?;
let layout = TyLayout {
ty,
details
};
// NB: This recording is normally disabled; when enabled, it
// can however trigger recursive invocations of `layout_of`.
// Therefore, we execute it *after* the main query has
// completed, to avoid problems around recursive structures
// and the like. (Admittedly, I wasn't able to reproduce a problem
// here, but it seems like the right thing to do. -nmatsakis)
let cx = LayoutCx {
tcx: *self.tcx,
param_env: self.param_env
};
cx.record_layout_for_printing(layout);
Ok(layout)
}
}
// Helper (inherent) `layout_of` methods to avoid pushing `LayoutCx` to users.
impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
/// Computes the layout of a type. Note that this implicitly
/// executes in "reveal all" mode.
#[inline]
pub fn layout_of(self, param_env_and_ty: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
-> Result<TyLayout<'tcx>, LayoutError<'tcx>> {
let cx = LayoutCx {
tcx: self,
param_env: param_env_and_ty.param_env
};
cx.layout_of(param_env_and_ty.value)
}
}
impl<'a, 'tcx> ty::maps::TyCtxtAt<'a, 'tcx, 'tcx> {
/// Computes the layout of a type. Note that this implicitly
/// executes in "reveal all" mode.
#[inline]
pub fn layout_of(self, param_env_and_ty: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
-> Result<TyLayout<'tcx>, LayoutError<'tcx>> {
let cx = LayoutCx {
tcx: self,
param_env: param_env_and_ty.param_env
};
cx.layout_of(param_env_and_ty.value)
}
}
impl<'a, 'tcx, C> TyLayoutMethods<'tcx, C> for Ty<'tcx>
where C: LayoutOf<Ty = Ty<'tcx>> + HasTyCtxt<'tcx>,
C::TyLayout: MaybeResult<TyLayout<'tcx>>
{
fn for_variant(this: TyLayout<'tcx>, cx: C, variant_index: usize) -> TyLayout<'tcx> {
let details = match this.variants {
Variants::Single { index } if index == variant_index => this.details,
Variants::Single { index } => {
// Deny calling for_variant more than once for non-Single enums.
cx.layout_of(this.ty).map_same(|layout| {
assert_eq!(layout.variants, Variants::Single { index });
layout
});
let fields = match this.ty.sty {
ty::TyAdt(def, _) => def.variants[variant_index].fields.len(),
_ => bug!()
};
let tcx = cx.tcx();
tcx.intern_layout(LayoutDetails {
variants: Variants::Single { index: variant_index },
fields: FieldPlacement::Union(fields),
abi: Abi::Uninhabited,
align: tcx.data_layout.i8_align,
size: Size::from_bytes(0)
})
}
Variants::NicheFilling { ref variants, .. } |
Variants::Tagged { ref variants, .. } => {
&variants[variant_index]
}
};
assert_eq!(details.variants, Variants::Single { index: variant_index });
TyLayout {
ty: this.ty,
details
}
}
fn field(this: TyLayout<'tcx>, cx: C, i: usize) -> C::TyLayout {
let tcx = cx.tcx();
cx.layout_of(match this.ty.sty {
ty::TyBool |
ty::TyChar |
ty::TyInt(_) |
ty::TyUint(_) |
ty::TyFloat(_) |
ty::TyFnPtr(_) |
ty::TyNever |
ty::TyFnDef(..) |
ty::TyGeneratorWitness(..) |
ty::TyForeign(..) |
ty::TyDynamic(..) => {
bug!("TyLayout::field_type({:?}): not applicable", this)
}
// Potentially-fat pointers.
ty::TyRef(_, pointee, _) |
ty::TyRawPtr(ty::TypeAndMut { ty: pointee, .. }) => {
assert!(i < 2);
// Reuse the fat *T type as its own thin pointer data field.
// This provides information about e.g. DST struct pointees
// (which may have no non-DST form), and will work as long
// as the `Abi` or `FieldPlacement` is checked by users.
if i == 0 {
let nil = tcx.mk_nil();
let ptr_ty = if this.ty.is_unsafe_ptr() {
tcx.mk_mut_ptr(nil)
} else {
tcx.mk_mut_ref(tcx.types.re_static, nil)
};
return cx.layout_of(ptr_ty).map_same(|mut ptr_layout| {
ptr_layout.ty = this.ty;
ptr_layout
});
}
match tcx.struct_tail(pointee).sty {
ty::TySlice(_) |
ty::TyStr => tcx.types.usize,
ty::TyDynamic(..) => {
// FIXME(eddyb) use an usize/fn() array with
// the correct number of vtables slots.
tcx.mk_imm_ref(tcx.types.re_static, tcx.mk_nil())
}
_ => bug!("TyLayout::field_type({:?}): not applicable", this)
}
}
// Arrays and slices.
ty::TyArray(element, _) |
ty::TySlice(element) => element,
ty::TyStr => tcx.types.u8,
// Tuples, generators and closures.
ty::TyClosure(def_id, ref substs) => {
substs.upvar_tys(def_id, tcx).nth(i).unwrap()
}
ty::TyGenerator(def_id, ref substs, _) => {
substs.field_tys(def_id, tcx).nth(i).unwrap()
}
ty::TyTuple(tys) => tys[i],
// SIMD vector types.
ty::TyAdt(def, ..) if def.repr.simd() => {
this.ty.simd_type(tcx)
}
// ADTs.
ty::TyAdt(def, substs) => {
match this.variants {
Variants::Single { index } => {
def.variants[index].fields[i].ty(tcx, substs)
}
// Discriminant field for enums (where applicable).
Variants::Tagged { tag: ref discr, .. } |
Variants::NicheFilling { niche: ref discr, .. } => {
assert_eq!(i, 0);
let layout = LayoutDetails::scalar(tcx, discr.clone());
return MaybeResult::from_ok(TyLayout {
details: tcx.intern_layout(layout),
ty: discr.value.to_ty(tcx)
});
}
}
}
ty::TyProjection(_) | ty::TyAnon(..) | ty::TyParam(_) |
ty::TyInfer(_) | ty::TyError => {
bug!("TyLayout::field_type: unexpected type `{}`", this.ty)
}
})
}
}
impl<'a, 'tcx> LayoutCx<'tcx, TyCtxt<'a, 'tcx, 'tcx>> {
/// Find the offset of a niche leaf field, starting from
/// the given type and recursing through aggregates, which
/// has at least `count` consecutive invalid values.
/// The tuple is `(offset, scalar, niche_value)`.
// FIXME(eddyb) traverse already optimized enums.
fn find_niche(self, layout: TyLayout<'tcx>, count: u128)
-> Result<Option<(Size, Scalar, u128)>, LayoutError<'tcx>>
{
let scalar_component = |scalar: &Scalar, offset| {
let Scalar { value, valid_range: ref v } = *scalar;
let bits = value.size(self).bits();
assert!(bits <= 128);
let max_value = !0u128 >> (128 - bits);
// Find out how many values are outside the valid range.
let niches = if v.start() <= v.end() {
v.start() + (max_value - v.end())
} else {
v.start() - v.end() - 1
};
// Give up if we can't fit `count` consecutive niches.
if count > niches {
return None;
}
let niche_start = v.end().wrapping_add(1) & max_value;
let niche_end = v.end().wrapping_add(count) & max_value;
Some((offset, Scalar {
value,
valid_range: *v.start()..=niche_end
}, niche_start))
};
// Locals variables which live across yields are stored
// in the generator type as fields. These may be uninitialized
// so we don't look for niches there.
if let ty::TyGenerator(..) = layout.ty.sty {
return Ok(None);
}
match layout.abi {
Abi::Scalar(ref scalar) => {
return Ok(scalar_component(scalar, Size::from_bytes(0)));
}
Abi::ScalarPair(ref a, ref b) => {
return Ok(scalar_component(a, Size::from_bytes(0)).or_else(|| {
scalar_component(b, a.value.size(self).abi_align(b.value.align(self)))
}));
}
Abi::Vector { ref element, .. } => {
return Ok(scalar_component(element, Size::from_bytes(0)));
}
_ => {}
}
// Perhaps one of the fields is non-zero, let's recurse and find out.
if let FieldPlacement::Union(_) = layout.fields {
// Only Rust enums have safe-to-inspect fields
// (a discriminant), other unions are unsafe.
if let Variants::Single { .. } = layout.variants {
return Ok(None);
}
}
if let FieldPlacement::Array { .. } = layout.fields {
if layout.fields.count() > 0 {
return self.find_niche(layout.field(self, 0)?, count);
}
}
for i in 0..layout.fields.count() {
let r = self.find_niche(layout.field(self, i)?, count)?;
if let Some((offset, scalar, niche_value)) = r {
let offset = layout.fields.offset(i) + offset;
return Ok(Some((offset, scalar, niche_value)));
}
}
Ok(None)
}
}
impl<'a> HashStable<StableHashingContext<'a>> for Variants {
fn hash_stable<W: StableHasherResult>(&self,
hcx: &mut StableHashingContext<'a>,
hasher: &mut StableHasher<W>) {
use ty::layout::Variants::*;
mem::discriminant(self).hash_stable(hcx, hasher);
match *self {
Single { index } => {
index.hash_stable(hcx, hasher);
}
Tagged {
ref tag,
ref variants,
} => {
tag.hash_stable(hcx, hasher);
variants.hash_stable(hcx, hasher);
}
NicheFilling {
dataful_variant,
ref niche_variants,
ref niche,
niche_start,
ref variants,
} => {
dataful_variant.hash_stable(hcx, hasher);
niche_variants.start().hash_stable(hcx, hasher);
niche_variants.end().hash_stable(hcx, hasher);
niche.hash_stable(hcx, hasher);
niche_start.hash_stable(hcx, hasher);
variants.hash_stable(hcx, hasher);
}
}
}
}
impl<'a> HashStable<StableHashingContext<'a>> for FieldPlacement {
fn hash_stable<W: StableHasherResult>(&self,
hcx: &mut StableHashingContext<'a>,
hasher: &mut StableHasher<W>) {
use ty::layout::FieldPlacement::*;
mem::discriminant(self).hash_stable(hcx, hasher);
match *self {
Union(count) => {
count.hash_stable(hcx, hasher);
}
Array { count, stride } => {
count.hash_stable(hcx, hasher);
stride.hash_stable(hcx, hasher);
}
Arbitrary { ref offsets, ref memory_index } => {
offsets.hash_stable(hcx, hasher);
memory_index.hash_stable(hcx, hasher);
}
}
}
}
impl<'a> HashStable<StableHashingContext<'a>> for Abi {
fn hash_stable<W: StableHasherResult>(&self,
hcx: &mut StableHashingContext<'a>,
hasher: &mut StableHasher<W>) {
use ty::layout::Abi::*;
mem::discriminant(self).hash_stable(hcx, hasher);
match *self {
Uninhabited => {}
Scalar(ref value) => {
value.hash_stable(hcx, hasher);
}
ScalarPair(ref a, ref b) => {
a.hash_stable(hcx, hasher);
b.hash_stable(hcx, hasher);
}
Vector { ref element, count } => {
element.hash_stable(hcx, hasher);
count.hash_stable(hcx, hasher);
}
Aggregate { sized } => {
sized.hash_stable(hcx, hasher);
}
}
}
}
impl<'a> HashStable<StableHashingContext<'a>> for Scalar {
fn hash_stable<W: StableHasherResult>(&self,
hcx: &mut StableHashingContext<'a>,
hasher: &mut StableHasher<W>) {
let Scalar { value, ref valid_range } = *self;
value.hash_stable(hcx, hasher);
valid_range.start().hash_stable(hcx, hasher);
valid_range.end().hash_stable(hcx, hasher);
}
}
impl_stable_hash_for!(struct ::ty::layout::LayoutDetails {
variants,
fields,
abi,
size,
align
});
impl_stable_hash_for!(enum ::ty::layout::Integer {
I8,
I16,
I32,
I64,
I128
});
impl_stable_hash_for!(enum ::ty::layout::Primitive {
Int(integer, signed),
F32,
F64,
Pointer
});
impl<'gcx> HashStable<StableHashingContext<'gcx>> for Align {
fn hash_stable<W: StableHasherResult>(&self,
hcx: &mut StableHashingContext<'gcx>,
hasher: &mut StableHasher<W>) {
self.abi().hash_stable(hcx, hasher);
self.pref().hash_stable(hcx, hasher);
}
}
impl<'gcx> HashStable<StableHashingContext<'gcx>> for Size {
fn hash_stable<W: StableHasherResult>(&self,
hcx: &mut StableHashingContext<'gcx>,
hasher: &mut StableHasher<W>) {
self.bytes().hash_stable(hcx, hasher);
}
}
impl<'a, 'gcx> HashStable<StableHashingContext<'a>> for LayoutError<'gcx>
{
fn hash_stable<W: StableHasherResult>(&self,
hcx: &mut StableHashingContext<'a>,
hasher: &mut StableHasher<W>) {
use ty::layout::LayoutError::*;
mem::discriminant(self).hash_stable(hcx, hasher);
match *self {
Unknown(t) |
SizeOverflow(t) => t.hash_stable(hcx, hasher)
}
}
}
| 41.087435 | 100 | 0.447864 |
5b4e8e88dd99b390225066bbd5001288f563e8e7 | 9,711 | extern crate regex;
use std::fs;
use std::cmp;
use regex::Regex;
fn main() {
let input = read_input();
let result = process(&input);
println!("Result: {}\n", result);
}
fn read_input() -> String {
let input_filename = String::from("input.txt");
fs::read_to_string(input_filename)
.expect("Failed to read file")
}
fn process(input: &str) -> i32 {
let points = Point::from_lines(&input);
// Work out how large a grid we have to consider
let (max_x, max_y) = extent(&points);
// Score a grid for each of the points
let mut scored_grids = Vec::new();
for point in points {
let scored_grid = scored_grid_from(point, max_x, max_y);
scored_grids.push(scored_grid);
}
// "Subtract" the grids
let cell_count = (max_x * max_y) as usize;
for cell_index in 0..cell_count {
// Get the closest cell point
let mut min_score = i32::max_value();
for grid_index in 0..scored_grids.len() {
let grid_cell_score = scored_grids[grid_index][cell_index];
min_score = cmp::min(min_score, grid_cell_score);
}
// Work out if it's uniquely close
let mut min_cells_seen = 0;
for grid_index in 0..scored_grids.len() {
let grid_cell_score = scored_grids[grid_index][cell_index];
if min_score == grid_cell_score {
min_cells_seen += 1;
}
}
// Re-score the cells as appropriate
if min_cells_seen > 1 {
// Equidistant from at least 2 points
for grid_index in 0..scored_grids.len() {
scored_grids[grid_index][cell_index] = -1;
}
} else {
// Uniquely close to one point
for grid_index in 0..scored_grids.len() {
let grid_cell_score = scored_grids[grid_index][cell_index];
if grid_cell_score == min_score {
continue;
}
scored_grids[grid_index][cell_index] = -1;
}
}
}
// Count the area left around each point
let mut areas = Vec::new();
for grid in &scored_grids {
if grid_is_infinite(grid, max_x, max_y) {
areas.push(0);
continue;
}
// Count the cells belonging to this point
let area = grid.iter().fold(0, |acc, value| {
if *value >= 0 {
return acc + 1;
} else {
return acc;
}
});
areas.push(area);
}
areas.sort();
return *areas.last().unwrap() as i32;
}
fn grid_is_infinite(grid: &Vec<i32>, extent_x: usize, extent_y: usize) -> bool {
let max = extent_x * extent_y;
let top_range = 0..extent_x;
let bottom_range = (extent_x * (extent_y - 1))..max;
for (top, bottom) in top_range.zip(bottom_range) {
if grid[top] >= 0 || grid[bottom] >= 0 {
return true;
}
}
let left_range = (0 ..max).step_by(extent_x);
let right_range = ((extent_x - 1)..max).step_by(extent_x);
for (left, right) in left_range.zip(right_range) {
if grid[left] >= 0 || grid[right] >= 0 {
return true;
}
}
return false;
}
fn scored_grid_from(point: Point, extent_x: usize, extend_y: usize) -> Vec<i32> {
let mut scores = Vec::new();
for y in 0..extend_y {
for x in 0..extent_x {
let score = ((y as i32) - point.y).abs() + ((x as i32) - point.x).abs();
scores.push(score);
}
}
return scores;
}
fn extent(points: &Vec<Point>) -> (usize, usize) {
let mut max_x = 0;
let mut max_y = 0;
for point in points {
max_x = cmp::max(max_x, point.x);
max_y = cmp::max(max_y, point.y);
}
max_x += 1;
max_y += 1;
(max_x as usize, max_y as usize)
}
//fn print_scores_as_grid(scores: &Vec<i32>, extent_x: usize, extent_y: usize) {
// println!("----[Grid]----");
// for y in 0..extent_y {
// for x in 0..extent_x {
// let index = (extent_x * y + x) as usize;
// print!("{:>4}", scores[index]);
// }
// println!("");
// }
// println!("--------------");
//}
#[derive(Debug,PartialEq)]
struct Point {
x: i32,
y: i32,
}
impl Point {
fn from_string(string: &str) -> Point {
let re = Regex::new(r"(?P<x>\d*)\D*(?P<y>\d*)").unwrap();
let captures = re.captures(string).unwrap();
return Point { x: captures["x"].parse().unwrap(), y: captures["y"].parse().unwrap() };
}
fn from_lines(lines: &str) -> Vec<Point> {
let mut points = Vec::new();
for line in lines.lines() {
let line = line.trim();
if line.len() == 0 {
continue;
}
points.push(Point::from_string(line));
}
return points;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_point_from_string() {
let subject = Point::from_string("1, 2");
assert_eq!(Point { x: 1, y: 2 }, subject);
let subject = Point::from_string("100 , 25699");
assert_eq!(Point { x: 100, y: 25699 }, subject);
}
#[test]
fn test_point_from_lines_trailing_newline() {
let subject = Point::from_lines("1, 2\n3, 4\n5, 6\n");
let expected = vec![Point {x: 1, y: 2},Point {x: 3, y: 4},Point {x: 5, y: 6},];
assert_eq!(expected, subject);
}
#[test]
fn test_point_from_lines_trailing() {
let subject = Point::from_lines("1, 2\n3, 4\n5, 6");
let expected = vec![Point {x: 1, y: 2},Point {x: 3, y: 4},Point {x: 5, y: 6},];
assert_eq!(expected, subject);
}
#[test]
fn test_extent() {
let input = vec![Point {x: 0, y: 10}, Point {x: 20, y: 0}, Point {x: 19, y: 10},];
let (max_x, max_y) = extent(&input);
assert_eq!(21, max_x);
assert_eq!(11, max_y);
}
#[test]
fn test_scored_grid_1() {
let in_point = Point { x: 1, y: 1};
let extent_x = 3;
let extent_y = 3;
let result = scored_grid_from(in_point, extent_x, extent_y);
let expected = vec![
2, 1, 2,
1, 0, 1,
2, 1, 2,
];
assert_eq!(expected, result);
}
#[test]
fn test_scored_grid_2() {
let in_point = Point { x: 1, y: 1};
let extent_x = 5;
let extent_y = 7;
let result = scored_grid_from(in_point, extent_x, extent_y);
let expected = vec![
2, 1, 2, 3, 4,
1, 0, 1, 2, 3,
2, 1, 2, 3, 4,
3, 2, 3, 4, 5,
4, 3, 4, 5, 6,
5, 4, 5, 6, 7,
6, 5, 6, 7, 8,
];
assert_eq!(expected, result);
}
#[test]
fn test_grid_is_infinite_top() {
let extent_x = 3;
let extent_y = 3;
let grid = vec![
0, -1, -1,
-1, -1, -1,
-1, -1, -1,
];
let result = grid_is_infinite(&grid, extent_x, extent_y);
assert_eq!(true, result);
let grid = vec![
-1, 0, -1,
-1, -1, -1,
-1, -1, -1,
];
let result = grid_is_infinite(&grid, extent_x, extent_y);
assert_eq!(true, result);
let grid = vec![
-1, -1, 0,
-1, -1, -1,
-1, -1, -1,
];
let result = grid_is_infinite(&grid, extent_x, extent_y);
assert_eq!(true, result);
}
#[test]
fn test_grid_is_infinite_centre() {
let extent_x = 3;
let extent_y = 3;
let grid = vec![
-1, -1, -1,
-1, -1, -1,
-1, -1, -1,
];
let result = grid_is_infinite(&grid, extent_x, extent_y);
assert_eq!(false, result);
let grid = vec![
-1, -1, -1,
-1, 0, -1,
-1, -1, -1,
];
let result = grid_is_infinite(&grid, extent_x, extent_y);
assert_eq!(false, result);
}
#[test]
fn test_grid_is_infinite_bottom() {
let extent_x = 3;
let extent_y = 3;
let grid = vec![
-1, -1, -1,
-1, -1, -1,
0, -1, -1,
];
let result = grid_is_infinite(&grid, extent_x, extent_y);
assert_eq!(true, result);
let grid = vec![
-1, -1, -1,
-1, -1, -1,
-1, 0, -1,
];
let result = grid_is_infinite(&grid, extent_x, extent_y);
assert_eq!(true, result);
let grid = vec![
-1, -1, -1,
-1, -1, -1,
-1, -1, 0,
];
let result = grid_is_infinite(&grid, extent_x, extent_y);
assert_eq!(true, result);
}
#[test]
fn test_grid_is_infinite_left() {
let extent_x = 3;
let extent_y = 3;
let grid = vec![
0, -1, -1,
-1, -1, -1,
-1, -1, -1,
];
let result = grid_is_infinite(&grid, extent_x, extent_y);
assert_eq!(true, result);
let grid = vec![
-1, -1, -1,
0, -1, -1,
-1, -1, -1,
];
let result = grid_is_infinite(&grid, extent_x, extent_y);
assert_eq!(true, result);
let grid = vec![
-1, -1, -1,
0, -1, -1,
-1, -1, -1,
];
let result = grid_is_infinite(&grid, extent_x, extent_y);
assert_eq!(true, result);
}
#[test]
fn test_example() {
let input = "1, 1\n1, 6\n8, 3\n3, 4\n5, 5\n8, 9";
let result = process(input);
assert_eq!(17, result);
}
}
| 27.125698 | 94 | 0.489239 |
56ffb3671f47db1cb81e13a5cdba85f4b4fc1991 | 707 | // if2.rs
// Step 1: Make me compile!
// Step 2: Get the bar_for_fuzz and default_to_baz tests passing!
// Execute the command `rustlings hint if2` if you want a hint :)
pub fn fizz_if_foo(fizzish: &str) -> &str {
if fizzish == "fizz" {
"foo"
}
else if fizzish == "fuzz"{
"bar"
}
else {
"baz"
}
}
// No test changes needed!
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn foo_for_fizz() {
assert_eq!(fizz_if_foo("fizz"), "foo")
}
#[test]
fn bar_for_fuzz() {
assert_eq!(fizz_if_foo("fuzz"), "bar")
}
#[test]
fn default_to_baz() {
assert_eq!(fizz_if_foo("literally anything"), "baz")
}
}
| 17.675 | 65 | 0.545969 |
614518f2dcf36a30d150d0a4f0a2769a6a46306f | 2,206 | mod predicate_pushdown;
mod queries;
use polars_core::prelude::*;
use polars_io::prelude::*;
use std::fs::File;
use std::io::{Cursor, Read, Write};
use crate::functions::{argsort_by, pearson_corr};
use crate::logical_plan::iterator::ArenaLpIter;
use crate::logical_plan::optimizer::simplify_expr::SimplifyExprRule;
use crate::logical_plan::optimizer::stack_opt::{OptimizationRule, StackOptimizer};
use crate::prelude::*;
use polars_core::chunked_array::builder::get_list_builder;
use polars_core::df;
#[cfg(feature = "temporal")]
use polars_core::export::chrono::{NaiveDate, NaiveDateTime, NaiveTime};
use std::iter::FromIterator;
fn scan_foods_csv() -> LazyFrame {
let path = "../../examples/aggregate_multiple_files_in_chunks/datasets/foods1.csv";
LazyCsvReader::new(path.to_string()).finish().unwrap()
}
#[cfg(feature = "parquet")]
fn scan_foods_parquet(par: bool) -> LazyFrame {
let path = "../../examples/aggregate_multiple_files_in_chunks/datasets/foods1.csv";
let out_path = path.replace(".csv", ".parquet");
if std::fs::metadata(&out_path).is_err() {
let df = CsvReader::from_path(path).unwrap().finish().unwrap();
let f = std::fs::File::create(&out_path).unwrap();
ParquetWriter::new(f).finish(&df);
}
LazyFrame::scan_parquet(out_path, None, false, par).unwrap()
}
pub(crate) fn fruits_cars() -> DataFrame {
df!(
"A"=> [1, 2, 3, 4, 5],
"fruits"=> ["banana", "banana", "apple", "apple", "banana"],
"B"=> [5, 4, 3, 2, 1],
"cars"=> ["beetle", "audi", "beetle", "beetle", "beetle"]
)
.unwrap()
}
// physical plan see: datafusion/physical_plan/planner.rs.html#61-63
pub(crate) fn get_df() -> DataFrame {
let s = r#"
"sepal.length","sepal.width","petal.length","petal.width","variety"
5.1,3.5,1.4,.2,"Setosa"
4.9,3,1.4,.2,"Setosa"
4.7,3.2,1.3,.2,"Setosa"
4.6,3.1,1.5,.2,"Setosa"
5,3.6,1.4,.2,"Setosa"
5.4,3.9,1.7,.4,"Setosa"
4.6,3.4,1.4,.3,"Setosa"
"#;
let file = Cursor::new(s);
let df = CsvReader::new(file)
// we also check if infer schema ignores errors
.infer_schema(Some(3))
.has_header(true)
.finish()
.unwrap();
df
}
| 30.638889 | 87 | 0.638713 |
1189aebe8ac5fa95cf4008a355957af8dbc7caf7 | 4,417 | use bevy_ecs::system::ResMut;
use bevy_utils::{Duration, Instant};
/// Tracks elapsed time since the last update and since the App has started
#[derive(Debug, Clone)]
pub struct Time {
delta: Duration,
last_update: Option<Instant>,
delta_seconds_f64: f64,
delta_seconds: f32,
seconds_since_startup: f64,
startup: Instant,
}
impl Default for Time {
fn default() -> Time {
Time {
delta: Duration::from_secs(0),
last_update: None,
startup: Instant::now(),
delta_seconds_f64: 0.0,
seconds_since_startup: 0.0,
delta_seconds: 0.0,
}
}
}
impl Time {
pub fn update(&mut self) {
let now = Instant::now();
self.update_with_instant(now);
}
pub(crate) fn update_with_instant(&mut self, instant: Instant) {
if let Some(last_update) = self.last_update {
self.delta = instant - last_update;
self.delta_seconds_f64 = self.delta.as_secs_f64();
self.delta_seconds = self.delta.as_secs_f32();
}
let duration_since_startup = instant - self.startup;
self.seconds_since_startup = duration_since_startup.as_secs_f64();
self.last_update = Some(instant);
}
/// The delta between the current tick and last tick as a [`Duration`]
#[inline]
pub fn delta(&self) -> Duration {
self.delta
}
/// The delta between the current and last tick as [`f32`] seconds
#[inline]
pub fn delta_seconds(&self) -> f32 {
self.delta_seconds
}
/// The delta between the current and last tick as [`f64`] seconds
#[inline]
pub fn delta_seconds_f64(&self) -> f64 {
self.delta_seconds_f64
}
/// The time since startup in seconds
#[inline]
pub fn seconds_since_startup(&self) -> f64 {
self.seconds_since_startup
}
/// The [`Instant`] the app was started
#[inline]
pub fn startup(&self) -> Instant {
self.startup
}
/// The ['Instant'] when [`Time::update`] was last called, if it exists
#[inline]
pub fn last_update(&self) -> Option<Instant> {
self.last_update
}
pub fn time_since_startup(&self) -> Duration {
Instant::now() - self.startup
}
}
pub(crate) fn time_system(mut time: ResMut<Time>) {
time.update();
}
#[cfg(test)]
#[allow(clippy::float_cmp)]
mod tests {
use super::Time;
use bevy_utils::{Duration, Instant};
#[test]
fn update_test() {
let start_instant = Instant::now();
// Create a `Time` for testing
let mut time = Time {
startup: start_instant,
..Default::default()
};
// Ensure `time` was constructed correctly
assert_eq!(time.delta(), Duration::from_secs(0));
assert_eq!(time.last_update(), None);
assert_eq!(time.startup(), start_instant);
assert_eq!(time.delta_seconds_f64(), 0.0);
assert_eq!(time.seconds_since_startup(), 0.0);
assert_eq!(time.delta_seconds(), 0.0);
// Update `time` and check results
let first_update_instant = Instant::now();
time.update_with_instant(first_update_instant);
assert_eq!(time.delta(), Duration::from_secs(0));
assert_eq!(time.last_update(), Some(first_update_instant));
assert_eq!(time.startup(), start_instant);
assert_eq!(time.delta_seconds_f64(), 0.0);
assert_eq!(
time.seconds_since_startup(),
(first_update_instant - start_instant).as_secs_f64()
);
assert_eq!(time.delta_seconds, 0.0);
// Update `time` again and check results
let second_update_instant = Instant::now();
time.update_with_instant(second_update_instant);
assert_eq!(time.delta(), second_update_instant - first_update_instant);
assert_eq!(time.last_update(), Some(second_update_instant));
assert_eq!(time.startup(), start_instant);
// At this point its safe to use time.delta as a valid value
// because it's been previously verified to be correct
assert_eq!(time.delta_seconds_f64(), time.delta().as_secs_f64());
assert_eq!(
time.seconds_since_startup(),
(second_update_instant - start_instant).as_secs_f64()
);
assert_eq!(time.delta_seconds(), time.delta().as_secs_f32());
}
}
| 29.844595 | 79 | 0.614444 |
de1cdde0cf9a9d471586639a6dffa487b9185a0d | 16,337 | //! Request extractors
use std::{
convert::Infallible,
future::Future,
pin::Pin,
task::{Context, Poll},
};
use actix_http::{Method, Uri};
use actix_utils::future::{ok, Ready};
use futures_core::ready;
use pin_project_lite::pin_project;
use crate::{dev::Payload, Error, HttpRequest};
/// A type that implements [`FromRequest`] is called an **extractor** and can extract data from
/// the request. Some types that implement this trait are: [`Json`], [`Header`], and [`Path`].
///
/// # Configuration
/// An extractor can be customized by injecting the corresponding configuration with one of:
///
/// - [`App::app_data()`][crate::App::app_data]
/// - [`Scope::app_data()`][crate::Scope::app_data]
/// - [`Resource::app_data()`][crate::Resource::app_data]
///
/// Here are some built-in extractors and their corresponding configuration.
/// Please refer to the respective documentation for details.
///
/// | Extractor | Configuration |
/// |-------------|-------------------|
/// | [`Header`] | _None_ |
/// | [`Path`] | [`PathConfig`] |
/// | [`Json`] | [`JsonConfig`] |
/// | [`Form`] | [`FormConfig`] |
/// | [`Query`] | [`QueryConfig`] |
/// | [`Bytes`] | [`PayloadConfig`] |
/// | [`String`] | [`PayloadConfig`] |
/// | [`Payload`] | [`PayloadConfig`] |
///
/// # Implementing An Extractor
/// To reduce duplicate code in handlers where extracting certain parts of a request has a common
/// structure, you can implement `FromRequest` for your own types.
///
/// Note that the request payload can only be consumed by one extractor.
///
/// [`Header`]: crate::web::Header
/// [`Json`]: crate::web::Json
/// [`JsonConfig`]: crate::web::JsonConfig
/// [`Form`]: crate::web::Form
/// [`FormConfig`]: crate::web::FormConfig
/// [`Path`]: crate::web::Path
/// [`PathConfig`]: crate::web::PathConfig
/// [`Query`]: crate::web::Query
/// [`QueryConfig`]: crate::web::QueryConfig
/// [`Payload`]: crate::web::Payload
/// [`PayloadConfig`]: crate::web::PayloadConfig
/// [`String`]: FromRequest#impl-FromRequest-for-String
/// [`Bytes`]: crate::web::Bytes#impl-FromRequest
/// [`Either`]: crate::web::Either
#[doc(alias = "extract", alias = "extractor")]
pub trait FromRequest: Sized {
/// The associated error which can be returned.
type Error: Into<Error>;
/// Future that resolves to a Self.
type Future: Future<Output = Result<Self, Self::Error>>;
/// Create a Self from request parts asynchronously.
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future;
/// Create a Self from request head asynchronously.
///
/// This method is short for `T::from_request(req, &mut Payload::None)`.
fn extract(req: &HttpRequest) -> Self::Future {
Self::from_request(req, &mut Payload::None)
}
}
/// Optionally extract a field from the request
///
/// If the FromRequest for T fails, return None rather than returning an error response
///
/// # Examples
/// ```
/// use actix_web::{web, dev, App, Error, HttpRequest, FromRequest};
/// use actix_web::error::ErrorBadRequest;
/// use futures_util::future::{ok, err, Ready};
/// use serde::Deserialize;
/// use rand;
///
/// #[derive(Debug, Deserialize)]
/// struct Thing {
/// name: String
/// }
///
/// impl FromRequest for Thing {
/// type Error = Error;
/// type Future = Ready<Result<Self, Self::Error>>;
///
/// fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future {
/// if rand::random() {
/// ok(Thing { name: "thingy".into() })
/// } else {
/// err(ErrorBadRequest("no luck"))
/// }
///
/// }
/// }
///
/// /// extract `Thing` from request
/// async fn index(supplied_thing: Option<Thing>) -> String {
/// match supplied_thing {
/// // Puns not intended
/// Some(thing) => format!("Got something: {:?}", thing),
/// None => format!("No thing!")
/// }
/// }
///
/// fn main() {
/// let app = App::new().service(
/// web::resource("/users/:first").route(
/// web::post().to(index))
/// );
/// }
/// ```
impl<T: 'static> FromRequest for Option<T>
where
T: FromRequest,
T::Future: 'static,
{
type Error = Error;
type Future = FromRequestOptFuture<T::Future>;
#[inline]
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
FromRequestOptFuture {
fut: T::from_request(req, payload),
}
}
}
pin_project! {
pub struct FromRequestOptFuture<Fut> {
#[pin]
fut: Fut,
}
}
impl<Fut, T, E> Future for FromRequestOptFuture<Fut>
where
Fut: Future<Output = Result<T, E>>,
E: Into<Error>,
{
type Output = Result<Option<T>, Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
let res = ready!(this.fut.poll(cx));
match res {
Ok(t) => Poll::Ready(Ok(Some(t))),
Err(e) => {
log::debug!("Error for Option<T> extractor: {}", e.into());
Poll::Ready(Ok(None))
}
}
}
}
/// Optionally extract a field from the request or extract the Error if unsuccessful
///
/// If the `FromRequest` for T fails, inject Err into handler rather than returning an error response
///
/// # Examples
/// ```
/// use actix_web::{web, dev, App, Result, Error, HttpRequest, FromRequest};
/// use actix_web::error::ErrorBadRequest;
/// use futures_util::future::{ok, err, Ready};
/// use serde::Deserialize;
/// use rand;
///
/// #[derive(Debug, Deserialize)]
/// struct Thing {
/// name: String
/// }
///
/// impl FromRequest for Thing {
/// type Error = Error;
/// type Future = Ready<Result<Thing, Error>>;
///
/// fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future {
/// if rand::random() {
/// ok(Thing { name: "thingy".into() })
/// } else {
/// err(ErrorBadRequest("no luck"))
/// }
/// }
/// }
///
/// /// extract `Thing` from request
/// async fn index(supplied_thing: Result<Thing>) -> String {
/// match supplied_thing {
/// Ok(thing) => format!("Got thing: {:?}", thing),
/// Err(e) => format!("Error extracting thing: {}", e)
/// }
/// }
///
/// fn main() {
/// let app = App::new().service(
/// web::resource("/users/:first").route(web::post().to(index))
/// );
/// }
/// ```
impl<T> FromRequest for Result<T, T::Error>
where
T: FromRequest + 'static,
T::Error: 'static,
T::Future: 'static,
{
type Error = Error;
type Future = FromRequestResFuture<T::Future>;
#[inline]
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
FromRequestResFuture {
fut: T::from_request(req, payload),
}
}
}
pin_project! {
pub struct FromRequestResFuture<Fut> {
#[pin]
fut: Fut,
}
}
impl<Fut, T, E> Future for FromRequestResFuture<Fut>
where
Fut: Future<Output = Result<T, E>>,
{
type Output = Result<Result<T, E>, Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
let res = ready!(this.fut.poll(cx));
Poll::Ready(Ok(res))
}
}
/// Extract the request's URI.
///
/// # Examples
/// ```
/// use actix_web::{http::Uri, web, App, Responder};
///
/// async fn handler(uri: Uri) -> impl Responder {
/// format!("Requested path: {}", uri.path())
/// }
///
/// let app = App::new().default_service(web::to(handler));
/// ```
impl FromRequest for Uri {
type Error = Infallible;
type Future = Ready<Result<Self, Self::Error>>;
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
ok(req.uri().clone())
}
}
/// Extract the request's method.
///
/// # Examples
/// ```
/// use actix_web::{http::Method, web, App, Responder};
///
/// async fn handler(method: Method) -> impl Responder {
/// format!("Request method: {}", method)
/// }
///
/// let app = App::new().default_service(web::to(handler));
/// ```
impl FromRequest for Method {
type Error = Infallible;
type Future = Ready<Result<Self, Self::Error>>;
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
ok(req.method().clone())
}
}
#[doc(hidden)]
#[allow(non_snake_case)]
mod tuple_from_req {
use super::*;
macro_rules! tuple_from_req {
($fut: ident; $($T: ident),*) => {
/// FromRequest implementation for tuple
#[allow(unused_parens)]
impl<$($T: FromRequest + 'static),+> FromRequest for ($($T,)+)
{
type Error = Error;
type Future = $fut<$($T),+>;
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
$fut {
$(
$T: ExtractFuture::Future {
fut: $T::from_request(req, payload)
},
)+
}
}
}
pin_project! {
pub struct $fut<$($T: FromRequest),+> {
$(
#[pin]
$T: ExtractFuture<$T::Future, $T>,
)+
}
}
impl<$($T: FromRequest),+> Future for $fut<$($T),+>
{
type Output = Result<($($T,)+), Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut this = self.project();
let mut ready = true;
$(
match this.$T.as_mut().project() {
ExtractProj::Future { fut } => match fut.poll(cx) {
Poll::Ready(Ok(output)) => {
let _ = this.$T.as_mut().project_replace(ExtractFuture::Done { output });
},
Poll::Ready(Err(e)) => return Poll::Ready(Err(e.into())),
Poll::Pending => ready = false,
},
ExtractProj::Done { .. } => {},
ExtractProj::Empty => unreachable!("FromRequest polled after finished"),
}
)+
if ready {
Poll::Ready(Ok(
($(
match this.$T.project_replace(ExtractFuture::Empty) {
ExtractReplaceProj::Done { output } => output,
_ => unreachable!("FromRequest polled after finished"),
},
)+)
))
} else {
Poll::Pending
}
}
}
};
}
pin_project! {
#[project = ExtractProj]
#[project_replace = ExtractReplaceProj]
enum ExtractFuture<Fut, Res> {
Future {
#[pin]
fut: Fut
},
Done {
output: Res,
},
Empty
}
}
impl FromRequest for () {
type Error = Infallible;
type Future = Ready<Result<Self, Self::Error>>;
fn from_request(_: &HttpRequest, _: &mut Payload) -> Self::Future {
ok(())
}
}
tuple_from_req! { TupleFromRequest1; A }
tuple_from_req! { TupleFromRequest2; A, B }
tuple_from_req! { TupleFromRequest3; A, B, C }
tuple_from_req! { TupleFromRequest4; A, B, C, D }
tuple_from_req! { TupleFromRequest5; A, B, C, D, E }
tuple_from_req! { TupleFromRequest6; A, B, C, D, E, F }
tuple_from_req! { TupleFromRequest7; A, B, C, D, E, F, G }
tuple_from_req! { TupleFromRequest8; A, B, C, D, E, F, G, H }
tuple_from_req! { TupleFromRequest9; A, B, C, D, E, F, G, H, I }
tuple_from_req! { TupleFromRequest10; A, B, C, D, E, F, G, H, I, J }
tuple_from_req! { TupleFromRequest11; A, B, C, D, E, F, G, H, I, J, K }
tuple_from_req! { TupleFromRequest12; A, B, C, D, E, F, G, H, I, J, K, L }
}
#[cfg(test)]
mod tests {
use actix_http::header;
use bytes::Bytes;
use serde::Deserialize;
use super::*;
use crate::test::TestRequest;
use crate::types::{Form, FormConfig};
#[derive(Deserialize, Debug, PartialEq)]
struct Info {
hello: String,
}
#[actix_rt::test]
async fn test_option() {
let (req, mut pl) = TestRequest::default()
.insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded"))
.data(FormConfig::default().limit(4096))
.to_http_parts();
let r = Option::<Form<Info>>::from_request(&req, &mut pl)
.await
.unwrap();
assert_eq!(r, None);
let (req, mut pl) = TestRequest::default()
.insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded"))
.insert_header((header::CONTENT_LENGTH, "9"))
.set_payload(Bytes::from_static(b"hello=world"))
.to_http_parts();
let r = Option::<Form<Info>>::from_request(&req, &mut pl)
.await
.unwrap();
assert_eq!(
r,
Some(Form(Info {
hello: "world".into()
}))
);
let (req, mut pl) = TestRequest::default()
.insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded"))
.insert_header((header::CONTENT_LENGTH, "9"))
.set_payload(Bytes::from_static(b"bye=world"))
.to_http_parts();
let r = Option::<Form<Info>>::from_request(&req, &mut pl)
.await
.unwrap();
assert_eq!(r, None);
}
#[actix_rt::test]
async fn test_result() {
let (req, mut pl) = TestRequest::default()
.insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded"))
.insert_header((header::CONTENT_LENGTH, "11"))
.set_payload(Bytes::from_static(b"hello=world"))
.to_http_parts();
let r = Result::<Form<Info>, Error>::from_request(&req, &mut pl)
.await
.unwrap()
.unwrap();
assert_eq!(
r,
Form(Info {
hello: "world".into()
})
);
let (req, mut pl) = TestRequest::default()
.insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded"))
.insert_header((header::CONTENT_LENGTH, 9))
.set_payload(Bytes::from_static(b"bye=world"))
.to_http_parts();
let r = Result::<Form<Info>, Error>::from_request(&req, &mut pl)
.await
.unwrap();
assert!(r.is_err());
}
#[actix_rt::test]
async fn test_uri() {
let req = TestRequest::default().uri("/foo/bar").to_http_request();
let uri = Uri::extract(&req).await.unwrap();
assert_eq!(uri.path(), "/foo/bar");
}
#[actix_rt::test]
async fn test_method() {
let req = TestRequest::default().method(Method::GET).to_http_request();
let method = Method::extract(&req).await.unwrap();
assert_eq!(method, Method::GET);
}
#[actix_rt::test]
async fn test_concurrent() {
let (req, mut pl) = TestRequest::default()
.uri("/foo/bar")
.method(Method::GET)
.insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded"))
.insert_header((header::CONTENT_LENGTH, "11"))
.set_payload(Bytes::from_static(b"hello=world"))
.to_http_parts();
let (method, uri, form) = <(Method, Uri, Form<Info>)>::from_request(&req, &mut pl)
.await
.unwrap();
assert_eq!(method, Method::GET);
assert_eq!(uri.path(), "/foo/bar");
assert_eq!(
form,
Form(Info {
hello: "world".into()
})
);
}
}
| 31.058935 | 109 | 0.522311 |
1deb07865059054f04ec4915dfc5df87a5e4f167 | 30,715 | // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the THIRD-PARTY file.
#[cfg(target_arch = "aarch64")]
use devices::legacy::SerialDevice;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::{fmt, io};
#[cfg(target_arch = "x86_64")]
use vm_memory::GuestAddress;
#[cfg(target_arch = "aarch64")]
use arch::aarch64::DeviceInfoForFDT;
use arch::DeviceType;
use arch::DeviceType::Virtio;
#[cfg(target_arch = "aarch64")]
use devices::legacy::RTCDevice;
use devices::pseudo::BootTimer;
use devices::virtio::{
Balloon, Block, MmioTransport, Net, VirtioDevice, TYPE_BALLOON, TYPE_BLOCK, TYPE_NET,
TYPE_VSOCK,
};
use devices::BusDevice;
use kvm_ioctls::{IoEventAddress, VmFd};
use linux_loader::cmdline as kernel_cmdline;
use logger::info;
use versionize::{VersionMap, Versionize, VersionizeResult};
use versionize_derive::Versionize;
/// Errors for MMIO device manager.
#[derive(Debug)]
pub enum Error {
/// Failed to perform an operation on the bus.
BusError(devices::BusError),
/// Appending to kernel command line failed.
Cmdline(linux_loader::cmdline::Error),
/// The device couldn't be found.
DeviceNotFound,
/// Failure in creating or cloning an event fd.
EventFd(io::Error),
/// Incorrect device type.
IncorrectDeviceType,
/// Internal device error.
InternalDeviceError(String),
/// Invalid configuration attempted.
InvalidInput,
/// No more IRQs are available.
IrqsExhausted,
/// Registering an IO Event failed.
RegisterIoEvent(kvm_ioctls::Error),
/// Registering an IRQ FD failed.
RegisterIrqFd(kvm_ioctls::Error),
/// Failed to update the mmio device.
UpdateFailed,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::BusError(e) => write!(f, "failed to perform bus operation: {}", e),
Error::Cmdline(e) => write!(f, "unable to add device to kernel command line: {}", e),
Error::EventFd(e) => write!(f, "failed to create or clone event descriptor: {}", e),
Error::IncorrectDeviceType => write!(f, "incorrect device type"),
Error::InternalDeviceError(e) => write!(f, "device error: {}", e),
Error::InvalidInput => write!(f, "invalid configuration"),
Error::IrqsExhausted => write!(f, "no more IRQs are available"),
Error::RegisterIoEvent(e) => write!(f, "failed to register IO event: {}", e),
Error::RegisterIrqFd(e) => write!(f, "failed to register irqfd: {}", e),
Error::DeviceNotFound => write!(f, "the device couldn't be found"),
Error::UpdateFailed => write!(f, "failed to update the mmio device"),
}
}
}
type Result<T> = ::std::result::Result<T, Error>;
/// This represents the size of the mmio device specified to the kernel as a cmdline option
/// It has to be larger than 0x100 (the offset where the configuration space starts from
/// the beginning of the memory mapped device registers) + the size of the configuration space
/// Currently hardcoded to 4K.
const MMIO_LEN: u64 = 0x1000;
/// Stores the address range and irq allocated to this device.
#[derive(Clone, Debug, PartialEq, Versionize)]
// NOTICE: Any changes to this structure require a snapshot version bump.
pub struct MMIODeviceInfo {
/// Mmio address at which the device is registered.
pub addr: u64,
/// Mmio addr range length.
pub len: u64,
/// Used Irq line(s) for the device.
pub irqs: Vec<u32>,
}
struct IrqManager {
first: u32,
last: u32,
next_avail: u32,
}
impl IrqManager {
pub fn new(first: u32, last: u32) -> Self {
Self {
first,
last,
next_avail: first,
}
}
pub fn get(&mut self, count: u32) -> Result<Vec<u32>> {
if self.next_avail + count > self.last + 1 {
return Err(Error::IrqsExhausted);
}
let mut irqs = Vec::with_capacity(count as usize);
for _ in 0..count {
irqs.push(self.next_avail);
self.next_avail += 1;
}
Ok(irqs)
}
pub fn check(&self, irqs: &[u32]) -> Result<()> {
for irq in irqs {
// Check for out of range.
if self.first > *irq || *irq > self.last {
return Err(Error::InvalidInput);
}
}
Ok(())
}
}
/// Manages the complexities of registering a MMIO device.
pub struct MMIODeviceManager {
pub(crate) bus: devices::Bus,
mmio_base: u64,
next_avail_mmio: u64,
irqs: IrqManager,
pub(crate) id_to_dev_info: HashMap<(DeviceType, String), MMIODeviceInfo>,
}
impl MMIODeviceManager {
/// Create a new DeviceManager handling mmio devices (virtio net, block).
pub fn new(mmio_base: u64, irq_interval: (u32, u32)) -> MMIODeviceManager {
MMIODeviceManager {
mmio_base,
next_avail_mmio: mmio_base,
irqs: IrqManager::new(irq_interval.0, irq_interval.1),
bus: devices::Bus::new(),
id_to_dev_info: HashMap::new(),
}
}
/// Allocates resources for a new device to be added.
fn allocate_new_slot(&mut self, irq_count: u32) -> Result<MMIODeviceInfo> {
let irqs = self.irqs.get(irq_count)?;
let slot = MMIODeviceInfo {
addr: self.next_avail_mmio,
len: MMIO_LEN,
irqs,
};
self.next_avail_mmio += MMIO_LEN;
Ok(slot)
}
/// Does a slot sanity check against expected values.
pub fn slot_sanity_check(&self, slot: &MMIODeviceInfo) -> Result<()> {
if slot.addr < self.mmio_base || slot.len != MMIO_LEN {
return Err(Error::InvalidInput);
}
self.irqs.check(&slot.irqs)
}
/// Register a device at some MMIO address.
fn register_mmio_device(
&mut self,
identifier: (DeviceType, String),
slot: MMIODeviceInfo,
device: Arc<Mutex<dyn BusDevice>>,
) -> Result<()> {
self.bus
.insert(device, slot.addr, slot.len)
.map_err(Error::BusError)?;
self.id_to_dev_info.insert(identifier, slot);
Ok(())
}
/// Register a virtio-over-MMIO device to be used via MMIO transport at a specific slot.
pub fn register_mmio_virtio(
&mut self,
vm: &VmFd,
device_id: String,
mmio_device: MmioTransport,
slot: &MMIODeviceInfo,
) -> Result<()> {
// Our virtio devices are currently hardcoded to use a single IRQ.
// Validate that requirement.
if slot.irqs.len() != 1 {
return Err(Error::InvalidInput);
}
let identifier;
{
let locked_device = mmio_device.locked_device();
identifier = (DeviceType::Virtio(locked_device.device_type()), device_id);
for (i, queue_evt) in locked_device.queue_events().iter().enumerate() {
let io_addr =
IoEventAddress::Mmio(slot.addr + u64::from(devices::virtio::NOTIFY_REG_OFFSET));
vm.register_ioevent(queue_evt, &io_addr, i as u32)
.map_err(Error::RegisterIoEvent)?;
}
vm.register_irqfd(locked_device.interrupt_evt(), slot.irqs[0])
.map_err(Error::RegisterIrqFd)?;
}
self.register_mmio_device(identifier, slot.clone(), Arc::new(Mutex::new(mmio_device)))
}
/// Append a registered virtio-over-MMIO device to the kernel cmdline.
#[cfg(target_arch = "x86_64")]
pub fn add_virtio_device_to_cmdline(
cmdline: &mut kernel_cmdline::Cmdline,
slot: &MMIODeviceInfo,
) -> Result<()> {
// as per doc, [virtio_mmio.]device=<size>@<baseaddr>:<irq> needs to be appended
// to kernel commandline for virtio mmio devices to get recognized
// the size parameter has to be transformed to KiB, so dividing hexadecimal value in
// bytes to 1024; further, the '{}' formatting rust construct will automatically
// transform it to decimal
cmdline
.add_virtio_mmio_device(slot.len, GuestAddress(slot.addr), slot.irqs[0], None)
.map_err(Error::Cmdline)
}
/// Allocate slot and register an already created virtio-over-MMIO device. Also Adds the device
/// to the boot cmdline.
pub fn register_mmio_virtio_for_boot(
&mut self,
vm: &VmFd,
device_id: String,
mmio_device: MmioTransport,
_cmdline: &mut kernel_cmdline::Cmdline,
) -> Result<MMIODeviceInfo> {
let mmio_slot = self.allocate_new_slot(1)?;
self.register_mmio_virtio(vm, device_id, mmio_device, &mmio_slot)?;
#[cfg(target_arch = "x86_64")]
Self::add_virtio_device_to_cmdline(_cmdline, &mmio_slot)?;
Ok(mmio_slot)
}
#[cfg(target_arch = "aarch64")]
/// Register an early console at the specified MMIO address if given as parameter,
/// otherwise allocate a new MMIO slot for it.
pub fn register_mmio_serial(
&mut self,
vm: &VmFd,
serial: Arc<Mutex<SerialDevice>>,
dev_info_opt: Option<MMIODeviceInfo>,
) -> Result<()> {
let slot = dev_info_opt.unwrap_or(self.allocate_new_slot(1)?);
vm.register_irqfd(
&serial.lock().expect("Poisoned lock").serial.interrupt_evt(),
slot.irqs[0],
)
.map_err(Error::RegisterIrqFd)?;
let identifier = (DeviceType::Serial, DeviceType::Serial.to_string());
self.register_mmio_device(identifier, slot, serial)
}
#[cfg(target_arch = "aarch64")]
/// Append the registered early console to the kernel cmdline.
pub fn add_mmio_serial_to_cmdline(&self, cmdline: &mut kernel_cmdline::Cmdline) -> Result<()> {
let mmio_slot = self
.id_to_dev_info
.get(&(DeviceType::Serial, DeviceType::Serial.to_string()))
.ok_or(Error::DeviceNotFound)?;
cmdline
.insert("earlycon", &format!("uart,mmio,0x{:08x}", mmio_slot.addr))
.map_err(Error::Cmdline)
}
#[cfg(target_arch = "aarch64")]
/// Create and register a MMIO RTC device at the specified MMIO address if given as parameter,
/// otherwise allocate a new MMIO slot for it.
pub fn register_mmio_rtc(
&mut self,
rtc: Arc<Mutex<RTCDevice>>,
dev_info_opt: Option<MMIODeviceInfo>,
) -> Result<()> {
// Create and attach a new RTC device.
// We allocate an IRQ even though we do not need it so that
// we do not break snapshot compatibility.
let slot = dev_info_opt.unwrap_or(self.allocate_new_slot(1)?);
let identifier = (DeviceType::Rtc, DeviceType::Rtc.to_string());
self.register_mmio_device(identifier, slot, rtc)
}
/// Register a boot timer device.
pub fn register_mmio_boot_timer(&mut self, device: BootTimer) -> Result<()> {
// Attach a new boot timer device.
let slot = self.allocate_new_slot(0)?;
let identifier = (DeviceType::BootTimer, DeviceType::BootTimer.to_string());
self.register_mmio_device(identifier, slot, Arc::new(Mutex::new(device)))
}
/// Gets the information of the devices registered up to some point in time.
pub fn get_device_info(&self) -> &HashMap<(DeviceType, String), MMIODeviceInfo> {
&self.id_to_dev_info
}
#[cfg(target_arch = "x86_64")]
/// Gets the number of interrupts used by the devices registered.
pub fn used_irqs_count(&self) -> usize {
let mut irq_number = 0;
self.get_device_info()
.iter()
.for_each(|(_, device_info)| irq_number += device_info.irqs.len());
irq_number
}
/// Gets the the specified device.
pub fn get_device(
&self,
device_type: DeviceType,
device_id: &str,
) -> Option<&Mutex<dyn BusDevice>> {
if let Some(dev_info) = self
.id_to_dev_info
.get(&(device_type, device_id.to_string()))
{
if let Some((_, device)) = self.bus.get_device(dev_info.addr) {
return Some(device);
}
}
None
}
/// Run fn for each registered device.
pub fn for_each_device<F, E>(&self, mut f: F) -> std::result::Result<(), E>
where
F: FnMut(
&DeviceType,
&String,
&MMIODeviceInfo,
&Mutex<dyn BusDevice>,
) -> std::result::Result<(), E>,
{
for ((device_type, device_id), device_info) in self.get_device_info().iter() {
let bus_device = self
.get_device(*device_type, device_id)
// Safe to unwrap() because we know the device exists.
.unwrap();
f(device_type, device_id, device_info, bus_device)?;
}
Ok(())
}
/// Run fn for each registered virtio device.
pub fn for_each_virtio_device<F, E>(&self, mut f: F) -> std::result::Result<(), E>
where
F: FnMut(
u32,
&String,
&MMIODeviceInfo,
Arc<Mutex<dyn VirtioDevice>>,
) -> std::result::Result<(), E>,
{
self.for_each_device(|device_type, device_id, device_info, bus_device| {
if let Virtio(virtio_type) = device_type {
let virtio_device = bus_device
.lock()
.expect("Poisoned lock")
.as_any()
.downcast_ref::<MmioTransport>()
.expect("Unexpected BusDevice type")
.device();
f(*virtio_type, device_id, device_info, virtio_device)?;
}
Ok(())
})?;
Ok(())
}
/// Run fn `f()` for the virtio device matching `virtio_type` and `id`.
pub fn with_virtio_device_with_id<T, F>(&self, virtio_type: u32, id: &str, f: F) -> Result<()>
where
T: VirtioDevice + 'static,
F: FnOnce(&mut T) -> std::result::Result<(), String>,
{
if let Some(busdev) = self.get_device(DeviceType::Virtio(virtio_type), id) {
let virtio_device = busdev
.lock()
.expect("Poisoned lock")
.as_any()
.downcast_ref::<MmioTransport>()
.expect("Unexpected BusDevice type")
.device();
let mut dev = virtio_device.lock().expect("Poisoned lock");
f(dev
.as_mut_any()
.downcast_mut::<T>()
.ok_or(Error::IncorrectDeviceType)?)
.map_err(Error::InternalDeviceError)?;
} else {
return Err(Error::DeviceNotFound);
}
Ok(())
}
/// Artificially kick devices as if they had external events.
pub fn kick_devices(&self) {
info!("Artificially kick devices.");
// We only kick virtio devices for now.
let _: Result<()> = self.for_each_virtio_device(|virtio_type, id, _info, dev| {
let mut virtio = dev.lock().expect("Poisoned lock");
match virtio_type {
TYPE_BALLOON => {
let balloon = virtio.as_mut_any().downcast_mut::<Balloon>().unwrap();
// If device is activated, kick the balloon queue(s) to make up for any
// pending or in-flight epoll events we may have not captured in snapshot.
// Stats queue doesn't need kicking as it is notified via a `timer_fd`.
if balloon.is_activated() {
info!("kick balloon {}.", id);
balloon.process_virtio_queues();
}
}
TYPE_BLOCK => {
let block = virtio.as_mut_any().downcast_mut::<Block>().unwrap();
// If device is activated, kick the block queue(s) to make up for any
// pending or in-flight epoll events we may have not captured in snapshot.
// No need to kick Ratelimiters because they are restored 'unblocked' so
// any inflight `timer_fd` events can be safely discarded.
if block.is_activated() {
info!("kick block {}.", id);
block.process_virtio_queues();
}
}
TYPE_NET => {
let net = virtio.as_mut_any().downcast_mut::<Net>().unwrap();
// If device is activated, kick the net queue(s) to make up for any
// pending or in-flight epoll events we may have not captured in snapshot.
// No need to kick Ratelimiters because they are restored 'unblocked' so
// any inflight `timer_fd` events can be safely discarded.
if net.is_activated() {
info!("kick net {}.", id);
net.process_virtio_queues();
}
}
TYPE_VSOCK => {
// Vsock has complicated protocol that isn't resilient to any packet loss,
// so for Vsock we don't support connection persistence through snapshot.
// Any in-flight packets or events are simply lost.
// Vsock is restored 'empty'.
}
_ => (),
}
Ok(())
});
}
}
#[cfg(target_arch = "aarch64")]
impl DeviceInfoForFDT for MMIODeviceInfo {
fn addr(&self) -> u64 {
self.addr
}
fn irq(&self) -> u32 {
self.irqs[0]
}
fn length(&self) -> u64 {
self.len
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::builder;
use devices::virtio::{ActivateResult, Queue, VirtioDevice};
use std::sync::atomic::AtomicUsize;
use std::sync::Arc;
use utils::errno;
use utils::eventfd::EventFd;
use vm_memory::{GuestAddress, GuestMemoryMmap};
const QUEUE_SIZES: &[u16] = &[64];
impl MMIODeviceManager {
fn register_virtio_test_device(
&mut self,
vm: &VmFd,
guest_mem: GuestMemoryMmap,
device: Arc<Mutex<dyn devices::virtio::VirtioDevice>>,
cmdline: &mut kernel_cmdline::Cmdline,
dev_id: &str,
) -> Result<u64> {
let mmio_device = MmioTransport::new(guest_mem, device);
let mmio_slot =
self.register_mmio_virtio_for_boot(vm, dev_id.to_string(), mmio_device, cmdline)?;
Ok(mmio_slot.addr)
}
}
#[allow(dead_code)]
struct DummyDevice {
dummy: u32,
queues: Vec<Queue>,
queue_evts: [EventFd; 1],
interrupt_evt: EventFd,
}
impl DummyDevice {
pub fn new() -> Self {
DummyDevice {
dummy: 0,
queues: QUEUE_SIZES.iter().map(|&s| Queue::new(s)).collect(),
queue_evts: [EventFd::new(libc::EFD_NONBLOCK).expect("cannot create eventFD")],
interrupt_evt: EventFd::new(libc::EFD_NONBLOCK).expect("cannot create eventFD"),
}
}
}
impl devices::virtio::VirtioDevice for DummyDevice {
fn avail_features(&self) -> u64 {
0
}
fn acked_features(&self) -> u64 {
0
}
fn set_acked_features(&mut self, _: u64) {}
fn device_type(&self) -> u32 {
0
}
fn queues(&self) -> &[Queue] {
&self.queues
}
fn queues_mut(&mut self) -> &mut [Queue] {
&mut self.queues
}
fn queue_events(&self) -> &[EventFd] {
&self.queue_evts
}
fn interrupt_evt(&self) -> &EventFd {
&self.interrupt_evt
}
fn interrupt_status(&self) -> Arc<AtomicUsize> {
Arc::new(AtomicUsize::new(0))
}
fn ack_features_by_page(&mut self, page: u32, value: u32) {
let _ = page;
let _ = value;
}
fn read_config(&self, offset: u64, data: &mut [u8]) {
let _ = offset;
let _ = data;
}
fn write_config(&mut self, offset: u64, data: &[u8]) {
let _ = offset;
let _ = data;
}
fn activate(&mut self, _: GuestMemoryMmap) -> ActivateResult {
Ok(())
}
fn is_activated(&self) -> bool {
false
}
}
#[test]
fn test_register_virtio_device() {
let start_addr1 = GuestAddress(0x0);
let start_addr2 = GuestAddress(0x1000);
let guest_mem = vm_memory::test_utils::create_anon_guest_memory(
&[(start_addr1, 0x1000), (start_addr2, 0x1000)],
false,
)
.unwrap();
let mut vm = builder::setup_kvm_vm(&guest_mem, false).unwrap();
let mut device_manager =
MMIODeviceManager::new(0xd000_0000, (arch::IRQ_BASE, arch::IRQ_MAX));
let mut cmdline = kernel_cmdline::Cmdline::new(4096);
let dummy = Arc::new(Mutex::new(DummyDevice::new()));
#[cfg(target_arch = "x86_64")]
assert!(builder::setup_interrupt_controller(&mut vm).is_ok());
#[cfg(target_arch = "aarch64")]
assert!(builder::setup_interrupt_controller(&mut vm, 1).is_ok());
assert!(device_manager
.register_virtio_test_device(vm.fd(), guest_mem, dummy, &mut cmdline, "dummy")
.is_ok());
}
#[test]
fn test_register_too_many_devices() {
let start_addr1 = GuestAddress(0x0);
let start_addr2 = GuestAddress(0x1000);
let guest_mem = vm_memory::test_utils::create_anon_guest_memory(
&[(start_addr1, 0x1000), (start_addr2, 0x1000)],
false,
)
.unwrap();
let mut vm = builder::setup_kvm_vm(&guest_mem, false).unwrap();
let mut device_manager =
MMIODeviceManager::new(0xd000_0000, (arch::IRQ_BASE, arch::IRQ_MAX));
let mut cmdline = kernel_cmdline::Cmdline::new(4096);
#[cfg(target_arch = "x86_64")]
assert!(builder::setup_interrupt_controller(&mut vm).is_ok());
#[cfg(target_arch = "aarch64")]
assert!(builder::setup_interrupt_controller(&mut vm, 1).is_ok());
for _i in arch::IRQ_BASE..=arch::IRQ_MAX {
device_manager
.register_virtio_test_device(
vm.fd(),
guest_mem.clone(),
Arc::new(Mutex::new(DummyDevice::new())),
&mut cmdline,
"dummy1",
)
.unwrap();
}
assert_eq!(
format!(
"{}",
device_manager
.register_virtio_test_device(
vm.fd(),
guest_mem,
Arc::new(Mutex::new(DummyDevice::new())),
&mut cmdline,
"dummy2"
)
.unwrap_err()
),
"no more IRQs are available".to_string()
);
}
#[test]
fn test_dummy_device() {
let dummy = DummyDevice::new();
assert_eq!(dummy.device_type(), 0);
assert_eq!(dummy.queues().len(), QUEUE_SIZES.len());
}
#[test]
fn test_error_debug_display() {
let check_fmt_err = |e: Error| {
// Use an exhaustive 'match' to make sure we cover all error variants.
// When adding a new variant here, don't forget to also call this function with it.
let msg = match e {
Error::BusError(_) => format!("{}{:?}", e, e),
Error::Cmdline(_) => format!("{}{:?}", e, e),
Error::DeviceNotFound => format!("{}{:?}", e, e),
Error::EventFd(_) => format!("{}{:?}", e, e),
Error::IncorrectDeviceType => format!("{}{:?}", e, e),
Error::InternalDeviceError(_) => format!("{}{:?}", e, e),
Error::InvalidInput => format!("{}{:?}", e, e),
Error::IrqsExhausted => format!("{}{:?}", e, e),
Error::RegisterIoEvent(_) => format!("{}{:?}", e, e),
Error::RegisterIrqFd(_) => format!("{}{:?}", e, e),
Error::UpdateFailed => format!("{}{:?}", e, e),
};
assert!(!msg.is_empty());
};
check_fmt_err(Error::BusError(devices::BusError::Overlap));
check_fmt_err(Error::Cmdline(linux_loader::cmdline::Error::TooLarge));
check_fmt_err(Error::DeviceNotFound);
check_fmt_err(Error::EventFd(io::Error::from_raw_os_error(0)));
check_fmt_err(Error::IncorrectDeviceType);
check_fmt_err(Error::InternalDeviceError(String::new()));
check_fmt_err(Error::InvalidInput);
check_fmt_err(Error::IrqsExhausted);
check_fmt_err(Error::RegisterIoEvent(errno::Error::new(0)));
check_fmt_err(Error::RegisterIrqFd(errno::Error::new(0)));
check_fmt_err(Error::UpdateFailed);
}
#[test]
fn test_device_info() {
let start_addr1 = GuestAddress(0x0);
let start_addr2 = GuestAddress(0x1000);
let guest_mem = vm_memory::test_utils::create_anon_guest_memory(
&[(start_addr1, 0x1000), (start_addr2, 0x1000)],
false,
)
.unwrap();
let mut vm = builder::setup_kvm_vm(&guest_mem, false).unwrap();
#[cfg(target_arch = "x86_64")]
// Only used for x86_64 part of the test.
let mem_clone = guest_mem.clone();
#[cfg(target_arch = "x86_64")]
assert!(builder::setup_interrupt_controller(&mut vm).is_ok());
#[cfg(target_arch = "aarch64")]
assert!(builder::setup_interrupt_controller(&mut vm, 1).is_ok());
let mut device_manager =
MMIODeviceManager::new(0xd000_0000, (arch::IRQ_BASE, arch::IRQ_MAX));
let mut cmdline = kernel_cmdline::Cmdline::new(4096);
let dummy = Arc::new(Mutex::new(DummyDevice::new()));
let type_id = dummy.lock().unwrap().device_type();
let id = String::from("foo");
let addr = device_manager
.register_virtio_test_device(vm.fd(), guest_mem, dummy, &mut cmdline, &id)
.unwrap();
assert!(device_manager
.get_device(DeviceType::Virtio(type_id), &id)
.is_some());
assert_eq!(
addr,
device_manager.id_to_dev_info[&(DeviceType::Virtio(type_id), id.clone())].addr
);
assert_eq!(
arch::IRQ_BASE,
device_manager.id_to_dev_info[&(DeviceType::Virtio(type_id), id)].irqs[0]
);
let id = "bar";
assert!(device_manager
.get_device(DeviceType::Virtio(type_id), &id)
.is_none());
#[cfg(target_arch = "x86_64")]
{
let dummy2 = Arc::new(Mutex::new(DummyDevice::new()));
let id2 = String::from("foo2");
device_manager
.register_virtio_test_device(vm.fd(), mem_clone, dummy2, &mut cmdline, &id2)
.unwrap();
let mut count = 0;
let _: Result<()> = device_manager.for_each_device(|devtype, devid, _, _| {
assert_eq!(*devtype, DeviceType::Virtio(type_id));
match devid.as_str() {
"foo" => count += 1,
"foo2" => count += 2,
_ => unreachable!(),
};
Ok(())
});
assert_eq!(count, 3);
assert_eq!(device_manager.used_irqs_count(), 2);
}
}
#[test]
fn test_slot_irq_allocation() {
let mut device_manager =
MMIODeviceManager::new(0xd000_0000, (arch::IRQ_BASE, arch::IRQ_MAX));
let _addr = device_manager.allocate_new_slot(0);
assert_eq!(device_manager.irqs.next_avail, arch::IRQ_BASE);
let _addr = device_manager.allocate_new_slot(1);
assert_eq!(device_manager.irqs.next_avail, arch::IRQ_BASE + 1);
assert_eq!(
format!(
"{}",
device_manager
.allocate_new_slot(arch::IRQ_MAX - arch::IRQ_BASE + 1)
.unwrap_err()
),
"no more IRQs are available".to_string()
);
let _addr = device_manager.allocate_new_slot(arch::IRQ_MAX - arch::IRQ_BASE - 1);
assert_eq!(device_manager.irqs.next_avail, arch::IRQ_MAX);
assert_eq!(
format!("{}", device_manager.allocate_new_slot(2).unwrap_err()),
"no more IRQs are available".to_string()
);
let _addr = device_manager.allocate_new_slot(1);
assert_eq!(device_manager.irqs.next_avail, arch::IRQ_MAX + 1);
assert!(device_manager.allocate_new_slot(0).is_ok());
}
#[test]
fn test_slot_sanity_checks() {
let mmio_base = 0xd000_0000;
let device_manager = MMIODeviceManager::new(mmio_base, (arch::IRQ_BASE, arch::IRQ_MAX));
// Valid slot.
let slot = MMIODeviceInfo {
addr: mmio_base,
len: MMIO_LEN,
irqs: vec![arch::IRQ_BASE, arch::IRQ_BASE + 1],
};
device_manager.slot_sanity_check(&slot).unwrap();
// 'addr' below base.
let slot = MMIODeviceInfo {
addr: mmio_base - 1,
len: MMIO_LEN,
irqs: vec![arch::IRQ_BASE, arch::IRQ_BASE + 1],
};
device_manager.slot_sanity_check(&slot).unwrap_err();
// Invalid 'len'.
let slot = MMIODeviceInfo {
addr: mmio_base,
len: MMIO_LEN - 1,
irqs: vec![arch::IRQ_BASE, arch::IRQ_BASE + 1],
};
device_manager.slot_sanity_check(&slot).unwrap_err();
// 'irq' below range.
let slot = MMIODeviceInfo {
addr: mmio_base,
len: MMIO_LEN,
irqs: vec![arch::IRQ_BASE - 1, arch::IRQ_BASE + 1],
};
device_manager.slot_sanity_check(&slot).unwrap_err();
// 'irq' above range.
let slot = MMIODeviceInfo {
addr: mmio_base,
len: MMIO_LEN,
irqs: vec![arch::IRQ_BASE, arch::IRQ_MAX + 1],
};
device_manager.slot_sanity_check(&slot).unwrap_err();
}
}
| 36.39218 | 100 | 0.562071 |
5614caa2147de3b2c6355f04ace5701f407f2ed6 | 1,071 | use num_bigint::{BigUint, RandBigInt};
pub struct DiffieHellmanState {
pub secret: BigUint,
p: BigUint,
g: BigUint,
pub pubkey: BigUint,
}
impl DiffieHellmanState {
pub fn new(g: &BigUint, p: &BigUint) -> DiffieHellmanState {
let secret = rand::thread_rng().gen_biguint_below(&p);
let pubkey = DiffieHellmanState::gen_pubkey(&p, &g, &secret);
DiffieHellmanState {
secret,
p: p.clone(),
g: g.clone(),
pubkey,
}
}
pub fn new_static(g: &BigUint, p: &BigUint, secret: &BigUint) -> DiffieHellmanState {
let pubkey = DiffieHellmanState::gen_pubkey(&p, &g, &secret);
DiffieHellmanState {
secret: secret.clone(),
p: p.clone(),
g: g.clone(),
pubkey,
}
}
pub fn gen_shared_key(self, other_pubkey: &BigUint) -> BigUint {
other_pubkey.modpow(&self.secret, &self.p)
}
fn gen_pubkey(p: &BigUint, g: &BigUint, secret: &BigUint) -> BigUint {
g.modpow(secret, p)
}
}
| 26.775 | 89 | 0.564893 |
1cbe5277242fb6fd41e141a7e4b02b47b121664e | 4,288 | pub use super::name::WadName;
use serde::Deserialize;
pub type LightLevel = i16;
pub type LinedefFlags = u16;
pub type SectorId = u16;
pub type SectorTag = u16;
pub type SectorType = u16;
pub type SidedefId = i16;
pub type SpecialType = u16;
pub type ThingFlags = u16;
pub type ThingType = u16;
pub type VertexId = u16;
pub type WadCoord = i16;
pub type SegId = u16;
pub type LinedefId = u16;
pub type ChildId = u16;
#[derive(Copy, Clone, Deserialize)]
pub struct WadInfo {
pub identifier: [u8; 4],
pub num_lumps: i32,
pub info_table_offset: i32,
}
#[derive(Copy, Clone, Deserialize)]
pub struct WadLump {
pub file_pos: i32,
pub size: i32,
pub name: WadName,
}
#[derive(Copy, Clone, Deserialize)]
pub struct WadThing {
pub x: WadCoord,
pub y: WadCoord,
pub angle: WadCoord,
pub thing_type: ThingType,
pub flags: ThingFlags,
}
#[derive(Copy, Clone, Deserialize)]
pub struct WadVertex {
pub x: WadCoord,
pub y: WadCoord,
}
#[derive(Copy, Clone, Deserialize)]
pub struct WadLinedef {
pub start_vertex: VertexId,
pub end_vertex: VertexId,
pub flags: LinedefFlags,
pub special_type: SpecialType,
pub sector_tag: SectorTag,
pub right_side: SidedefId,
pub left_side: SidedefId,
}
impl WadLinedef {
pub fn impassable(&self) -> bool {
self.flags & 0x0001 != 0
}
pub fn blocks_monsters(&self) -> bool {
self.flags & 0x0002 != 0
}
pub fn is_two_sided(&self) -> bool {
self.flags & 0x0004 != 0
}
pub fn upper_unpegged(&self) -> bool {
self.flags & 0x0008 != 0
}
pub fn lower_unpegged(&self) -> bool {
self.flags & 0x0010 != 0
}
pub fn secret(&self) -> bool {
self.flags & 0x0020 != 0
}
pub fn blocks_sound(&self) -> bool {
self.flags & 0x0040 != 0
}
pub fn always_shown_on_map(&self) -> bool {
self.flags & 0x0080 != 0
}
pub fn never_shown_on_map(&self) -> bool {
self.flags & 0x0100 != 0
}
}
#[derive(Copy, Clone, Deserialize)]
pub struct WadSidedef {
pub x_offset: WadCoord,
pub y_offset: WadCoord,
pub upper_texture: WadName,
pub lower_texture: WadName,
pub middle_texture: WadName,
pub sector: SectorId,
}
#[derive(Copy, Clone, Deserialize)]
pub struct WadSector {
pub floor_height: WadCoord,
pub ceiling_height: WadCoord,
pub floor_texture: WadName,
pub ceiling_texture: WadName,
pub light: LightLevel,
pub sector_type: SectorType,
pub tag: SectorTag,
}
#[derive(Copy, Clone, Deserialize)]
pub struct WadSubsector {
pub num_segs: u16,
pub first_seg: SegId,
}
#[derive(Copy, Clone, Deserialize)]
pub struct WadSeg {
pub start_vertex: VertexId,
pub end_vertex: VertexId,
pub angle: u16,
pub linedef: LinedefId,
pub direction: u16,
pub offset: u16,
}
#[derive(Copy, Clone, Deserialize)]
pub struct WadNode {
pub line_x: WadCoord,
pub line_y: WadCoord,
pub step_x: WadCoord,
pub step_y: WadCoord,
pub right_y_max: WadCoord,
pub right_y_min: WadCoord,
pub right_x_max: WadCoord,
pub right_x_min: WadCoord,
pub left_y_max: WadCoord,
pub left_y_min: WadCoord,
pub left_x_max: WadCoord,
pub left_x_min: WadCoord,
pub right: ChildId,
pub left: ChildId,
}
#[derive(Copy, Clone, Deserialize)]
pub struct WadTextureHeader {
pub name: WadName,
pub masked: u32,
pub width: u16,
pub height: u16,
pub column_directory: u32,
pub num_patches: u16,
}
#[derive(Copy, Clone, Deserialize)]
pub struct WadTexturePatchRef {
pub origin_x: i16,
pub origin_y: i16,
pub patch: u16,
pub stepdir: u16,
pub colormap: u16,
}
pub const PALETTE_SIZE: usize = 256 * 3;
pub const COLORMAP_SIZE: usize = 256;
pub struct Palette(pub [u8; PALETTE_SIZE]);
impl Default for Palette {
fn default() -> Self {
Palette([0u8; PALETTE_SIZE])
}
}
impl AsMut<[u8]> for Palette {
fn as_mut(&mut self) -> &mut [u8] {
&mut self.0
}
}
pub struct Colormap(pub [u8; COLORMAP_SIZE]);
impl Default for Colormap {
fn default() -> Self {
Colormap([0u8; COLORMAP_SIZE])
}
}
impl AsMut<[u8]> for Colormap {
fn as_mut(&mut self) -> &mut [u8] {
&mut self.0
}
}
| 21.766497 | 47 | 0.64459 |
ac0c0a27bac2b19923198189240f8a1b7e501794 | 2,559 | use crate::backend::Instance;
use winit::dpi::{PhysicalPosition, PhysicalSize};
use winit::event::TouchPhase;
use winit::window::WindowBuilder;
test!(run);
async fn run(instance: &dyn Instance) {
let seat = instance.default_seat();
let touch = seat.add_touchscreen();
let el = instance.create_event_loop();
let mut events = el.events();
let window = el.create_window(WindowBuilder::new().with_inner_size(PhysicalSize {
width: 100,
height: 100,
}));
window.mapped(true).await;
window.inner_size(100, 100).await;
window.set_outer_position(100 - window.inner_offset().0, 100 - window.inner_offset().1);
window
.outer_position(100 - window.inner_offset().0, 100 - window.inner_offset().1)
.await;
let f1 = touch.down(110, 110);
let (_, te1) = events.window_touch_event().await;
assert!(seat.is(te1.device_id));
assert_eq!(te1.phase, TouchPhase::Started);
assert_eq!(te1.location, PhysicalPosition { x: 10.0, y: 10.0 });
f1.move_(105, 120);
let (_, te2) = events.window_touch_event().await;
assert!(seat.is(te2.device_id));
assert_eq!(te2.id, te1.id);
assert_eq!(te2.phase, TouchPhase::Moved);
assert_eq!(te2.location, PhysicalPosition { x: 5.0, y: 20.0 });
let f2 = touch.down(101, 103);
let (_, te3) = events.window_touch_event().await;
assert!(seat.is(te3.device_id));
assert_eq!(te3.phase, TouchPhase::Started);
assert_eq!(te3.location, PhysicalPosition { x: 1.0, y: 3.0 });
f1.move_(107, 135);
let (_, te4) = events.window_touch_event().await;
assert!(seat.is(te4.device_id));
assert_eq!(te4.id, te1.id);
assert_eq!(te4.phase, TouchPhase::Moved);
assert_eq!(te4.location, PhysicalPosition { x: 7.0, y: 35.0 });
f2.move_(106, 107);
let (_, te5) = events.window_touch_event().await;
assert!(seat.is(te5.device_id));
assert_eq!(te5.id, te3.id);
assert_eq!(te5.phase, TouchPhase::Moved);
assert_eq!(te5.location, PhysicalPosition { x: 6.0, y: 7.0 });
drop(f1);
let (_, te6) = events.window_touch_event().await;
assert!(seat.is(te6.device_id));
assert_eq!(te6.id, te1.id);
assert_eq!(te6.phase, TouchPhase::Ended);
assert_eq!(te6.location, PhysicalPosition { x: 7.0, y: 35.0 });
drop(f2);
let (_, te7) = events.window_touch_event().await;
assert!(seat.is(te7.device_id));
assert_eq!(te7.id, te3.id);
assert_eq!(te7.phase, TouchPhase::Ended);
assert_eq!(te7.location, PhysicalPosition { x: 6.0, y: 7.0 });
}
| 29.413793 | 92 | 0.646346 |
0129ef66247b07a99ede8c773e4c773a5bfa0d33 | 2,508 | // Copyright 2021. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use crate::{
services::{
infrastructure_services::NodeAddressable,
AssetProcessor,
AssetProxy,
BaseNodeClient,
MempoolService,
ValidatorNodeClientFactory,
},
storage::DbFactory,
};
/// A trait to describe a specific configuration of services. This type allows other services to
/// simply reference types.
/// This trait is intended to only include `types` and no methods.
pub trait ServiceSpecification: Clone {
type Addr: NodeAddressable;
type DbFactory: DbFactory + Clone + Sync + Send + 'static;
type BaseNodeClient: BaseNodeClient + Clone + Sync + Send + 'static;
type ValidatorNodeClientFactory: ValidatorNodeClientFactory<Addr = Self::Addr> + Clone + Sync + Send + 'static;
type MempoolService: MempoolService + Clone + Sync + Send + 'static;
type AssetProcessor: AssetProcessor + Clone + Sync + Send + 'static;
type AssetProxy: AssetProxy + Clone + Sync + Send + 'static;
}
| 53.361702 | 119 | 0.746013 |
ab7e75bf4f10c7f282d59ae2ff9fe847c97e534e | 115,885 | //! This pass type-checks the MIR to ensure it is not broken.
use std::rc::Rc;
use std::{fmt, iter, mem};
use either::Either;
use rustc_data_structures::frozen::Frozen;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_errors::struct_span_err;
use rustc_hir as hir;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::lang_items::LangItem;
use rustc_index::vec::{Idx, IndexVec};
use rustc_infer::infer::canonical::QueryRegionConstraints;
use rustc_infer::infer::outlives::env::RegionBoundPairs;
use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
use rustc_infer::infer::{
InferCtxt, InferOk, LateBoundRegionConversionTime, NllRegionVariableOrigin,
};
use rustc_middle::mir::tcx::PlaceTy;
use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor};
use rustc_middle::mir::AssertKind;
use rustc_middle::mir::*;
use rustc_middle::ty::adjustment::PointerCast;
use rustc_middle::ty::cast::CastTy;
use rustc_middle::ty::fold::TypeFoldable;
use rustc_middle::ty::subst::{GenericArgKind, Subst, SubstsRef, UserSubsts};
use rustc_middle::ty::{
self, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, RegionVid, ToPredicate, Ty,
TyCtxt, UserType, UserTypeAnnotationIndex, WithConstness,
};
use rustc_span::{Span, DUMMY_SP};
use rustc_target::abi::VariantIdx;
use rustc_trait_selection::infer::InferCtxtExt as _;
use rustc_trait_selection::opaque_types::{GenerateMemberConstraints, InferCtxtExt};
use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
use rustc_trait_selection::traits::query::type_op;
use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp;
use rustc_trait_selection::traits::query::{Fallible, NoSolution};
use rustc_trait_selection::traits::{self, ObligationCause, PredicateObligations};
use crate::dataflow::impls::MaybeInitializedPlaces;
use crate::dataflow::move_paths::MoveData;
use crate::dataflow::ResultsCursor;
use crate::transform::{
check_consts::ConstCx, promote_consts::is_const_fn_in_array_repeat_expression,
};
use crate::borrow_check::{
borrow_set::BorrowSet,
constraints::{OutlivesConstraint, OutlivesConstraintSet},
facts::AllFacts,
location::LocationTable,
member_constraints::MemberConstraintSet,
nll::ToRegionVid,
path_utils,
region_infer::values::{
LivenessValues, PlaceholderIndex, PlaceholderIndices, RegionValueElements,
},
region_infer::{ClosureRegionRequirementsExt, TypeTest},
renumber,
type_check::free_region_relations::{CreateResult, UniversalRegionRelations},
universal_regions::{DefiningTy, UniversalRegions},
Upvar,
};
macro_rules! span_mirbug {
($context:expr, $elem:expr, $($message:tt)*) => ({
$crate::borrow_check::type_check::mirbug(
$context.tcx(),
$context.last_span,
&format!(
"broken MIR in {:?} ({:?}): {}",
$context.body.source.def_id(),
$elem,
format_args!($($message)*),
),
)
})
}
macro_rules! span_mirbug_and_err {
($context:expr, $elem:expr, $($message:tt)*) => ({
{
span_mirbug!($context, $elem, $($message)*);
$context.error()
}
})
}
mod constraint_conversion;
pub mod free_region_relations;
mod input_output;
crate mod liveness;
mod relate_tys;
/// Type checks the given `mir` in the context of the inference
/// context `infcx`. Returns any region constraints that have yet to
/// be proven. This result is includes liveness constraints that
/// ensure that regions appearing in the types of all local variables
/// are live at all points where that local variable may later be
/// used.
///
/// This phase of type-check ought to be infallible -- this is because
/// the original, HIR-based type-check succeeded. So if any errors
/// occur here, we will get a `bug!` reported.
///
/// # Parameters
///
/// - `infcx` -- inference context to use
/// - `param_env` -- parameter environment to use for trait solving
/// - `body` -- MIR body to type-check
/// - `promoted` -- map of promoted constants within `body`
/// - `universal_regions` -- the universal regions from `body`s function signature
/// - `location_table` -- MIR location map of `body`
/// - `borrow_set` -- information about borrows occurring in `body`
/// - `all_facts` -- when using Polonius, this is the generated set of Polonius facts
/// - `flow_inits` -- results of a maybe-init dataflow analysis
/// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
/// - `elements` -- MIR region map
pub(crate) fn type_check<'mir, 'tcx>(
infcx: &InferCtxt<'_, 'tcx>,
param_env: ty::ParamEnv<'tcx>,
body: &Body<'tcx>,
promoted: &IndexVec<Promoted, Body<'tcx>>,
universal_regions: &Rc<UniversalRegions<'tcx>>,
location_table: &LocationTable,
borrow_set: &BorrowSet<'tcx>,
all_facts: &mut Option<AllFacts>,
flow_inits: &mut ResultsCursor<'mir, 'tcx, MaybeInitializedPlaces<'mir, 'tcx>>,
move_data: &MoveData<'tcx>,
elements: &Rc<RegionValueElements>,
upvars: &[Upvar<'tcx>],
) -> MirTypeckResults<'tcx> {
let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
let mut constraints = MirTypeckRegionConstraints {
placeholder_indices: PlaceholderIndices::default(),
placeholder_index_to_region: IndexVec::default(),
liveness_constraints: LivenessValues::new(elements.clone()),
outlives_constraints: OutlivesConstraintSet::default(),
member_constraints: MemberConstraintSet::default(),
closure_bounds_mapping: Default::default(),
type_tests: Vec::default(),
};
let CreateResult {
universal_region_relations,
region_bound_pairs,
normalized_inputs_and_output,
} = free_region_relations::create(
infcx,
param_env,
Some(implicit_region_bound),
universal_regions,
&mut constraints,
);
let mut borrowck_context = BorrowCheckContext {
universal_regions,
location_table,
borrow_set,
all_facts,
constraints: &mut constraints,
upvars,
};
let opaque_type_values = type_check_internal(
infcx,
param_env,
body,
promoted,
®ion_bound_pairs,
implicit_region_bound,
&mut borrowck_context,
&universal_region_relations,
|mut cx| {
cx.equate_inputs_and_outputs(&body, universal_regions, &normalized_inputs_and_output);
liveness::generate(&mut cx, body, elements, flow_inits, move_data, location_table);
translate_outlives_facts(&mut cx);
cx.opaque_type_values
},
);
MirTypeckResults { constraints, universal_region_relations, opaque_type_values }
}
fn type_check_internal<'a, 'tcx, R>(
infcx: &'a InferCtxt<'a, 'tcx>,
param_env: ty::ParamEnv<'tcx>,
body: &'a Body<'tcx>,
promoted: &'a IndexVec<Promoted, Body<'tcx>>,
region_bound_pairs: &'a RegionBoundPairs<'tcx>,
implicit_region_bound: ty::Region<'tcx>,
borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
universal_region_relations: &'a UniversalRegionRelations<'tcx>,
extra: impl FnOnce(TypeChecker<'a, 'tcx>) -> R,
) -> R {
let mut checker = TypeChecker::new(
infcx,
body,
param_env,
region_bound_pairs,
implicit_region_bound,
borrowck_context,
universal_region_relations,
);
let errors_reported = {
let mut verifier = TypeVerifier::new(&mut checker, body, promoted);
verifier.visit_body(&body);
verifier.errors_reported
};
if !errors_reported {
// if verifier failed, don't do further checks to avoid ICEs
checker.typeck_mir(body);
}
extra(checker)
}
fn translate_outlives_facts(typeck: &mut TypeChecker<'_, '_>) {
let cx = &mut typeck.borrowck_context;
if let Some(facts) = cx.all_facts {
let _prof_timer = typeck.infcx.tcx.prof.generic_activity("polonius_fact_generation");
let location_table = cx.location_table;
facts.outlives.extend(cx.constraints.outlives_constraints.outlives().iter().flat_map(
|constraint: &OutlivesConstraint| {
if let Some(from_location) = constraint.locations.from_location() {
Either::Left(iter::once((
constraint.sup,
constraint.sub,
location_table.mid_index(from_location),
)))
} else {
Either::Right(
location_table
.all_points()
.map(move |location| (constraint.sup, constraint.sub, location)),
)
}
},
));
}
}
fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: &str) {
// We sometimes see MIR failures (notably predicate failures) due to
// the fact that we check rvalue sized predicates here. So use `delay_span_bug`
// to avoid reporting bugs in those cases.
tcx.sess.diagnostic().delay_span_bug(span, msg);
}
enum FieldAccessError {
OutOfRange { field_count: usize },
}
/// Verifies that MIR types are sane to not crash further checks.
///
/// The sanitize_XYZ methods here take an MIR object and compute its
/// type, calling `span_mirbug` and returning an error type if there
/// is a problem.
struct TypeVerifier<'a, 'b, 'tcx> {
cx: &'a mut TypeChecker<'b, 'tcx>,
body: &'b Body<'tcx>,
promoted: &'b IndexVec<Promoted, Body<'tcx>>,
last_span: Span,
errors_reported: bool,
}
impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> {
fn visit_span(&mut self, span: &Span) {
if !span.is_dummy() {
self.last_span = *span;
}
}
fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
self.sanitize_place(place, location, context);
}
fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
self.super_constant(constant, location);
let ty = self.sanitize_type(constant, constant.literal.ty);
self.cx.infcx.tcx.for_each_free_region(&ty, |live_region| {
let live_region_vid =
self.cx.borrowck_context.universal_regions.to_region_vid(live_region);
self.cx
.borrowck_context
.constraints
.liveness_constraints
.add_element(live_region_vid, location);
});
if let Some(annotation_index) = constant.user_ty {
if let Err(terr) = self.cx.relate_type_and_user_type(
constant.literal.ty,
ty::Variance::Invariant,
&UserTypeProjection { base: annotation_index, projs: vec![] },
location.to_locations(),
ConstraintCategory::Boring,
) {
let annotation = &self.cx.user_type_annotations[annotation_index];
span_mirbug!(
self,
constant,
"bad constant user type {:?} vs {:?}: {:?}",
annotation,
constant.literal.ty,
terr,
);
}
} else {
let tcx = self.tcx();
if let ty::ConstKind::Unevaluated(def, substs, promoted) = constant.literal.val {
if let Some(promoted) = promoted {
let check_err = |verifier: &mut TypeVerifier<'a, 'b, 'tcx>,
promoted: &Body<'tcx>,
ty,
san_ty| {
if let Err(terr) = verifier.cx.eq_types(
san_ty,
ty,
location.to_locations(),
ConstraintCategory::Boring,
) {
span_mirbug!(
verifier,
promoted,
"bad promoted type ({:?}: {:?}): {:?}",
ty,
san_ty,
terr
);
};
};
if !self.errors_reported {
let promoted_body = &self.promoted[promoted];
self.sanitize_promoted(promoted_body, location);
let promoted_ty = promoted_body.return_ty();
check_err(self, promoted_body, ty, promoted_ty);
}
} else {
if let Err(terr) = self.cx.fully_perform_op(
location.to_locations(),
ConstraintCategory::Boring,
self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
constant.literal.ty,
def.did,
UserSubsts { substs, user_self_ty: None },
)),
) {
span_mirbug!(
self,
constant,
"bad constant type {:?} ({:?})",
constant,
terr
);
}
}
} else if let Some(static_def_id) = constant.check_static_ptr(tcx) {
let unnormalized_ty = tcx.type_of(static_def_id);
let locations = location.to_locations();
let normalized_ty = self.cx.normalize(unnormalized_ty, locations);
let literal_ty = constant.literal.ty.builtin_deref(true).unwrap().ty;
if let Err(terr) = self.cx.eq_types(
normalized_ty,
literal_ty,
locations,
ConstraintCategory::Boring,
) {
span_mirbug!(self, constant, "bad static type {:?} ({:?})", constant, terr);
}
}
if let ty::FnDef(def_id, substs) = *constant.literal.ty.kind() {
let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
self.cx.normalize_and_prove_instantiated_predicates(
instantiated_predicates,
location.to_locations(),
);
}
}
}
fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
self.super_rvalue(rvalue, location);
let rval_ty = rvalue.ty(self.body, self.tcx());
self.sanitize_type(rvalue, rval_ty);
}
fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
self.super_local_decl(local, local_decl);
self.sanitize_type(local_decl, local_decl.ty);
if let Some(user_ty) = &local_decl.user_ty {
for (user_ty, span) in user_ty.projections_and_spans() {
let ty = if !local_decl.is_nonref_binding() {
// If we have a binding of the form `let ref x: T = ..`
// then remove the outermost reference so we can check the
// type annotation for the remaining type.
if let ty::Ref(_, rty, _) = local_decl.ty.kind() {
rty
} else {
bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
}
} else {
local_decl.ty
};
if let Err(terr) = self.cx.relate_type_and_user_type(
ty,
ty::Variance::Invariant,
user_ty,
Locations::All(*span),
ConstraintCategory::TypeAnnotation,
) {
span_mirbug!(
self,
local,
"bad user type on variable {:?}: {:?} != {:?} ({:?})",
local,
local_decl.ty,
local_decl.user_ty,
terr,
);
}
}
}
}
fn visit_body(&mut self, body: &Body<'tcx>) {
self.sanitize_type(&"return type", body.return_ty());
for local_decl in &body.local_decls {
self.sanitize_type(local_decl, local_decl.ty);
}
if self.errors_reported {
return;
}
self.super_body(body);
}
}
impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
fn new(
cx: &'a mut TypeChecker<'b, 'tcx>,
body: &'b Body<'tcx>,
promoted: &'b IndexVec<Promoted, Body<'tcx>>,
) -> Self {
TypeVerifier { body, promoted, cx, last_span: body.span, errors_reported: false }
}
fn tcx(&self) -> TyCtxt<'tcx> {
self.cx.infcx.tcx
}
fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
if ty.has_escaping_bound_vars() || ty.references_error() {
span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
} else {
ty
}
}
/// Checks that the types internal to the `place` match up with
/// what would be expected.
fn sanitize_place(
&mut self,
place: &Place<'tcx>,
location: Location,
context: PlaceContext,
) -> PlaceTy<'tcx> {
debug!("sanitize_place: {:?}", place);
let mut place_ty = PlaceTy::from_ty(self.body.local_decls[place.local].ty);
for elem in place.projection.iter() {
if place_ty.variant_index.is_none() {
if place_ty.ty.references_error() {
assert!(self.errors_reported);
return PlaceTy::from_ty(self.tcx().ty_error());
}
}
place_ty = self.sanitize_projection(place_ty, elem, place, location)
}
if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
let tcx = self.tcx();
let trait_ref = ty::TraitRef {
def_id: tcx.require_lang_item(LangItem::Copy, Some(self.last_span)),
substs: tcx.mk_substs_trait(place_ty.ty, &[]),
};
// To have a `Copy` operand, the type `T` of the
// value must be `Copy`. Note that we prove that `T: Copy`,
// rather than using the `is_copy_modulo_regions`
// test. This is important because
// `is_copy_modulo_regions` ignores the resulting region
// obligations and assumes they pass. This can result in
// bounds from `Copy` impls being unsoundly ignored (e.g.,
// #29149). Note that we decide to use `Copy` before knowing
// whether the bounds fully apply: in effect, the rule is
// that if a value of some type could implement `Copy`, then
// it must.
self.cx.prove_trait_ref(
trait_ref,
location.to_locations(),
ConstraintCategory::CopyBound,
);
}
place_ty
}
fn sanitize_promoted(&mut self, promoted_body: &'b Body<'tcx>, location: Location) {
// Determine the constraints from the promoted MIR by running the type
// checker on the promoted MIR, then transfer the constraints back to
// the main MIR, changing the locations to the provided location.
let parent_body = mem::replace(&mut self.body, promoted_body);
// Use new sets of constraints and closure bounds so that we can
// modify their locations.
let all_facts = &mut None;
let mut constraints = Default::default();
let mut closure_bounds = Default::default();
let mut liveness_constraints =
LivenessValues::new(Rc::new(RegionValueElements::new(&promoted_body)));
// Don't try to add borrow_region facts for the promoted MIR
let mut swap_constraints = |this: &mut Self| {
mem::swap(this.cx.borrowck_context.all_facts, all_facts);
mem::swap(
&mut this.cx.borrowck_context.constraints.outlives_constraints,
&mut constraints,
);
mem::swap(
&mut this.cx.borrowck_context.constraints.closure_bounds_mapping,
&mut closure_bounds,
);
mem::swap(
&mut this.cx.borrowck_context.constraints.liveness_constraints,
&mut liveness_constraints,
);
};
swap_constraints(self);
self.visit_body(&promoted_body);
if !self.errors_reported {
// if verifier failed, don't do further checks to avoid ICEs
self.cx.typeck_mir(promoted_body);
}
self.body = parent_body;
// Merge the outlives constraints back in, at the given location.
swap_constraints(self);
let locations = location.to_locations();
for constraint in constraints.outlives().iter() {
let mut constraint = *constraint;
constraint.locations = locations;
if let ConstraintCategory::Return(_)
| ConstraintCategory::UseAsConst
| ConstraintCategory::UseAsStatic = constraint.category
{
// "Returning" from a promoted is an assignment to a
// temporary from the user's point of view.
constraint.category = ConstraintCategory::Boring;
}
self.cx.borrowck_context.constraints.outlives_constraints.push(constraint)
}
for live_region in liveness_constraints.rows() {
self.cx
.borrowck_context
.constraints
.liveness_constraints
.add_element(live_region, location);
}
if !closure_bounds.is_empty() {
let combined_bounds_mapping =
closure_bounds.into_iter().flat_map(|(_, value)| value).collect();
let existing = self
.cx
.borrowck_context
.constraints
.closure_bounds_mapping
.insert(location, combined_bounds_mapping);
assert!(existing.is_none(), "Multiple promoteds/closures at the same location.");
}
}
fn sanitize_projection(
&mut self,
base: PlaceTy<'tcx>,
pi: PlaceElem<'tcx>,
place: &Place<'tcx>,
location: Location,
) -> PlaceTy<'tcx> {
debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
let tcx = self.tcx();
let base_ty = base.ty;
match pi {
ProjectionElem::Deref => {
let deref_ty = base_ty.builtin_deref(true);
PlaceTy::from_ty(deref_ty.map(|t| t.ty).unwrap_or_else(|| {
span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
}))
}
ProjectionElem::Index(i) => {
let index_ty = Place::from(i).ty(self.body, tcx).ty;
if index_ty != tcx.types.usize {
PlaceTy::from_ty(span_mirbug_and_err!(self, i, "index by non-usize {:?}", i))
} else {
PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
}))
}
}
ProjectionElem::ConstantIndex { .. } => {
// consider verifying in-bounds
PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
}))
}
ProjectionElem::Subslice { from, to, from_end } => {
PlaceTy::from_ty(match base_ty.kind() {
ty::Array(inner, _) => {
assert!(!from_end, "array subslices should not use from_end");
tcx.mk_array(inner, to - from)
}
ty::Slice(..) => {
assert!(from_end, "slice subslices should use from_end");
base_ty
}
_ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
})
}
ProjectionElem::Downcast(maybe_name, index) => match base_ty.kind() {
ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
if index.as_usize() >= adt_def.variants.len() {
PlaceTy::from_ty(span_mirbug_and_err!(
self,
place,
"cast to variant #{:?} but enum only has {:?}",
index,
adt_def.variants.len()
))
} else {
PlaceTy { ty: base_ty, variant_index: Some(index) }
}
}
// We do not need to handle generators here, because this runs
// before the generator transform stage.
_ => {
let ty = if let Some(name) = maybe_name {
span_mirbug_and_err!(
self,
place,
"can't downcast {:?} as {:?}",
base_ty,
name
)
} else {
span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
};
PlaceTy::from_ty(ty)
}
},
ProjectionElem::Field(field, fty) => {
let fty = self.sanitize_type(place, fty);
match self.field_ty(place, base, field, location) {
Ok(ty) => {
let ty = self.cx.normalize(ty, location);
if let Err(terr) = self.cx.eq_types(
ty,
fty,
location.to_locations(),
ConstraintCategory::Boring,
) {
span_mirbug!(
self,
place,
"bad field access ({:?}: {:?}): {:?}",
ty,
fty,
terr
);
}
}
Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
self,
place,
"accessed field #{} but variant only has {}",
field.index(),
field_count
),
}
PlaceTy::from_ty(fty)
}
}
}
fn error(&mut self) -> Ty<'tcx> {
self.errors_reported = true;
self.tcx().ty_error()
}
fn field_ty(
&mut self,
parent: &dyn fmt::Debug,
base_ty: PlaceTy<'tcx>,
field: Field,
location: Location,
) -> Result<Ty<'tcx>, FieldAccessError> {
let tcx = self.tcx();
let (variant, substs) = match base_ty {
PlaceTy { ty, variant_index: Some(variant_index) } => match *ty.kind() {
ty::Adt(adt_def, substs) => (&adt_def.variants[variant_index], substs),
ty::Generator(def_id, substs, _) => {
let mut variants = substs.as_generator().state_tys(def_id, tcx);
let mut variant = match variants.nth(variant_index.into()) {
Some(v) => v,
None => bug!(
"variant_index of generator out of range: {:?}/{:?}",
variant_index,
substs.as_generator().state_tys(def_id, tcx).count()
),
};
return match variant.nth(field.index()) {
Some(ty) => Ok(ty),
None => Err(FieldAccessError::OutOfRange { field_count: variant.count() }),
};
}
_ => bug!("can't have downcast of non-adt non-generator type"),
},
PlaceTy { ty, variant_index: None } => match *ty.kind() {
ty::Adt(adt_def, substs) if !adt_def.is_enum() => {
(&adt_def.variants[VariantIdx::new(0)], substs)
}
ty::Closure(_, substs) => {
return match substs
.as_closure()
.tupled_upvars_ty()
.tuple_element_ty(field.index())
{
Some(ty) => Ok(ty),
None => Err(FieldAccessError::OutOfRange {
field_count: substs.as_closure().upvar_tys().count(),
}),
};
}
ty::Generator(_, substs, _) => {
// Only prefix fields (upvars and current state) are
// accessible without a variant index.
return match substs.as_generator().prefix_tys().nth(field.index()) {
Some(ty) => Ok(ty),
None => Err(FieldAccessError::OutOfRange {
field_count: substs.as_generator().prefix_tys().count(),
}),
};
}
ty::Tuple(tys) => {
return match tys.get(field.index()) {
Some(&ty) => Ok(ty.expect_ty()),
None => Err(FieldAccessError::OutOfRange { field_count: tys.len() }),
};
}
_ => {
return Ok(span_mirbug_and_err!(
self,
parent,
"can't project out of {:?}",
base_ty
));
}
},
};
if let Some(field) = variant.fields.get(field.index()) {
Ok(self.cx.normalize(field.ty(tcx, substs), location))
} else {
Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
}
}
}
/// The MIR type checker. Visits the MIR and enforces all the
/// constraints needed for it to be valid and well-typed. Along the
/// way, it accrues region constraints -- these can later be used by
/// NLL region checking.
struct TypeChecker<'a, 'tcx> {
infcx: &'a InferCtxt<'a, 'tcx>,
param_env: ty::ParamEnv<'tcx>,
last_span: Span,
body: &'a Body<'tcx>,
/// User type annotations are shared between the main MIR and the MIR of
/// all of the promoted items.
user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
region_bound_pairs: &'a RegionBoundPairs<'tcx>,
implicit_region_bound: ty::Region<'tcx>,
reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
universal_region_relations: &'a UniversalRegionRelations<'tcx>,
opaque_type_values: FxHashMap<DefId, ty::ResolvedOpaqueTy<'tcx>>,
}
struct BorrowCheckContext<'a, 'tcx> {
universal_regions: &'a UniversalRegions<'tcx>,
location_table: &'a LocationTable,
all_facts: &'a mut Option<AllFacts>,
borrow_set: &'a BorrowSet<'tcx>,
constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
upvars: &'a [Upvar<'tcx>],
}
crate struct MirTypeckResults<'tcx> {
crate constraints: MirTypeckRegionConstraints<'tcx>,
pub(in crate::borrow_check) universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
crate opaque_type_values: FxHashMap<DefId, ty::ResolvedOpaqueTy<'tcx>>,
}
/// A collection of region constraints that must be satisfied for the
/// program to be considered well-typed.
crate struct MirTypeckRegionConstraints<'tcx> {
/// Maps from a `ty::Placeholder` to the corresponding
/// `PlaceholderIndex` bit that we will use for it.
///
/// To keep everything in sync, do not insert this set
/// directly. Instead, use the `placeholder_region` helper.
crate placeholder_indices: PlaceholderIndices,
/// Each time we add a placeholder to `placeholder_indices`, we
/// also create a corresponding "representative" region vid for
/// that wraps it. This vector tracks those. This way, when we
/// convert the same `ty::RePlaceholder(p)` twice, we can map to
/// the same underlying `RegionVid`.
crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
/// In general, the type-checker is not responsible for enforcing
/// liveness constraints; this job falls to the region inferencer,
/// which performs a liveness analysis. However, in some limited
/// cases, the MIR type-checker creates temporary regions that do
/// not otherwise appear in the MIR -- in particular, the
/// late-bound regions that it instantiates at call-sites -- and
/// hence it must report on their liveness constraints.
crate liveness_constraints: LivenessValues<RegionVid>,
crate outlives_constraints: OutlivesConstraintSet,
crate member_constraints: MemberConstraintSet<'tcx, RegionVid>,
crate closure_bounds_mapping:
FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
crate type_tests: Vec<TypeTest<'tcx>>,
}
impl MirTypeckRegionConstraints<'tcx> {
fn placeholder_region(
&mut self,
infcx: &InferCtxt<'_, 'tcx>,
placeholder: ty::PlaceholderRegion,
) -> ty::Region<'tcx> {
let placeholder_index = self.placeholder_indices.insert(placeholder);
match self.placeholder_index_to_region.get(placeholder_index) {
Some(&v) => v,
None => {
let origin = NllRegionVariableOrigin::Placeholder(placeholder);
let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
self.placeholder_index_to_region.push(region);
region
}
}
}
}
/// The `Locations` type summarizes *where* region constraints are
/// required to hold. Normally, this is at a particular point which
/// created the obligation, but for constraints that the user gave, we
/// want the constraint to hold at all points.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum Locations {
/// Indicates that a type constraint should always be true. This
/// is particularly important in the new borrowck analysis for
/// things like the type of the return slot. Consider this
/// example:
///
/// ```
/// fn foo<'a>(x: &'a u32) -> &'a u32 {
/// let y = 22;
/// return &y; // error
/// }
/// ```
///
/// Here, we wind up with the signature from the return type being
/// something like `&'1 u32` where `'1` is a universal region. But
/// the type of the return slot `_0` is something like `&'2 u32`
/// where `'2` is an existential region variable. The type checker
/// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
/// older NLL analysis, we required this only at the entry point
/// to the function. By the nature of the constraints, this wound
/// up propagating to all points reachable from start (because
/// `'1` -- as a universal region -- is live everywhere). In the
/// newer analysis, though, this doesn't work: `_0` is considered
/// dead at the start (it has no usable value) and hence this type
/// equality is basically a no-op. Then, later on, when we do `_0
/// = &'3 y`, that region `'3` never winds up related to the
/// universal region `'1` and hence no error occurs. Therefore, we
/// use Locations::All instead, which ensures that the `'1` and
/// `'2` are equal everything. We also use this for other
/// user-given type annotations; e.g., if the user wrote `let mut
/// x: &'static u32 = ...`, we would ensure that all values
/// assigned to `x` are of `'static` lifetime.
///
/// The span points to the place the constraint arose. For example,
/// it points to the type in a user-given type annotation. If
/// there's no sensible span then it's DUMMY_SP.
All(Span),
/// An outlives constraint that only has to hold at a single location,
/// usually it represents a point where references flow from one spot to
/// another (e.g., `x = y`)
Single(Location),
}
impl Locations {
pub fn from_location(&self) -> Option<Location> {
match self {
Locations::All(_) => None,
Locations::Single(from_location) => Some(*from_location),
}
}
/// Gets a span representing the location.
pub fn span(&self, body: &Body<'_>) -> Span {
match self {
Locations::All(span) => *span,
Locations::Single(l) => body.source_info(*l).span,
}
}
}
impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
fn new(
infcx: &'a InferCtxt<'a, 'tcx>,
body: &'a Body<'tcx>,
param_env: ty::ParamEnv<'tcx>,
region_bound_pairs: &'a RegionBoundPairs<'tcx>,
implicit_region_bound: ty::Region<'tcx>,
borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
universal_region_relations: &'a UniversalRegionRelations<'tcx>,
) -> Self {
let mut checker = Self {
infcx,
last_span: DUMMY_SP,
body,
user_type_annotations: &body.user_type_annotations,
param_env,
region_bound_pairs,
implicit_region_bound,
borrowck_context,
reported_errors: Default::default(),
universal_region_relations,
opaque_type_values: FxHashMap::default(),
};
checker.check_user_type_annotations();
checker
}
fn unsized_feature_enabled(&self) -> bool {
let features = self.tcx().features();
features.unsized_locals || features.unsized_fn_params
}
/// Equate the inferred type and the annotated type for user type annotations
fn check_user_type_annotations(&mut self) {
debug!(
"check_user_type_annotations: user_type_annotations={:?}",
self.user_type_annotations
);
for user_annotation in self.user_type_annotations {
let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
let (annotation, _) =
self.infcx.instantiate_canonical_with_fresh_inference_vars(span, user_ty);
match annotation {
UserType::Ty(mut ty) => {
ty = self.normalize(ty, Locations::All(span));
if let Err(terr) = self.eq_types(
ty,
inferred_ty,
Locations::All(span),
ConstraintCategory::BoringNoLocation,
) {
span_mirbug!(
self,
user_annotation,
"bad user type ({:?} = {:?}): {:?}",
ty,
inferred_ty,
terr
);
}
self.prove_predicate(
ty::PredicateKind::WellFormed(inferred_ty.into()).to_predicate(self.tcx()),
Locations::All(span),
ConstraintCategory::TypeAnnotation,
);
}
UserType::TypeOf(def_id, user_substs) => {
if let Err(terr) = self.fully_perform_op(
Locations::All(span),
ConstraintCategory::BoringNoLocation,
self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
inferred_ty,
def_id,
user_substs,
)),
) {
span_mirbug!(
self,
user_annotation,
"bad user type AscribeUserType({:?}, {:?} {:?}): {:?}",
inferred_ty,
def_id,
user_substs,
terr
);
}
}
}
}
}
/// Given some operation `op` that manipulates types, proves
/// predicates, or otherwise uses the inference context, executes
/// `op` and then executes all the further obligations that `op`
/// returns. This will yield a set of outlives constraints amongst
/// regions which are extracted and stored as having occurred at
/// `locations`.
///
/// **Any `rustc_infer::infer` operations that might generate region
/// constraints should occur within this method so that those
/// constraints can be properly localized!**
fn fully_perform_op<R>(
&mut self,
locations: Locations,
category: ConstraintCategory,
op: impl type_op::TypeOp<'tcx, Output = R>,
) -> Fallible<R> {
let (r, opt_data) = op.fully_perform(self.infcx)?;
if let Some(data) = &opt_data {
self.push_region_constraints(locations, category, data);
}
Ok(r)
}
fn push_region_constraints(
&mut self,
locations: Locations,
category: ConstraintCategory,
data: &QueryRegionConstraints<'tcx>,
) {
debug!("push_region_constraints: constraints generated at {:?} are {:#?}", locations, data);
constraint_conversion::ConstraintConversion::new(
self.infcx,
self.borrowck_context.universal_regions,
self.region_bound_pairs,
Some(self.implicit_region_bound),
self.param_env,
locations,
category,
&mut self.borrowck_context.constraints,
)
.convert_all(data);
}
/// Convenient wrapper around `relate_tys::relate_types` -- see
/// that fn for docs.
fn relate_types(
&mut self,
a: Ty<'tcx>,
v: ty::Variance,
b: Ty<'tcx>,
locations: Locations,
category: ConstraintCategory,
) -> Fallible<()> {
relate_tys::relate_types(
self.infcx,
self.param_env,
a,
v,
b,
locations,
category,
Some(self.borrowck_context),
)
}
fn sub_types(
&mut self,
sub: Ty<'tcx>,
sup: Ty<'tcx>,
locations: Locations,
category: ConstraintCategory,
) -> Fallible<()> {
self.relate_types(sub, ty::Variance::Covariant, sup, locations, category)
}
/// Try to relate `sub <: sup`; if this fails, instantiate opaque
/// variables in `sub` with their inferred definitions and try
/// again. This is used for opaque types in places (e.g., `let x:
/// impl Foo = ..`).
fn sub_types_or_anon(
&mut self,
sub: Ty<'tcx>,
sup: Ty<'tcx>,
locations: Locations,
category: ConstraintCategory,
) -> Fallible<()> {
if let Err(terr) = self.sub_types(sub, sup, locations, category) {
if let ty::Opaque(..) = sup.kind() {
// When you have `let x: impl Foo = ...` in a closure,
// the resulting inferend values are stored with the
// def-id of the base function.
let parent_def_id =
self.tcx().closure_base_def_id(self.body.source.def_id()).expect_local();
return self.eq_opaque_type_and_type(sub, sup, parent_def_id, locations, category);
} else {
return Err(terr);
}
}
Ok(())
}
fn eq_types(
&mut self,
a: Ty<'tcx>,
b: Ty<'tcx>,
locations: Locations,
category: ConstraintCategory,
) -> Fallible<()> {
self.relate_types(a, ty::Variance::Invariant, b, locations, category)
}
fn relate_type_and_user_type(
&mut self,
a: Ty<'tcx>,
v: ty::Variance,
user_ty: &UserTypeProjection,
locations: Locations,
category: ConstraintCategory,
) -> Fallible<()> {
debug!(
"relate_type_and_user_type(a={:?}, v={:?}, user_ty={:?}, locations={:?})",
a, v, user_ty, locations,
);
let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
let tcx = self.infcx.tcx;
for proj in &user_ty.projs {
let projected_ty = curr_projected_ty.projection_ty_core(
tcx,
self.param_env,
proj,
|this, field, &()| {
let ty = this.field_ty(tcx, field);
self.normalize(ty, locations)
},
);
curr_projected_ty = projected_ty;
}
debug!(
"user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
user_ty.base, annotated_type, user_ty.projs, curr_projected_ty
);
let ty = curr_projected_ty.ty;
self.relate_types(a, v, ty, locations, category)?;
Ok(())
}
fn eq_opaque_type_and_type(
&mut self,
revealed_ty: Ty<'tcx>,
anon_ty: Ty<'tcx>,
anon_owner_def_id: LocalDefId,
locations: Locations,
category: ConstraintCategory,
) -> Fallible<()> {
debug!(
"eq_opaque_type_and_type( \
revealed_ty={:?}, \
anon_ty={:?})",
revealed_ty, anon_ty
);
// Fast path for the common case.
if !anon_ty.has_opaque_types() {
if let Err(terr) = self.eq_types(anon_ty, revealed_ty, locations, category) {
span_mirbug!(
self,
locations,
"eq_opaque_type_and_type: `{:?}=={:?}` failed with `{:?}`",
revealed_ty,
anon_ty,
terr
);
}
return Ok(());
}
let infcx = self.infcx;
let tcx = infcx.tcx;
let param_env = self.param_env;
let body = self.body;
let concrete_opaque_types = &tcx.typeck(anon_owner_def_id).concrete_opaque_types;
let mut opaque_type_values = Vec::new();
debug!("eq_opaque_type_and_type: mir_def_id={:?}", body.source.def_id());
let opaque_type_map = self.fully_perform_op(
locations,
category,
CustomTypeOp::new(
|infcx| {
let mut obligations = ObligationAccumulator::default();
let dummy_body_id = hir::CRATE_HIR_ID;
let (output_ty, opaque_type_map) =
obligations.add(infcx.instantiate_opaque_types(
anon_owner_def_id,
dummy_body_id,
param_env,
anon_ty,
locations.span(body),
));
debug!(
"eq_opaque_type_and_type: \
instantiated output_ty={:?} \
opaque_type_map={:#?} \
revealed_ty={:?}",
output_ty, opaque_type_map, revealed_ty
);
// Make sure that the inferred types are well-formed. I'm
// not entirely sure this is needed (the HIR type check
// didn't do this) but it seems sensible to prevent opaque
// types hiding ill-formed types.
obligations.obligations.push(traits::Obligation::new(
ObligationCause::dummy(),
param_env,
ty::PredicateKind::WellFormed(revealed_ty.into()).to_predicate(infcx.tcx),
));
obligations.add(
infcx
.at(&ObligationCause::dummy(), param_env)
.eq(output_ty, revealed_ty)?,
);
for (&opaque_def_id, opaque_decl) in &opaque_type_map {
let resolved_ty = infcx.resolve_vars_if_possible(opaque_decl.concrete_ty);
let concrete_is_opaque = if let ty::Opaque(def_id, _) = resolved_ty.kind() {
*def_id == opaque_def_id
} else {
false
};
let opaque_defn_ty = match concrete_opaque_types.get(&opaque_def_id) {
None => {
if !concrete_is_opaque {
tcx.sess.delay_span_bug(
body.span,
&format!(
"Non-defining use of {:?} with revealed type",
opaque_def_id,
),
);
}
continue;
}
Some(opaque_defn_ty) => opaque_defn_ty,
};
debug!("opaque_defn_ty = {:?}", opaque_defn_ty);
let subst_opaque_defn_ty =
opaque_defn_ty.concrete_type.subst(tcx, opaque_decl.substs);
let renumbered_opaque_defn_ty =
renumber::renumber_regions(infcx, subst_opaque_defn_ty);
debug!(
"eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?}",
opaque_decl.concrete_ty, resolved_ty, renumbered_opaque_defn_ty,
);
if !concrete_is_opaque {
// Equate concrete_ty (an inference variable) with
// the renumbered type from typeck.
obligations.add(
infcx
.at(&ObligationCause::dummy(), param_env)
.eq(opaque_decl.concrete_ty, renumbered_opaque_defn_ty)?,
);
opaque_type_values.push((
opaque_def_id,
ty::ResolvedOpaqueTy {
concrete_type: renumbered_opaque_defn_ty,
substs: opaque_decl.substs,
},
));
} else {
// We're using an opaque `impl Trait` type without
// 'revealing' it. For example, code like this:
//
// type Foo = impl Debug;
// fn foo1() -> Foo { ... }
// fn foo2() -> Foo { foo1() }
//
// In `foo2`, we're not revealing the type of `Foo` - we're
// just treating it as the opaque type.
//
// When this occurs, we do *not* want to try to equate
// the concrete type with the underlying defining type
// of the opaque type - this will always fail, since
// the defining type of an opaque type is always
// some other type (e.g. not itself)
// Essentially, none of the normal obligations apply here -
// we're just passing around some unknown opaque type,
// without actually looking at the underlying type it
// gets 'revealed' into
debug!(
"eq_opaque_type_and_type: non-defining use of {:?}",
opaque_def_id,
);
}
}
debug!("eq_opaque_type_and_type: equated");
Ok(InferOk {
value: Some(opaque_type_map),
obligations: obligations.into_vec(),
})
},
|| "input_output".to_string(),
),
)?;
self.opaque_type_values.extend(opaque_type_values);
let universal_region_relations = self.universal_region_relations;
// Finally, if we instantiated the anon types successfully, we
// have to solve any bounds (e.g., `-> impl Iterator` needs to
// prove that `T: Iterator` where `T` is the type we
// instantiated it with).
if let Some(opaque_type_map) = opaque_type_map {
for (opaque_def_id, opaque_decl) in opaque_type_map {
self.fully_perform_op(
locations,
ConstraintCategory::OpaqueType,
CustomTypeOp::new(
|_cx| {
infcx.constrain_opaque_type(
opaque_def_id,
&opaque_decl,
GenerateMemberConstraints::IfNoStaticBound,
universal_region_relations,
);
Ok(InferOk { value: (), obligations: vec![] })
},
|| "opaque_type_map".to_string(),
),
)?;
}
}
Ok(())
}
fn tcx(&self) -> TyCtxt<'tcx> {
self.infcx.tcx
}
fn check_stmt(&mut self, body: &Body<'tcx>, stmt: &Statement<'tcx>, location: Location) {
debug!("check_stmt: {:?}", stmt);
let tcx = self.tcx();
match stmt.kind {
StatementKind::Assign(box (ref place, ref rv)) => {
// Assignments to temporaries are not "interesting";
// they are not caused by the user, but rather artifacts
// of lowering. Assignments to other sorts of places *are* interesting
// though.
let category = match place.as_local() {
Some(RETURN_PLACE) => {
if let BorrowCheckContext {
universal_regions:
UniversalRegions { defining_ty: DefiningTy::Const(def_id, _), .. },
..
} = self.borrowck_context
{
if tcx.is_static(*def_id) {
ConstraintCategory::UseAsStatic
} else {
ConstraintCategory::UseAsConst
}
} else {
ConstraintCategory::Return(ReturnConstraint::Normal)
}
}
Some(l) if !body.local_decls[l].is_user_variable() => {
ConstraintCategory::Boring
}
_ => ConstraintCategory::Assignment,
};
let place_ty = place.ty(body, tcx).ty;
let place_ty = self.normalize(place_ty, location);
let rv_ty = rv.ty(body, tcx);
let rv_ty = self.normalize(rv_ty, location);
if let Err(terr) =
self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
{
span_mirbug!(
self,
stmt,
"bad assignment ({:?} = {:?}): {:?}",
place_ty,
rv_ty,
terr
);
}
if let Some(annotation_index) = self.rvalue_user_ty(rv) {
if let Err(terr) = self.relate_type_and_user_type(
rv_ty,
ty::Variance::Invariant,
&UserTypeProjection { base: annotation_index, projs: vec![] },
location.to_locations(),
ConstraintCategory::Boring,
) {
let annotation = &self.user_type_annotations[annotation_index];
span_mirbug!(
self,
stmt,
"bad user type on rvalue ({:?} = {:?}): {:?}",
annotation,
rv_ty,
terr
);
}
}
self.check_rvalue(body, rv, location);
if !self.unsized_feature_enabled() {
let trait_ref = ty::TraitRef {
def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
substs: tcx.mk_substs_trait(place_ty, &[]),
};
self.prove_trait_ref(
trait_ref,
location.to_locations(),
ConstraintCategory::SizedBound,
);
}
}
StatementKind::SetDiscriminant { ref place, variant_index } => {
let place_type = place.ty(body, tcx).ty;
let adt = match place_type.kind() {
ty::Adt(adt, _) if adt.is_enum() => adt,
_ => {
span_bug!(
stmt.source_info.span,
"bad set discriminant ({:?} = {:?}): lhs is not an enum",
place,
variant_index
);
}
};
if variant_index.as_usize() >= adt.variants.len() {
span_bug!(
stmt.source_info.span,
"bad set discriminant ({:?} = {:?}): value of of range",
place,
variant_index
);
};
}
StatementKind::AscribeUserType(box (ref place, ref projection), variance) => {
let place_ty = place.ty(body, tcx).ty;
if let Err(terr) = self.relate_type_and_user_type(
place_ty,
variance,
projection,
Locations::All(stmt.source_info.span),
ConstraintCategory::TypeAnnotation,
) {
let annotation = &self.user_type_annotations[projection.base];
span_mirbug!(
self,
stmt,
"bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
place_ty,
annotation,
projection.projs,
terr
);
}
}
StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping {
..
}) => span_bug!(
stmt.source_info.span,
"Unexpected StatementKind::CopyNonOverlapping, should only appear after lowering_intrinsics",
),
StatementKind::FakeRead(..)
| StatementKind::StorageLive(..)
| StatementKind::StorageDead(..)
| StatementKind::LlvmInlineAsm { .. }
| StatementKind::Retag { .. }
| StatementKind::Coverage(..)
| StatementKind::Nop => {}
}
}
fn check_terminator(
&mut self,
body: &Body<'tcx>,
term: &Terminator<'tcx>,
term_location: Location,
) {
debug!("check_terminator: {:?}", term);
let tcx = self.tcx();
match term.kind {
TerminatorKind::Goto { .. }
| TerminatorKind::Resume
| TerminatorKind::Abort
| TerminatorKind::Return
| TerminatorKind::GeneratorDrop
| TerminatorKind::Unreachable
| TerminatorKind::Drop { .. }
| TerminatorKind::FalseEdge { .. }
| TerminatorKind::FalseUnwind { .. }
| TerminatorKind::InlineAsm { .. } => {
// no checks needed for these
}
TerminatorKind::DropAndReplace { ref place, ref value, target: _, unwind: _ } => {
let place_ty = place.ty(body, tcx).ty;
let rv_ty = value.ty(body, tcx);
let locations = term_location.to_locations();
if let Err(terr) =
self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
{
span_mirbug!(
self,
term,
"bad DropAndReplace ({:?} = {:?}): {:?}",
place_ty,
rv_ty,
terr
);
}
}
TerminatorKind::SwitchInt { ref discr, switch_ty, .. } => {
let discr_ty = discr.ty(body, tcx);
if let Err(terr) = self.sub_types(
discr_ty,
switch_ty,
term_location.to_locations(),
ConstraintCategory::Assignment,
) {
span_mirbug!(
self,
term,
"bad SwitchInt ({:?} on {:?}): {:?}",
switch_ty,
discr_ty,
terr
);
}
if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
}
// FIXME: check the values
}
TerminatorKind::Call { ref func, ref args, ref destination, from_hir_call, .. } => {
let func_ty = func.ty(body, tcx);
debug!("check_terminator: call, func_ty={:?}", func_ty);
let sig = match func_ty.kind() {
ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
_ => {
span_mirbug!(self, term, "call to non-function {:?}", func_ty);
return;
}
};
let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
term.source_info.span,
LateBoundRegionConversionTime::FnCall,
sig,
);
let sig = self.normalize(sig, term_location);
self.check_call_dest(body, term, &sig, destination, term_location);
self.prove_predicates(
sig.inputs_and_output.iter().map(|ty| ty::PredicateKind::WellFormed(ty.into())),
term_location.to_locations(),
ConstraintCategory::Boring,
);
// The ordinary liveness rules will ensure that all
// regions in the type of the callee are live here. We
// then further constrain the late-bound regions that
// were instantiated at the call site to be live as
// well. The resulting is that all the input (and
// output) types in the signature must be live, since
// all the inputs that fed into it were live.
for &late_bound_region in map.values() {
let region_vid =
self.borrowck_context.universal_regions.to_region_vid(late_bound_region);
self.borrowck_context
.constraints
.liveness_constraints
.add_element(region_vid, term_location);
}
self.check_call_inputs(body, term, &sig, args, term_location, from_hir_call);
}
TerminatorKind::Assert { ref cond, ref msg, .. } => {
let cond_ty = cond.ty(body, tcx);
if cond_ty != tcx.types.bool {
span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
}
if let AssertKind::BoundsCheck { ref len, ref index } = *msg {
if len.ty(body, tcx) != tcx.types.usize {
span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
}
if index.ty(body, tcx) != tcx.types.usize {
span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
}
}
}
TerminatorKind::Yield { ref value, .. } => {
let value_ty = value.ty(body, tcx);
match body.yield_ty() {
None => span_mirbug!(self, term, "yield in non-generator"),
Some(ty) => {
if let Err(terr) = self.sub_types(
value_ty,
ty,
term_location.to_locations(),
ConstraintCategory::Yield,
) {
span_mirbug!(
self,
term,
"type of yield value is {:?}, but the yield type is {:?}: {:?}",
value_ty,
ty,
terr
);
}
}
}
}
}
}
fn check_call_dest(
&mut self,
body: &Body<'tcx>,
term: &Terminator<'tcx>,
sig: &ty::FnSig<'tcx>,
destination: &Option<(Place<'tcx>, BasicBlock)>,
term_location: Location,
) {
let tcx = self.tcx();
match *destination {
Some((ref dest, _target_block)) => {
let dest_ty = dest.ty(body, tcx).ty;
let dest_ty = self.normalize(dest_ty, term_location);
let category = match dest.as_local() {
Some(RETURN_PLACE) => {
if let BorrowCheckContext {
universal_regions:
UniversalRegions { defining_ty: DefiningTy::Const(def_id, _), .. },
..
} = self.borrowck_context
{
if tcx.is_static(*def_id) {
ConstraintCategory::UseAsStatic
} else {
ConstraintCategory::UseAsConst
}
} else {
ConstraintCategory::Return(ReturnConstraint::Normal)
}
}
Some(l) if !body.local_decls[l].is_user_variable() => {
ConstraintCategory::Boring
}
_ => ConstraintCategory::Assignment,
};
let locations = term_location.to_locations();
if let Err(terr) =
self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
{
span_mirbug!(
self,
term,
"call dest mismatch ({:?} <- {:?}): {:?}",
dest_ty,
sig.output(),
terr
);
}
// When `unsized_fn_params` and `unsized_locals` are both not enabled,
// this check is done at `check_local`.
if self.unsized_feature_enabled() {
let span = term.source_info.span;
self.ensure_place_sized(dest_ty, span);
}
}
None => {
if !self
.tcx()
.conservative_is_privately_uninhabited(self.param_env.and(sig.output()))
{
span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
}
}
}
}
fn check_call_inputs(
&mut self,
body: &Body<'tcx>,
term: &Terminator<'tcx>,
sig: &ty::FnSig<'tcx>,
args: &[Operand<'tcx>],
term_location: Location,
from_hir_call: bool,
) {
debug!("check_call_inputs({:?}, {:?})", sig, args);
if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) {
span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
}
for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
let op_arg_ty = op_arg.ty(body, self.tcx());
let op_arg_ty = self.normalize(op_arg_ty, term_location);
let category = if from_hir_call {
ConstraintCategory::CallArgument
} else {
ConstraintCategory::Boring
};
if let Err(terr) =
self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
{
span_mirbug!(
self,
term,
"bad arg #{:?} ({:?} <- {:?}): {:?}",
n,
fn_arg,
op_arg_ty,
terr
);
}
}
}
fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
let is_cleanup = block_data.is_cleanup;
self.last_span = block_data.terminator().source_info.span;
match block_data.terminator().kind {
TerminatorKind::Goto { target } => {
self.assert_iscleanup(body, block_data, target, is_cleanup)
}
TerminatorKind::SwitchInt { ref targets, .. } => {
for target in targets.all_targets() {
self.assert_iscleanup(body, block_data, *target, is_cleanup);
}
}
TerminatorKind::Resume => {
if !is_cleanup {
span_mirbug!(self, block_data, "resume on non-cleanup block!")
}
}
TerminatorKind::Abort => {
if !is_cleanup {
span_mirbug!(self, block_data, "abort on non-cleanup block!")
}
}
TerminatorKind::Return => {
if is_cleanup {
span_mirbug!(self, block_data, "return on cleanup block")
}
}
TerminatorKind::GeneratorDrop { .. } => {
if is_cleanup {
span_mirbug!(self, block_data, "generator_drop in cleanup block")
}
}
TerminatorKind::Yield { resume, drop, .. } => {
if is_cleanup {
span_mirbug!(self, block_data, "yield in cleanup block")
}
self.assert_iscleanup(body, block_data, resume, is_cleanup);
if let Some(drop) = drop {
self.assert_iscleanup(body, block_data, drop, is_cleanup);
}
}
TerminatorKind::Unreachable => {}
TerminatorKind::Drop { target, unwind, .. }
| TerminatorKind::DropAndReplace { target, unwind, .. }
| TerminatorKind::Assert { target, cleanup: unwind, .. } => {
self.assert_iscleanup(body, block_data, target, is_cleanup);
if let Some(unwind) = unwind {
if is_cleanup {
span_mirbug!(self, block_data, "unwind on cleanup block")
}
self.assert_iscleanup(body, block_data, unwind, true);
}
}
TerminatorKind::Call { ref destination, cleanup, .. } => {
if let &Some((_, target)) = destination {
self.assert_iscleanup(body, block_data, target, is_cleanup);
}
if let Some(cleanup) = cleanup {
if is_cleanup {
span_mirbug!(self, block_data, "cleanup on cleanup block")
}
self.assert_iscleanup(body, block_data, cleanup, true);
}
}
TerminatorKind::FalseEdge { real_target, imaginary_target } => {
self.assert_iscleanup(body, block_data, real_target, is_cleanup);
self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
}
TerminatorKind::FalseUnwind { real_target, unwind } => {
self.assert_iscleanup(body, block_data, real_target, is_cleanup);
if let Some(unwind) = unwind {
if is_cleanup {
span_mirbug!(self, block_data, "cleanup in cleanup block via false unwind");
}
self.assert_iscleanup(body, block_data, unwind, true);
}
}
TerminatorKind::InlineAsm { destination, .. } => {
if let Some(target) = destination {
self.assert_iscleanup(body, block_data, target, is_cleanup);
}
}
}
}
fn assert_iscleanup(
&mut self,
body: &Body<'tcx>,
ctxt: &dyn fmt::Debug,
bb: BasicBlock,
iscleanuppad: bool,
) {
if body[bb].is_cleanup != iscleanuppad {
span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad);
}
}
fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
match body.local_kind(local) {
LocalKind::ReturnPointer | LocalKind::Arg => {
// return values of normal functions are required to be
// sized by typeck, but return values of ADT constructors are
// not because we don't include a `Self: Sized` bounds on them.
//
// Unbound parts of arguments were never required to be Sized
// - maybe we should make that a warning.
return;
}
LocalKind::Var | LocalKind::Temp => {}
}
// When `unsized_fn_params` or `unsized_locals` is enabled, only function calls
// and nullary ops are checked in `check_call_dest`.
if !self.unsized_feature_enabled() {
let span = local_decl.source_info.span;
let ty = local_decl.ty;
self.ensure_place_sized(ty, span);
}
}
fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
let tcx = self.tcx();
// Erase the regions from `ty` to get a global type. The
// `Sized` bound in no way depends on precise regions, so this
// shouldn't affect `is_sized`.
let erased_ty = tcx.erase_regions(ty);
if !erased_ty.is_sized(tcx.at(span), self.param_env) {
// in current MIR construction, all non-control-flow rvalue
// expressions evaluate through `as_temp` or `into` a return
// slot or local, so to find all unsized rvalues it is enough
// to check all temps, return slots and locals.
if self.reported_errors.replace((ty, span)).is_none() {
let mut diag = struct_span_err!(
self.tcx().sess,
span,
E0161,
"cannot move a value of type {0}: the size of {0} \
cannot be statically determined",
ty
);
// While this is located in `nll::typeck` this error is not
// an NLL error, it's a required check to prevent creation
// of unsized rvalues in certain cases:
// * operand of a box expression
// * callee in a call expression
diag.emit();
}
}
}
fn aggregate_field_ty(
&mut self,
ak: &AggregateKind<'tcx>,
field_index: usize,
location: Location,
) -> Result<Ty<'tcx>, FieldAccessError> {
let tcx = self.tcx();
match *ak {
AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
let variant = &def.variants[variant_index];
let adj_field_index = active_field_index.unwrap_or(field_index);
if let Some(field) = variant.fields.get(adj_field_index) {
Ok(self.normalize(field.ty(tcx, substs), location))
} else {
Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
}
}
AggregateKind::Closure(_, substs) => {
match substs.as_closure().upvar_tys().nth(field_index) {
Some(ty) => Ok(ty),
None => Err(FieldAccessError::OutOfRange {
field_count: substs.as_closure().upvar_tys().count(),
}),
}
}
AggregateKind::Generator(_, substs, _) => {
// It doesn't make sense to look at a field beyond the prefix;
// these require a variant index, and are not initialized in
// aggregate rvalues.
match substs.as_generator().prefix_tys().nth(field_index) {
Some(ty) => Ok(ty),
None => Err(FieldAccessError::OutOfRange {
field_count: substs.as_generator().prefix_tys().count(),
}),
}
}
AggregateKind::Array(ty) => Ok(ty),
AggregateKind::Tuple => {
unreachable!("This should have been covered in check_rvalues");
}
}
}
fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
let tcx = self.tcx();
match rvalue {
Rvalue::Aggregate(ak, ops) => {
self.check_aggregate_rvalue(&body, rvalue, ak, ops, location)
}
Rvalue::Repeat(operand, len) => {
// If the length cannot be evaluated we must assume that the length can be larger
// than 1.
// If the length is larger than 1, the repeat expression will need to copy the
// element, so we require the `Copy` trait.
if len.try_eval_usize(tcx, self.param_env).map_or(true, |len| len > 1) {
match operand {
Operand::Copy(..) | Operand::Constant(..) => {
// These are always okay: direct use of a const, or a value that can evidently be copied.
}
Operand::Move(place) => {
// Make sure that repeated elements implement `Copy`.
let span = body.source_info(location).span;
let ty = operand.ty(body, tcx);
if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) {
let ccx = ConstCx::new_with_param_env(tcx, body, self.param_env);
let is_const_fn =
is_const_fn_in_array_repeat_expression(&ccx, &place, &body);
debug!("check_rvalue: is_const_fn={:?}", is_const_fn);
let def_id = body.source.def_id().expect_local();
self.infcx.report_selection_error(
&traits::Obligation::new(
ObligationCause::new(
span,
self.tcx().hir().local_def_id_to_hir_id(def_id),
traits::ObligationCauseCode::RepeatVec(is_const_fn),
),
self.param_env,
ty::Binder::bind(ty::TraitRef::new(
self.tcx().require_lang_item(
LangItem::Copy,
Some(self.last_span),
),
tcx.mk_substs_trait(ty, &[]),
))
.without_const()
.to_predicate(self.tcx()),
),
&traits::SelectionError::Unimplemented,
false,
false,
);
}
}
}
}
}
Rvalue::NullaryOp(_, ty) => {
// Even with unsized locals cannot box an unsized value.
if self.unsized_feature_enabled() {
let span = body.source_info(location).span;
self.ensure_place_sized(ty, span);
}
let trait_ref = ty::TraitRef {
def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)),
substs: tcx.mk_substs_trait(ty, &[]),
};
self.prove_trait_ref(
trait_ref,
location.to_locations(),
ConstraintCategory::SizedBound,
);
}
Rvalue::Cast(cast_kind, op, ty) => {
match cast_kind {
CastKind::Pointer(PointerCast::ReifyFnPointer) => {
let fn_sig = op.ty(body, tcx).fn_sig(tcx);
// The type that we see in the fcx is like
// `foo::<'a, 'b>`, where `foo` is the path to a
// function definition. When we extract the
// signature, it comes from the `fn_sig` query,
// and hence may contain unnormalized results.
let fn_sig = self.normalize(fn_sig, location);
let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
if let Err(terr) = self.eq_types(
ty_fn_ptr_from,
ty,
location.to_locations(),
ConstraintCategory::Cast,
) {
span_mirbug!(
self,
rvalue,
"equating {:?} with {:?} yields {:?}",
ty_fn_ptr_from,
ty,
terr
);
}
}
CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
let sig = match op.ty(body, tcx).kind() {
ty::Closure(_, substs) => substs.as_closure().sig(),
_ => bug!(),
};
let ty_fn_ptr_from = tcx.mk_fn_ptr(tcx.signature_unclosure(sig, *unsafety));
if let Err(terr) = self.eq_types(
ty_fn_ptr_from,
ty,
location.to_locations(),
ConstraintCategory::Cast,
) {
span_mirbug!(
self,
rvalue,
"equating {:?} with {:?} yields {:?}",
ty_fn_ptr_from,
ty,
terr
);
}
}
CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
let fn_sig = op.ty(body, tcx).fn_sig(tcx);
// The type that we see in the fcx is like
// `foo::<'a, 'b>`, where `foo` is the path to a
// function definition. When we extract the
// signature, it comes from the `fn_sig` query,
// and hence may contain unnormalized results.
let fn_sig = self.normalize(fn_sig, location);
let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
if let Err(terr) = self.eq_types(
ty_fn_ptr_from,
ty,
location.to_locations(),
ConstraintCategory::Cast,
) {
span_mirbug!(
self,
rvalue,
"equating {:?} with {:?} yields {:?}",
ty_fn_ptr_from,
ty,
terr
);
}
}
CastKind::Pointer(PointerCast::Unsize) => {
let &ty = ty;
let trait_ref = ty::TraitRef {
def_id: tcx
.require_lang_item(LangItem::CoerceUnsized, Some(self.last_span)),
substs: tcx.mk_substs_trait(op.ty(body, tcx), &[ty.into()]),
};
self.prove_trait_ref(
trait_ref,
location.to_locations(),
ConstraintCategory::Cast,
);
}
CastKind::Pointer(PointerCast::MutToConstPointer) => {
let ty_from = match op.ty(body, tcx).kind() {
ty::RawPtr(ty::TypeAndMut {
ty: ty_from,
mutbl: hir::Mutability::Mut,
}) => ty_from,
_ => {
span_mirbug!(
self,
rvalue,
"unexpected base type for cast {:?}",
ty,
);
return;
}
};
let ty_to = match ty.kind() {
ty::RawPtr(ty::TypeAndMut {
ty: ty_to,
mutbl: hir::Mutability::Not,
}) => ty_to,
_ => {
span_mirbug!(
self,
rvalue,
"unexpected target type for cast {:?}",
ty,
);
return;
}
};
if let Err(terr) = self.sub_types(
ty_from,
ty_to,
location.to_locations(),
ConstraintCategory::Cast,
) {
span_mirbug!(
self,
rvalue,
"relating {:?} with {:?} yields {:?}",
ty_from,
ty_to,
terr
);
}
}
CastKind::Pointer(PointerCast::ArrayToPointer) => {
let ty_from = op.ty(body, tcx);
let opt_ty_elem_mut = match ty_from.kind() {
ty::RawPtr(ty::TypeAndMut { mutbl: array_mut, ty: array_ty }) => {
match array_ty.kind() {
ty::Array(ty_elem, _) => Some((ty_elem, *array_mut)),
_ => None,
}
}
_ => None,
};
let (ty_elem, ty_mut) = match opt_ty_elem_mut {
Some(ty_elem_mut) => ty_elem_mut,
None => {
span_mirbug!(
self,
rvalue,
"ArrayToPointer cast from unexpected type {:?}",
ty_from,
);
return;
}
};
let (ty_to, ty_to_mut) = match ty.kind() {
ty::RawPtr(ty::TypeAndMut { mutbl: ty_to_mut, ty: ty_to }) => {
(ty_to, *ty_to_mut)
}
_ => {
span_mirbug!(
self,
rvalue,
"ArrayToPointer cast to unexpected type {:?}",
ty,
);
return;
}
};
if ty_to_mut == Mutability::Mut && ty_mut == Mutability::Not {
span_mirbug!(
self,
rvalue,
"ArrayToPointer cast from const {:?} to mut {:?}",
ty,
ty_to
);
return;
}
if let Err(terr) = self.sub_types(
ty_elem,
ty_to,
location.to_locations(),
ConstraintCategory::Cast,
) {
span_mirbug!(
self,
rvalue,
"relating {:?} with {:?} yields {:?}",
ty_elem,
ty_to,
terr
)
}
}
CastKind::Misc => {
let ty_from = op.ty(body, tcx);
let cast_ty_from = CastTy::from_ty(ty_from);
let cast_ty_to = CastTy::from_ty(ty);
match (cast_ty_from, cast_ty_to) {
(None, _)
| (_, None | Some(CastTy::FnPtr))
| (Some(CastTy::Float), Some(CastTy::Ptr(_)))
| (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Float)) => {
span_mirbug!(self, rvalue, "Invalid cast {:?} -> {:?}", ty_from, ty,)
}
(
Some(CastTy::Int(_)),
Some(CastTy::Int(_) | CastTy::Float | CastTy::Ptr(_)),
)
| (Some(CastTy::Float), Some(CastTy::Int(_) | CastTy::Float))
| (Some(CastTy::Ptr(_)), Some(CastTy::Int(_) | CastTy::Ptr(_)))
| (Some(CastTy::FnPtr), Some(CastTy::Int(_) | CastTy::Ptr(_))) => (),
}
}
}
}
Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
self.add_reborrow_constraint(&body, location, region, borrowed_place);
}
Rvalue::BinaryOp(
BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge,
box (left, right),
) => {
let ty_left = left.ty(body, tcx);
match ty_left.kind() {
// Types with regions are comparable if they have a common super-type.
ty::RawPtr(_) | ty::FnPtr(_) => {
let ty_right = right.ty(body, tcx);
let common_ty = self.infcx.next_ty_var(TypeVariableOrigin {
kind: TypeVariableOriginKind::MiscVariable,
span: body.source_info(location).span,
});
self.relate_types(
common_ty,
ty::Variance::Contravariant,
ty_left,
location.to_locations(),
ConstraintCategory::Boring,
)
.unwrap_or_else(|err| {
bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
});
if let Err(terr) = self.relate_types(
common_ty,
ty::Variance::Contravariant,
ty_right,
location.to_locations(),
ConstraintCategory::Boring,
) {
span_mirbug!(
self,
rvalue,
"unexpected comparison types {:?} and {:?} yields {:?}",
ty_left,
ty_right,
terr
)
}
}
// For types with no regions we can just check that the
// both operands have the same type.
ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_)
if ty_left == right.ty(body, tcx) => {}
// Other types are compared by trait methods, not by
// `Rvalue::BinaryOp`.
_ => span_mirbug!(
self,
rvalue,
"unexpected comparison types {:?} and {:?}",
ty_left,
right.ty(body, tcx)
),
}
}
Rvalue::AddressOf(..)
| Rvalue::ThreadLocalRef(..)
| Rvalue::Use(..)
| Rvalue::Len(..)
| Rvalue::BinaryOp(..)
| Rvalue::CheckedBinaryOp(..)
| Rvalue::UnaryOp(..)
| Rvalue::Discriminant(..) => {}
}
}
/// If this rvalue supports a user-given type annotation, then
/// extract and return it. This represents the final type of the
/// rvalue and will be unified with the inferred type.
fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
match rvalue {
Rvalue::Use(_)
| Rvalue::ThreadLocalRef(_)
| Rvalue::Repeat(..)
| Rvalue::Ref(..)
| Rvalue::AddressOf(..)
| Rvalue::Len(..)
| Rvalue::Cast(..)
| Rvalue::BinaryOp(..)
| Rvalue::CheckedBinaryOp(..)
| Rvalue::NullaryOp(..)
| Rvalue::UnaryOp(..)
| Rvalue::Discriminant(..) => None,
Rvalue::Aggregate(aggregate, _) => match **aggregate {
AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
AggregateKind::Array(_) => None,
AggregateKind::Tuple => None,
AggregateKind::Closure(_, _) => None,
AggregateKind::Generator(_, _, _) => None,
},
}
}
fn check_aggregate_rvalue(
&mut self,
body: &Body<'tcx>,
rvalue: &Rvalue<'tcx>,
aggregate_kind: &AggregateKind<'tcx>,
operands: &[Operand<'tcx>],
location: Location,
) {
let tcx = self.tcx();
self.prove_aggregate_predicates(aggregate_kind, location);
if *aggregate_kind == AggregateKind::Tuple {
// tuple rvalue field type is always the type of the op. Nothing to check here.
return;
}
for (i, operand) in operands.iter().enumerate() {
let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
Ok(field_ty) => field_ty,
Err(FieldAccessError::OutOfRange { field_count }) => {
span_mirbug!(
self,
rvalue,
"accessed field #{} but variant only has {}",
i,
field_count
);
continue;
}
};
let operand_ty = operand.ty(body, tcx);
let operand_ty = self.normalize(operand_ty, location);
if let Err(terr) = self.sub_types(
operand_ty,
field_ty,
location.to_locations(),
ConstraintCategory::Boring,
) {
span_mirbug!(
self,
rvalue,
"{:?} is not a subtype of {:?}: {:?}",
operand_ty,
field_ty,
terr
);
}
}
}
/// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
///
/// # Parameters
///
/// - `location`: the location `L` where the borrow expression occurs
/// - `borrow_region`: the region `'a` associated with the borrow
/// - `borrowed_place`: the place `P` being borrowed
fn add_reborrow_constraint(
&mut self,
body: &Body<'tcx>,
location: Location,
borrow_region: ty::Region<'tcx>,
borrowed_place: &Place<'tcx>,
) {
// These constraints are only meaningful during borrowck:
let BorrowCheckContext { borrow_set, location_table, all_facts, constraints, .. } =
self.borrowck_context;
// In Polonius mode, we also push a `borrow_region` fact
// linking the loan to the region (in some cases, though,
// there is no loan associated with this borrow expression --
// that occurs when we are borrowing an unsafe place, for
// example).
if let Some(all_facts) = all_facts {
let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation");
if let Some(borrow_index) = borrow_set.get_index_of(&location) {
let region_vid = borrow_region.to_region_vid();
all_facts.borrow_region.push((
region_vid,
borrow_index,
location_table.mid_index(location),
));
}
}
// If we are reborrowing the referent of another reference, we
// need to add outlives relationships. In a case like `&mut
// *p`, where the `p` has type `&'b mut Foo`, for example, we
// need to ensure that `'b: 'a`.
debug!(
"add_reborrow_constraint({:?}, {:?}, {:?})",
location, borrow_region, borrowed_place
);
let mut cursor = borrowed_place.projection.as_ref();
let tcx = self.infcx.tcx;
let field = path_utils::is_upvar_field_projection(
tcx,
&self.borrowck_context.upvars,
borrowed_place.as_ref(),
body,
);
let category = if let Some(field) = field {
let var_hir_id = self.borrowck_context.upvars[field.index()].place.get_root_variable();
// FIXME(project-rfc-2229#8): Use Place for better diagnostics
ConstraintCategory::ClosureUpvar(var_hir_id)
} else {
ConstraintCategory::Boring
};
while let [proj_base @ .., elem] = cursor {
cursor = proj_base;
debug!("add_reborrow_constraint - iteration {:?}", elem);
match elem {
ProjectionElem::Deref => {
let base_ty = Place::ty_from(borrowed_place.local, proj_base, body, tcx).ty;
debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
match base_ty.kind() {
ty::Ref(ref_region, _, mutbl) => {
constraints.outlives_constraints.push(OutlivesConstraint {
sup: ref_region.to_region_vid(),
sub: borrow_region.to_region_vid(),
locations: location.to_locations(),
category,
});
match mutbl {
hir::Mutability::Not => {
// Immutable reference. We don't need the base
// to be valid for the entire lifetime of
// the borrow.
break;
}
hir::Mutability::Mut => {
// Mutable reference. We *do* need the base
// to be valid, because after the base becomes
// invalid, someone else can use our mutable deref.
// This is in order to make the following function
// illegal:
// ```
// fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
// &mut *x
// }
// ```
//
// As otherwise you could clone `&mut T` using the
// following function:
// ```
// fn bad(x: &mut T) -> (&mut T, &mut T) {
// let my_clone = unsafe_deref(&'a x);
// ENDREGION 'a;
// (my_clone, x)
// }
// ```
}
}
}
ty::RawPtr(..) => {
// deref of raw pointer, guaranteed to be valid
break;
}
ty::Adt(def, _) if def.is_box() => {
// deref of `Box`, need the base to be valid - propagate
}
_ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
}
}
ProjectionElem::Field(..)
| ProjectionElem::Downcast(..)
| ProjectionElem::Index(..)
| ProjectionElem::ConstantIndex { .. }
| ProjectionElem::Subslice { .. } => {
// other field access
}
}
}
}
fn prove_aggregate_predicates(
&mut self,
aggregate_kind: &AggregateKind<'tcx>,
location: Location,
) {
let tcx = self.tcx();
debug!(
"prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
aggregate_kind, location
);
let instantiated_predicates = match aggregate_kind {
AggregateKind::Adt(def, _, substs, _, _) => {
tcx.predicates_of(def.did).instantiate(tcx, substs)
}
// For closures, we have some **extra requirements** we
//
// have to check. In particular, in their upvars and
// signatures, closures often reference various regions
// from the surrounding function -- we call those the
// closure's free regions. When we borrow-check (and hence
// region-check) closures, we may find that the closure
// requires certain relationships between those free
// regions. However, because those free regions refer to
// portions of the CFG of their caller, the closure is not
// in a position to verify those relationships. In that
// case, the requirements get "propagated" to us, and so
// we have to solve them here where we instantiate the
// closure.
//
// Despite the opacity of the previous parapgrah, this is
// actually relatively easy to understand in terms of the
// desugaring. A closure gets desugared to a struct, and
// these extra requirements are basically like where
// clauses on the struct.
AggregateKind::Closure(def_id, substs)
| AggregateKind::Generator(def_id, substs, _) => {
self.prove_closure_bounds(tcx, def_id.expect_local(), substs, location)
}
AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
};
self.normalize_and_prove_instantiated_predicates(
instantiated_predicates,
location.to_locations(),
);
}
fn prove_closure_bounds(
&mut self,
tcx: TyCtxt<'tcx>,
def_id: LocalDefId,
substs: SubstsRef<'tcx>,
location: Location,
) -> ty::InstantiatedPredicates<'tcx> {
if let Some(ref closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements
{
let closure_constraints = QueryRegionConstraints {
outlives: closure_region_requirements.apply_requirements(
tcx,
def_id.to_def_id(),
substs,
),
// Presently, closures never propagate member
// constraints to their parents -- they are enforced
// locally. This is largely a non-issue as member
// constraints only come from `-> impl Trait` and
// friends which don't appear (thus far...) in
// closures.
member_constraints: vec![],
};
let bounds_mapping = closure_constraints
.outlives
.iter()
.enumerate()
.filter_map(|(idx, constraint)| {
let ty::OutlivesPredicate(k1, r2) =
constraint.no_bound_vars().unwrap_or_else(|| {
bug!("query_constraint {:?} contained bound vars", constraint,);
});
match k1.unpack() {
GenericArgKind::Lifetime(r1) => {
// constraint is r1: r2
let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1);
let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2);
let outlives_requirements =
&closure_region_requirements.outlives_requirements[idx];
Some((
(r1_vid, r2_vid),
(outlives_requirements.category, outlives_requirements.blame_span),
))
}
GenericArgKind::Type(_) | GenericArgKind::Const(_) => None,
}
})
.collect();
let existing = self
.borrowck_context
.constraints
.closure_bounds_mapping
.insert(location, bounds_mapping);
assert!(existing.is_none(), "Multiple closures at the same location.");
self.push_region_constraints(
location.to_locations(),
ConstraintCategory::ClosureBounds,
&closure_constraints,
);
}
tcx.predicates_of(def_id).instantiate(tcx, substs)
}
fn prove_trait_ref(
&mut self,
trait_ref: ty::TraitRef<'tcx>,
locations: Locations,
category: ConstraintCategory,
) {
self.prove_predicates(
Some(ty::PredicateKind::Trait(
ty::TraitPredicate { trait_ref },
hir::Constness::NotConst,
)),
locations,
category,
);
}
fn normalize_and_prove_instantiated_predicates(
&mut self,
instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
locations: Locations,
) {
for predicate in instantiated_predicates.predicates {
let predicate = self.normalize(predicate, locations);
self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
}
}
fn prove_predicates(
&mut self,
predicates: impl IntoIterator<Item = impl ToPredicate<'tcx>>,
locations: Locations,
category: ConstraintCategory,
) {
for predicate in predicates {
let predicate = predicate.to_predicate(self.tcx());
debug!("prove_predicates(predicate={:?}, locations={:?})", predicate, locations,);
self.prove_predicate(predicate, locations, category);
}
}
fn prove_predicate(
&mut self,
predicate: ty::Predicate<'tcx>,
locations: Locations,
category: ConstraintCategory,
) {
debug!("prove_predicate(predicate={:?}, location={:?})", predicate, locations,);
let param_env = self.param_env;
self.fully_perform_op(
locations,
category,
param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
)
.unwrap_or_else(|NoSolution| {
span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
})
}
fn typeck_mir(&mut self, body: &Body<'tcx>) {
self.last_span = body.span;
debug!("run_on_mir: {:?}", body.span);
for (local, local_decl) in body.local_decls.iter_enumerated() {
self.check_local(&body, local, local_decl);
}
for (block, block_data) in body.basic_blocks().iter_enumerated() {
let mut location = Location { block, statement_index: 0 };
for stmt in &block_data.statements {
if !stmt.source_info.span.is_dummy() {
self.last_span = stmt.source_info.span;
}
self.check_stmt(body, stmt, location);
location.statement_index += 1;
}
self.check_terminator(&body, block_data.terminator(), location);
self.check_iscleanup(&body, block_data);
}
}
fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
where
T: type_op::normalize::Normalizable<'tcx> + Copy + 'tcx,
{
debug!("normalize(value={:?}, location={:?})", value, location);
let param_env = self.param_env;
self.fully_perform_op(
location.to_locations(),
ConstraintCategory::Boring,
param_env.and(type_op::normalize::Normalize::new(value)),
)
.unwrap_or_else(|NoSolution| {
span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
value
})
}
}
trait NormalizeLocation: fmt::Debug + Copy {
fn to_locations(self) -> Locations;
}
impl NormalizeLocation for Locations {
fn to_locations(self) -> Locations {
self
}
}
impl NormalizeLocation for Location {
fn to_locations(self) -> Locations {
Locations::Single(self)
}
}
#[derive(Debug, Default)]
struct ObligationAccumulator<'tcx> {
obligations: PredicateObligations<'tcx>,
}
impl<'tcx> ObligationAccumulator<'tcx> {
fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
let InferOk { value, obligations } = value;
self.obligations.extend(obligations);
value
}
fn into_vec(self) -> PredicateObligations<'tcx> {
self.obligations
}
}
| 40.81895 | 117 | 0.471209 |
8a38729ed6b76c8d4e3bf4978a071db0d0a90978 | 424 | use super::ValueTrait;
use crate::error::FendError;
impl ValueTrait for bool {
fn type_name(&self) -> &'static str {
"bool"
}
fn format(&self, _indent: usize, spans: &mut Vec<crate::Span>) {
spans.push(crate::Span {
string: self.to_string(),
kind: crate::SpanKind::Boolean,
});
}
fn as_bool(&self) -> Result<bool, FendError> {
Ok(*self)
}
}
| 21.2 | 68 | 0.54717 |
5dc0d439e9e20212f4b91696b7dd577762c23801 | 84,647 | /// Configures what level the product should be uploaded with regards to
/// how users will be send events and how predictions will be made.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ProductLevelConfig {
/// The level of a [Catalog][google.cloud.retail.v2.Catalog] at which the
/// [UserEvent][google.cloud.retail.v2.UserEvent]s are uploaded. Acceptable
/// values are:
/// * `primary`
/// * `variant`
///
/// If this field is set to an invalid value other than these, an
/// INVALID_ARGUMENT error is returned.
///
/// If this field is `primary` and
/// [predict_product_level][google.cloud.retail.v2.ProductLevelConfig.predict_product_level]
/// is `variant`, an INVALID_ARGUMENT error is returned.
///
/// See
/// https://cloud.google.com/recommendations-ai/docs/catalog#catalog-levels
/// for more details.
#[prost(string, tag = "1")]
pub event_product_level: std::string::String,
/// The level of a [Catalog][google.cloud.retail.v2.Catalog] at which the
/// [PredictionService.Predict][google.cloud.retail.v2.PredictionService.Predict]
/// is called. Acceptable values are:
/// * `primary`
/// * `variant`
///
/// If this field is set to an invalid value other than these, an
/// INVALID_ARGUMENT error is returned.
///
/// If this field is `variant` and
/// [event_product_level][google.cloud.retail.v2.ProductLevelConfig.event_product_level]
/// is `primary`, an INVALID_ARGUMENT error is returned.
///
/// See
/// https://cloud.google.com/recommendations-ai/docs/catalog#catalog-levels
/// for more details.
#[prost(string, tag = "2")]
pub predict_product_level: std::string::String,
}
/// The catalog configuration.
/// Next ID: 5.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Catalog {
/// Required. Immutable. The fully qualified resource name of the catalog.
#[prost(string, tag = "1")]
pub name: std::string::String,
/// Required. Immutable. The catalog display name.
///
/// This field must be a UTF-8 encoded string with a length limit of 128 bytes.
/// Otherwise, an INVALID_ARGUMENT error is returned.
#[prost(string, tag = "2")]
pub display_name: std::string::String,
/// Required. The product level configuration.
#[prost(message, optional, tag = "4")]
pub product_level_config: ::std::option::Option<ProductLevelConfig>,
}
/// Request for
/// [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs]
/// method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ListCatalogsRequest {
/// Required. The account resource name with an associated location.
///
/// If the caller does not have permission to list
/// [Catalog][google.cloud.retail.v2.Catalog]s under this location, regardless
/// of whether or not this location exists, a PERMISSION_DENIED error is
/// returned.
#[prost(string, tag = "1")]
pub parent: std::string::String,
/// Maximum number of [Catalog][google.cloud.retail.v2.Catalog]s to return. If
/// unspecified, defaults to 50. The maximum allowed value is 1000. Values
/// above 1000 will be coerced to 1000.
///
/// If this field is negative, an INVALID_ARGUMENT is returned.
#[prost(int32, tag = "2")]
pub page_size: i32,
/// A page token
/// [ListCatalogsResponse.next_page_token][google.cloud.retail.v2.ListCatalogsResponse.next_page_token],
/// received from a previous
/// [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs]
/// call. Provide this to retrieve the subsequent page.
///
/// When paginating, all other parameters provided to
/// [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs]
/// must match the call that provided the page token. Otherwise, an
/// INVALID_ARGUMENT error is returned.
#[prost(string, tag = "3")]
pub page_token: std::string::String,
}
/// Response for
/// [CatalogService.ListCatalogs][google.cloud.retail.v2.CatalogService.ListCatalogs]
/// method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ListCatalogsResponse {
/// All the customer's [Catalog][google.cloud.retail.v2.Catalog]s.
#[prost(message, repeated, tag = "1")]
pub catalogs: ::std::vec::Vec<Catalog>,
/// A token that can be sent as
/// [ListCatalogsRequest.page_token][google.cloud.retail.v2.ListCatalogsRequest.page_token]
/// to retrieve the next page. If this field is omitted, there are no
/// subsequent pages.
#[prost(string, tag = "2")]
pub next_page_token: std::string::String,
}
/// Request for
/// [CatalogService.UpdateCatalog][google.cloud.retail.v2.CatalogService.UpdateCatalog]
/// method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct UpdateCatalogRequest {
/// Required. The [Catalog][google.cloud.retail.v2.Catalog] to update.
///
/// If the caller does not have permission to update the
/// [Catalog][google.cloud.retail.v2.Catalog], regardless of whether or not it
/// exists, a PERMISSION_DENIED error is returned.
///
/// If the [Catalog][google.cloud.retail.v2.Catalog] to update does not exist,
/// a NOT_FOUND error is returned.
#[prost(message, optional, tag = "1")]
pub catalog: ::std::option::Option<Catalog>,
/// Indicates which fields in the provided
/// [Catalog][google.cloud.retail.v2.Catalog] to update. If not set, will only
/// update the
/// [Catalog.product_level_config][google.cloud.retail.v2.Catalog.product_level_config]
/// field, which is also the only currently supported field to update.
///
/// If an unsupported or unknown field is provided, an INVALID_ARGUMENT error
/// is returned.
#[prost(message, optional, tag = "2")]
pub update_mask: ::std::option::Option<::prost_types::FieldMask>,
}
#[doc = r" Generated client implementations."]
pub mod catalog_service_client {
#![allow(unused_variables, dead_code, missing_docs)]
use tonic::codegen::*;
#[doc = " Service for managing catalog configuration."]
pub struct CatalogServiceClient<T> {
inner: tonic::client::Grpc<T>,
}
impl<T> CatalogServiceClient<T>
where
T: tonic::client::GrpcService<tonic::body::BoxBody>,
T::ResponseBody: Body + HttpBody + Send + 'static,
T::Error: Into<StdError>,
<T::ResponseBody as HttpBody>::Error: Into<StdError> + Send,
{
pub fn new(inner: T) -> Self {
let inner = tonic::client::Grpc::new(inner);
Self { inner }
}
pub fn with_interceptor(inner: T, interceptor: impl Into<tonic::Interceptor>) -> Self {
let inner = tonic::client::Grpc::with_interceptor(inner, interceptor);
Self { inner }
}
#[doc = " Lists all the [Catalog][google.cloud.retail.v2.Catalog]s associated with"]
#[doc = " the project."]
pub async fn list_catalogs(
&mut self,
request: impl tonic::IntoRequest<super::ListCatalogsRequest>,
) -> Result<tonic::Response<super::ListCatalogsResponse>, tonic::Status> {
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/google.cloud.retail.v2.CatalogService/ListCatalogs",
);
self.inner.unary(request.into_request(), path, codec).await
}
#[doc = " Updates the [Catalog][google.cloud.retail.v2.Catalog]s."]
pub async fn update_catalog(
&mut self,
request: impl tonic::IntoRequest<super::UpdateCatalogRequest>,
) -> Result<tonic::Response<super::Catalog>, tonic::Status> {
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/google.cloud.retail.v2.CatalogService/UpdateCatalog",
);
self.inner.unary(request.into_request(), path, codec).await
}
}
impl<T: Clone> Clone for CatalogServiceClient<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
impl<T> std::fmt::Debug for CatalogServiceClient<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "CatalogServiceClient {{ ... }}")
}
}
}
/// A custom attribute that is not explicitly modeled in
/// [Product][google.cloud.retail.v2.Product]].
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CustomAttribute {
/// The textual values of this custom attribute. For example, `["yellow",
/// "green"]` when the key is "color".
///
/// At most 400 values are allowed. Empty values are not allowed. Each value
/// must be a UTF-8 encoded string with a length limit of 256 bytes. Otherwise,
/// an INVALID_ARGUMENT error is returned.
///
/// Exactly one of [text][google.cloud.retail.v2.CustomAttribute.text] or
/// [numbers][google.cloud.retail.v2.CustomAttribute.numbers] should be set.
/// Otherwise, a FAILED_PRECONDITION error is returned.
#[prost(string, repeated, tag = "1")]
pub text: ::std::vec::Vec<std::string::String>,
/// The numerical values of this custom attribute. For example, `[2.3, 15.4]`
/// when the key is "lengths_cm".
///
/// At most 400 values are allowed.Otherwise, an INVALID_ARGUMENT error is
/// returned.
///
/// Exactly one of [text][google.cloud.retail.v2.CustomAttribute.text] or
/// [numbers][google.cloud.retail.v2.CustomAttribute.numbers] should be set.
/// Otherwise, a FAILED_PRECONDITION error is returned.
#[prost(double, repeated, tag = "2")]
pub numbers: ::std::vec::Vec<f64>,
}
/// [Product][google.cloud.retail.v2.Product] thumbnail/detail image.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Image {
/// Required. URI of the image.
///
/// This field must be a valid UTF-8 encoded URI with a length limit of 5 KiB.
/// Otherwise, an INVALID_ARGUMENT error is returned.
///
/// Google Merchant Center property
/// [image_link](https://support.google.com/merchants/answer/6324350).
/// Schema.org property [Product.image](http://schema.org/image).
#[prost(string, tag = "1")]
pub uri: std::string::String,
/// Height of the image in number of pixels.
///
/// This field must be nonnegative. Otherwise, an INVALID_ARGUMENT error is
/// returned.
#[prost(int32, tag = "2")]
pub height: i32,
/// Width of the image in number of pixels.
///
/// This field must be nonnegative. Otherwise, an INVALID_ARGUMENT error is
/// returned.
#[prost(int32, tag = "3")]
pub width: i32,
}
/// The price information of a [Product][google.cloud.retail.v2.Product].
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PriceInfo {
/// The 3-letter currency code defined in [ISO
/// 4217][https://www.iso.org/iso-4217-currency-codes.html].
///
/// If this field is an unrecognizable currency code, an INVALID_ARGUMENT
/// error is returned.
#[prost(string, tag = "1")]
pub currency_code: std::string::String,
/// Price of the product.
///
/// Google Merchant Center property
/// [price](https://support.google.com/merchants/answer/6324371).
/// Schema.org property
/// [Offer.priceSpecification](https://schema.org/priceSpecification).
#[prost(float, tag = "2")]
pub price: f32,
/// Price of the product without any discount. If zero, by default set to be
/// the [price][google.cloud.retail.v2.PriceInfo.price].
#[prost(float, tag = "3")]
pub original_price: f32,
/// The costs associated with the sale of a particular product. Used for gross
/// profit reporting.
///
/// * Profit = [price][google.cloud.retail.v2.PriceInfo.price] -
/// [cost][google.cloud.retail.v2.PriceInfo.cost]
///
/// Google Merchant Center property
/// [cost_of_goods_sold](https://support.google.com/merchants/answer/9017895)
#[prost(float, tag = "4")]
pub cost: f32,
}
/// Information of an end user.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct UserInfo {
/// Highly recommended for logged-in users. Unique identifier for logged-in
/// user, such as a user name.
///
/// The field must be a UTF-8 encoded string with a length limit of 128 bytes.
/// Otherwise, an INVALID_ARGUMENT error is returned.
#[prost(string, tag = "1")]
pub user_id: std::string::String,
/// The end user's IP address. This field is used to extract location
/// information for personalization.
///
/// This field must be either an IPv4 address (e.g. "104.133.9.80") or an IPv6
/// address (e.g. "2001:0db8:85a3:0000:0000:8a2e:0370:7334"). Otherwise, an
/// INVALID_ARGUMENT error is returned.
///
/// This should not be set when using the JavaScript tag in
/// [UserEventService.CollectUserEvent][google.cloud.retail.v2.UserEventService.CollectUserEvent]
/// or if
/// [direct_user_request][google.cloud.retail.v2.UserInfo.direct_user_request]
/// is set. Otherwise, a FAILED_PRECONDITION error is returned.
#[prost(string, tag = "2")]
pub ip_address: std::string::String,
/// User agent as included in the HTTP header.
///
/// The field must be a UTF-8 encoded string with a length limit of 1 KiB.
/// Otherwise, an INVALID_ARGUMENT error is returned.
///
/// This should not be set when using the client side event reporting with
/// GTM or JavaScript tag in
/// [UserEventService.CollectUserEvent][google.cloud.retail.v2.UserEventService.CollectUserEvent]
/// or if
/// [direct_user_request][google.cloud.retail.v2.UserInfo.direct_user_request]
/// is set. Otherwise, a FAILED_PRECONDITION error is returned.
#[prost(string, tag = "3")]
pub user_agent: std::string::String,
/// True if the request is made directly from the end user, in which case the
/// [ip_address][google.cloud.retail.v2.UserInfo.ip_address] and
/// [user_agent][google.cloud.retail.v2.UserInfo.user_agent] can be populated
/// from the HTTP request. This flag should be set only if the API request is
/// made directly from the end user such as a mobile app (and not if a gateway
/// or a server is processing and pushing the user events).
///
/// This should not be set when using the JavaScript tag in
/// [UserEventService.CollectUserEvent][google.cloud.retail.v2.UserEventService.CollectUserEvent].
/// Otherwise, a FAILED_PRECONDITION error is returned.
#[prost(bool, tag = "4")]
pub direct_user_request: bool,
}
/// Product captures all metadata information of items to be recommended or
/// searched.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Product {
/// Immutable. Full resource name of the product, such as
///
/// "projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/product_id".
///
/// The branch ID must be "default_branch".
#[prost(string, tag = "1")]
pub name: std::string::String,
/// Immutable. [Product][google.cloud.retail.v2.Product] identifier, which is
/// the final component of [name][google.cloud.retail.v2.Product.name]. For
/// example, this field is "id_1", if
/// [name][google.cloud.retail.v2.Product.name] is
///
/// "projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1".
///
/// This field must be a UTF-8 encoded string with a length limit of 128 bytes.
/// Otherwise, an INVALID_ARGUMENT error is returned.
///
/// Google Merchant Center property
/// [id](https://support.google.com/merchants/answer/6324405).
/// schema.org Property [Product.sku](https://schema.org/sku).
#[prost(string, tag = "2")]
pub id: std::string::String,
/// Variant group identifier. Must be an
/// [id][google.cloud.retail.v2.Product.id], with the same parent branch with
/// this product. Otherwise, an error is thrown.
///
/// The primary product may be empty during the creation, but cannot be updated
/// from a non-empty string to an empty one. Otherwise an INVALID_ARGUMENT
/// error is returned.
///
/// Should only be set for [Type.VARIANT][]
/// [Product][google.cloud.retail.v2.Product]s. A maximum of 1000 products are
/// allowed to share the same [Type.PRIMARY][]
/// [Product][google.cloud.retail.v2.Product]. Otherwise, an INVALID_ARGUMENT
/// error is returned.
///
/// Google Merchant Center Property
/// [item_group_id](https://support.google.com/merchants/answer/6324507).
/// schema.org Property
/// [Product.inProductGroupWithID](https://schema.org/inProductGroupWithID).
///
/// This field must be enabled before it can be used. [Learn
/// more](/recommendations-ai/docs/catalog#item-group-id).
#[prost(string, tag = "4")]
pub primary_product_id: std::string::String,
/// Required. Product categories. This field is repeated for supporting one
/// product belonging to several parallel categories. Each value is either the
/// full path of the category, or the [category
///
/// ID](https:
/// //www.google.com/basepages/producttype/taxonomy-with-ids.en-US.txt).
/// Strongly recommended using the full path for better search / recommendation
/// quality.
///
/// To represent full path of category, use '>' sign to separate different
/// hierarchies. If '>' is part of the category name, you should escape it with
/// '\x3E'.
///
/// For example, if a shoes product belongs to both
/// ["Shoes & Accessories" -> "Shoes"] and
/// ["Sports & Fitness" -> "Athletic Clothing" -> "Shoes"], it could be
/// represented as:
///
/// "categories": [
/// "Shoes & Accessories > Shoes",
/// "Sports & Fitness > Athletic Clothing > Shoes"
/// ]
///
/// At most 250 values are allowed per
/// [Product][google.cloud.retail.v2.Product]. Empty values are not allowed.
/// Each value must be a UTF-8 encoded string with a length limit of 5 KiB.
/// Otherwise, an INVALID_ARGUMENT error is returned.
///
/// Google Merchant Center property
///
/// [google_product_category](https:
/// //support.google.com/merchants/answer/6324436).
/// Schema.org property [Product.category] (https://schema.org/category).
#[prost(string, repeated, tag = "7")]
pub categories: ::std::vec::Vec<std::string::String>,
/// Required. Product title.
///
/// This field must be a UTF-8 encoded string with a length limit of 128 bytes.
/// Otherwise, an INVALID_ARGUMENT error is returned.
///
/// Google Merchant Center property
/// [title](https://support.google.com/merchants/answer/6324415). Schema.org
/// property [Product.name](https://schema.org/name).
#[prost(string, tag = "8")]
pub title: std::string::String,
/// Product description.
///
/// This field must be a UTF-8 encoded string with a length limit of 5 KiB.
/// Otherwise, an INVALID_ARGUMENT error is returned.
///
/// Google Merchant Center property
/// [description](https://support.google.com/merchants/answer/6324468).
/// schema.org property [Product.description](https://schema.org/description).
#[prost(string, tag = "10")]
pub description: std::string::String,
/// Language of the title/description and other string attributes. Use language
/// tags defined by [BCP 47][https://www.rfc-editor.org/rfc/bcp/bcp47.txt].
///
/// The model automatically detects the text language. The
/// [Product][google.cloud.retail.v2.Product] can include text in different
/// languages, but duplicating [Product][google.cloud.retail.v2.Product]s to
/// provide text in multiple languages can result in degraded model
/// performance.
///
/// Currently, recommendation supports all language codes, while the only
/// supported language code for search is "en-US".
#[prost(string, tag = "11")]
pub language_code: std::string::String,
/// Highly encouraged. Extra product attributes to be included. For example,
/// for products, this could include the store name, vendor, style, color, etc.
/// These are very strong signals for recommendation model, thus we highly
/// recommend providing the attributes here.
///
/// Features that can take on one of a limited number of possible values. Two
/// types of features can be set are:
///
/// Textual features. some examples would be the brand/maker of a product, or
/// country of a customer. Numerical features. Some examples would be the
/// height/weight of a product, or age of a customer.
///
/// For example: { "vendor": {"text": ["vendor123", "vendor456"]},
/// "lengths_cm": {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]}
/// }.
///
/// A maximum of 150 attributes are allowed. Otherwise, an INVALID_ARGUMENT
/// error is returned.
#[prost(map = "string, message", tag = "12")]
pub attributes: ::std::collections::HashMap<std::string::String, CustomAttribute>,
/// Custom tags associated with the product.
///
/// At most 250 values are allowed per
/// [Product][google.cloud.retail.v2.Product]. This value must be a UTF-8
/// encoded string with a length limit of 1 KiB. Otherwise, an INVALID_ARGUMENT
/// error is returned.
///
/// This tag can be used for filtering recommendation results by passing the
/// tag as part of the
/// [PredictRequest.filter][google.cloud.retail.v2.PredictRequest.filter].
///
/// Google Merchant Center property
/// [custom_label_0–4](https://support.google.com/merchants/answer/6324473).
#[prost(string, repeated, tag = "13")]
pub tags: ::std::vec::Vec<std::string::String>,
/// Product price and cost information.
///
/// Google Merchant Center property
/// [price](https://support.google.com/merchants/answer/6324371).
#[prost(message, optional, tag = "14")]
pub price_info: ::std::option::Option<PriceInfo>,
/// The timestamp when this [Product][google.cloud.retail.v2.Product] becomes
/// available recommendation and search.
#[prost(message, optional, tag = "18")]
pub available_time: ::std::option::Option<::prost_types::Timestamp>,
/// The online availability of the [Product][google.cloud.retail.v2.Product],
/// which is parallel to and independent of [fulfillment_info][]. Default is
/// [Availability.IN_STOCK][google.cloud.retail.v2.Product.Availability.IN_STOCK].
///
/// Google Merchant Center Property
/// [availability](https://support.google.com/merchants/answer/6324448).
/// schema.org Property [Offer.availability](https://schema.org/availability).
#[prost(enumeration = "product::Availability", tag = "19")]
pub availability: i32,
/// The available quantity of the item.
#[prost(message, optional, tag = "20")]
pub available_quantity: ::std::option::Option<i32>,
/// Canonical URL directly linking to the product detail page.
///
/// This field must be a UTF-8 encoded string with a length limit of 5 KiB.
/// Otherwise, an INVALID_ARGUMENT error is returned.
///
/// Google Merchant Center property
/// [link](https://support.google.com/merchants/answer/6324416).
/// Schema.org property [Offer.url](https://schema.org/url).
#[prost(string, tag = "22")]
pub uri: std::string::String,
/// Product images for the product.
///
/// Google Merchant Center property
/// [image_link](https://support.google.com/merchants/answer/6324350).
/// Schema.org property [Product.image](https://schema.org/image).
#[prost(message, repeated, tag = "23")]
pub images: ::std::vec::Vec<Image>,
/// Indicates which fields in the [variants][] are retrievable in [Search][].
/// If not set or empty, the following fields are returned:
///
/// * [name][google.cloud.retail.v2.Product.name]
/// * [availability][google.cloud.retail.v2.Product.availability]
/// * [color_info][]
///
/// Supported fields:
///
/// * [name][google.cloud.retail.v2.Product.name]
/// * [availability][google.cloud.retail.v2.Product.availability]
/// * [color_info][]
/// * [gtin][]
/// * [price_info][google.cloud.retail.v2.Product.price_info]
/// * [sizes][]
/// * [materials][]
/// * [patterns][]
/// * [conditions][]
/// * [images][google.cloud.retail.v2.Product.images]
/// * [attributes][google.cloud.retail.v2.Product.attributes]
///
/// To mark custom attributes as retrievable, include paths of the form
/// "attributes.key" where "key" is the key of a custom attribute, as
/// specified in [attributes][google.cloud.retail.v2.Product.attributes].
///
/// Maximum number of paths is 10. Otherwise, an INVALID_ARGUMENT error is
/// returned.
#[prost(message, optional, tag = "30")]
pub stocking_unit_retrievable_fields: ::std::option::Option<::prost_types::FieldMask>,
}
pub mod product {
/// Product availability. If this field is unspecified, the product is
/// assumed to be in stock.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
#[repr(i32)]
pub enum Availability {
/// Default product availability. Default to
/// [Availability.IN_STOCK][google.cloud.retail.v2.Product.Availability.IN_STOCK]
/// if unset.
Unspecified = 0,
/// Product in stock.
InStock = 1,
/// Product out of stock.
OutOfStock = 2,
/// Product that is in pre-order state.
Preorder = 3,
/// Product that is back-ordered (i.e. temporarily out of stock).
Backorder = 4,
}
}
/// UserEvent captures all metadata information recommendation engine needs to
/// know about how end users interact with customers' website.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct UserEvent {
/// Required. User event type. Allowed values are:
///
/// * `add-to-cart` Products being added to cart.
/// * `category-page-view` Special pages such as sale or promotion pages
/// viewed.
/// * `detail-page-view` Products detail page viewed.
/// * `home-page-view` Homepage viewed.
/// * `purchase-complete` User finishing a purchase.
/// * `search`
/// * `shopping-cart-page-view` User viewing a shopping cart.
#[prost(string, tag = "1")]
pub event_type: std::string::String,
/// Required. A unique identifier for tracking visitors. For example, this
/// could be implemented with a http cookie, which should be able to uniquely
/// identify a visitor on a single device. This unique identifier should not
/// change if the visitor log in/out of the website.
///
/// The field must be a UTF-8 encoded string with a length limit of 128 bytes.
/// Otherwise, an INVALID_ARGUMENT error is returned.
#[prost(string, tag = "2")]
pub visitor_id: std::string::String,
/// Only required for
/// [UserEventService.ImportUserEvents][google.cloud.retail.v2.UserEventService.ImportUserEvents]
/// method. Timestamp of when the user event happened.
#[prost(message, optional, tag = "3")]
pub event_time: ::std::option::Option<::prost_types::Timestamp>,
/// A list of identifiers for the independent experiment groups
/// this user event belongs to. This is used to distinguish between user events
/// associated with different experiment setups (e.g. using Recommendations AI,
/// using different recommendation models).
#[prost(string, repeated, tag = "4")]
pub experiment_ids: ::std::vec::Vec<std::string::String>,
/// Highly recommended for user events that are the result of
/// [PredictionService.Predict][google.cloud.retail.v2.PredictionService.Predict].
/// This field enables accurate attribution of recommendation model
/// performance.
///
/// The value must be a valid
/// [PredictResponse.attribute_token][] for user events that are the result of
/// [PredictionService.Predict][google.cloud.retail.v2.PredictionService.Predict].
///
/// This token enables us to accurately attribute page view or purchase back to
/// the event and the particular predict response containing this
/// clicked/purchased product. If user clicks on product K in the
/// recommendation results, pass [PredictResponse.attribute_token][] as a url
/// parameter to product K's page. When recording events on product K's page,
/// log the [PredictResponse.attribute_token][] to this field.
#[prost(string, tag = "5")]
pub attribution_token: std::string::String,
/// The main product details related to the event.
///
/// This field is required for the following event types:
///
/// * `add-to-cart`
/// * `detail-page-view`
/// * `purchase-complete`
///
/// In a `search` event, this field represents the products returned to the end
/// user on the current page (the end user may have not finished broswing the
/// whole page yet). When a new page is returned to the end user, after
/// pagination/filtering/ordering even for the same query, a new SEARCH event
/// with different
/// [product_details][google.cloud.retail.v2.UserEvent.product_details] is
/// desired. The end user may have not finished broswing the whole page yet.
#[prost(message, repeated, tag = "6")]
pub product_details: ::std::vec::Vec<ProductDetail>,
/// Extra user event features to include in the recommendation model.
///
/// For product recommendation, an example of extra user information is
/// traffic_channel, i.e. how user arrives at the site. Users can arrive
/// at the site by coming to the site directly, or coming through Google
/// search, and etc.
#[prost(map = "string, message", tag = "7")]
pub attributes: ::std::collections::HashMap<std::string::String, CustomAttribute>,
/// The id or name of the associated shopping cart. This id is used
/// to associate multiple items added or present in the cart before purchase.
///
/// This can only be set for `add-to-cart`, `remove-from-cart`,
/// `checkout-start`, `purchase-complete`, or `shopping-cart-page-view` events.
#[prost(string, tag = "8")]
pub cart_id: std::string::String,
/// A transaction represents the entire purchase transaction.
///
/// Required for `purchase-complete` events. Optional for `checkout-start`
/// events. Other event types should not set this field. Otherwise, an
/// INVALID_ARGUMENT error is returned.
#[prost(message, optional, tag = "9")]
pub purchase_transaction: ::std::option::Option<PurchaseTransaction>,
/// The user's search query.
///
/// The value must be a UTF-8 encoded string with a length limit of 5 KiB.
/// Otherwise, an INVALID_ARGUMENT error is returned.
///
/// Required for `search` events. Other event types should not set this field.
/// Otherwise, an INVALID_ARGUMENT error is returned.
#[prost(string, tag = "10")]
pub search_query: std::string::String,
/// The categories associated with a category page.
///
/// To represent full path of category, use '>' sign to separate different
/// hierarchies. If '>' is part of the category name, you should escape it with
/// '\x3E'.
///
/// Category pages include special pages such as sales or promotions. For
/// instance, a special sale page may have the category hierarchy:
/// "pageCategories" : ["Sales > 2017 Black Friday Deals"].
///
/// Required for `category-page-view` events. Other event types should not set
/// this field. Otherwise, an INVALID_ARGUMENT error is returned.
#[prost(string, repeated, tag = "11")]
pub page_categories: ::std::vec::Vec<std::string::String>,
/// User information.
#[prost(message, optional, tag = "12")]
pub user_info: ::std::option::Option<UserInfo>,
/// Complete url (window.location.href) of the user's current page.
/// When using the client side event reporting with JavaScript pixel and Google
/// Tag Manager, this value is filled in automatically. Maximum length 5KB.
#[prost(string, tag = "13")]
pub uri: std::string::String,
/// The referrer url of the current page. When using
/// the client side event reporting with JavaScript pixel and Google Tag
/// Manager, this value is filled in automatically.
#[prost(string, tag = "14")]
pub referrer_uri: std::string::String,
/// A unique id of a web page view.
/// This should be kept the same for all user events triggered from the same
/// pageview. For example, an item detail page view could trigger multiple
/// events as the user is browsing the page.
/// The `pageViewId` property should be kept the same for all these events so
/// that they can be grouped together properly. This `pageViewId` will be
/// automatically generated if using the client side event reporting with
/// JavaScript pixel and Google Tag Manager.
#[prost(string, tag = "15")]
pub page_view_id: std::string::String,
/// User event source.
/// Acceptable values are:
///
/// * `client_tag` if the event is ingested via a JavaScript tag or
/// Recommendations AI Tag through automl datalayer or JS Macros.
/// * `client_tag_ecommerce` if the event is ingested via Recommendations AI
/// Tag through
/// Enhanced Ecommerce datalayer.
/// * 'batch_upload' if the event is ingested via ImportUserEvents API.
///
/// This field should *not* be set when using client side event reporting with
/// JavaScript pixel and Google Tag Manager or the Recommendations AI Tag.
#[prost(string, tag = "16")]
pub event_source: std::string::String,
}
/// Detailed product information associated with a user event.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ProductDetail {
/// Required. [Product][google.cloud.retail.v2.Product] information.
/// Only [Product][id] field must to be set.
#[prost(message, optional, tag = "1")]
pub product: ::std::option::Option<Product>,
/// Quantity of the product associated with the user event. For
/// example, this field will be 2 if two products are added to the shopping
/// cart for `purchase-complete` event. Required for `add-to-cart` and
/// `purchase-complete` event types.
#[prost(message, optional, tag = "2")]
pub quantity: ::std::option::Option<i32>,
}
/// A transaction represents the entire purchase transaction.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PurchaseTransaction {
/// The transaction ID with a length limit of 128 bytes.
#[prost(string, tag = "1")]
pub id: std::string::String,
/// Required. Total revenue or grand total associated with the transaction.
/// This value include shipping, tax, or other adjustments to total revenue
/// that you want to include as part of your revenue calculations. This field
/// is not required if the event type is `refund`.
#[prost(float, tag = "2")]
pub revenue: f32,
/// All the taxes associated with the transaction.
#[prost(float, tag = "3")]
pub tax: f32,
/// All the costs associated with the product. These can be
/// manufacturing costs, shipping expenses not borne by the end user, or any
/// other costs.
///
/// Total product cost such that
/// profit = revenue - tax + [Product][pricing][cost]
/// If product_cost is not set, then
/// profit = revenue - tax - [Product][pricing][cost].
///
/// If [Product][pricing][cost] is not specified for one of the products,
/// [Product][pricing][cost] based profit *cannot* be calculated for this
/// Transaction.
#[prost(float, tag = "4")]
pub cost: f32,
/// Required. Currency code. Use three-character ISO-4217 code. This field
/// is not required if the event type is `refund`.
#[prost(string, tag = "5")]
pub currency_code: std::string::String,
}
/// Google Cloud Storage location for input content.
/// format.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct GcsSource {
/// Required. Google Cloud Storage URIs to input files. URI can be up to
/// 2000 characters long. URIs can match the full object path (for example,
/// gs://bucket/directory/object.json) or a pattern matching one or more
/// files, such as gs://bucket/directory/*.json. A request can
/// contain at most 100 files, and each file can be up to 2 GB. See
/// [Importing product information](/recommendations-ai/docs/upload-catalog)
/// for the expected file format and setup instructions.
#[prost(string, repeated, tag = "1")]
pub input_uris: ::std::vec::Vec<std::string::String>,
/// The schema to use when parsing the data from the source.
///
/// Supported values for product imports:
///
/// 1: "product" using
/// https://cloud.google.com/recommendations-ai/docs/upload-catalog#json
/// (Default for products.import)
///
/// 2: "product_merchant_center" using
/// https://cloud.google.com/recommendations-ai/docs/upload-catalog#mc
///
/// Supported values for user events imports:
///
/// 1: "user_event" using
/// https://cloud.google.com/recommendations-ai/docs/manage-user-events#import
/// (Default for userEvents.import)
///
/// 2. "user_event_ga360" using
/// https://support.google.com/analytics/answer/3437719?hl=en
#[prost(string, tag = "2")]
pub data_schema: std::string::String,
}
/// BigQuery source import data from.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct BigQuerySource {
/// The project id (can be project # or id) that the BigQuery source is in. If
/// not specified, inherits the project id from the parent request.
#[prost(string, tag = "5")]
pub project_id: std::string::String,
/// Required. The BigQuery data set to copy the data from.
#[prost(string, tag = "1")]
pub dataset_id: std::string::String,
/// Required. The BigQuery table to copy the data from.
#[prost(string, tag = "2")]
pub table_id: std::string::String,
/// Intermediate Cloud Storage directory used for the import. Can be specified
/// if one wants to have the BigQuery export to a specific Cloud Storage
/// directory.
#[prost(string, tag = "3")]
pub gcs_staging_dir: std::string::String,
/// The schema to use when parsing the data from the source.
///
/// Supported values for catalog imports:
///
/// 1: "product" using
/// https://cloud.google.com/recommendations-ai/docs/upload-catalog#json
/// (Default for products.import)
///
/// 2: "product_merchant_center" using
/// https://cloud.google.com/recommendations-ai/docs/upload-catalog#mc
///
/// Supported values for user event imports:
///
/// 1: "user_event" using
/// https://cloud.google.com/recommendations-ai/docs/manage-user-events#import
/// (Default for userEvents.import)
///
/// 2. "user_event_ga360" using
/// https://support.google.com/analytics/answer/3437719?hl=en
#[prost(string, tag = "4")]
pub data_schema: std::string::String,
}
/// The inline source for the input config for ImportProducts method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ProductInlineSource {
/// A list of products to update/create. Recommended max of 10k items.
#[prost(message, repeated, tag = "1")]
pub products: ::std::vec::Vec<Product>,
}
/// The inline source for the input config for ImportUserEvents method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct UserEventInlineSource {
/// A list of user events to import. Recommended max of 10k items.
#[prost(message, repeated, tag = "1")]
pub user_events: ::std::vec::Vec<UserEvent>,
}
/// Configuration of destination for Import related errors.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ImportErrorsConfig {
/// Required. Errors destination.
#[prost(oneof = "import_errors_config::Destination", tags = "1")]
pub destination: ::std::option::Option<import_errors_config::Destination>,
}
pub mod import_errors_config {
/// Required. Errors destination.
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Destination {
/// Google Cloud Storage path for import errors. This must be an empty,
/// existing Cloud Storage bucket. Import errors will be written to a file in
/// this bucket, one per line, as a JSON-encoded
/// `google.rpc.Status` message.
#[prost(string, tag = "1")]
GcsPrefix(std::string::String),
}
}
/// Request message for Import methods.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ImportProductsRequest {
/// Required.
/// "projects/1234/locations/global/catalogs/default_catalog/branches/default_branch"
///
/// If no updateMask is specified, requires products.create permission.
/// If updateMask is specified, requires products.update permission.
#[prost(string, tag = "1")]
pub parent: std::string::String,
/// Required. The desired input location of the data.
#[prost(message, optional, tag = "2")]
pub input_config: ::std::option::Option<ProductInputConfig>,
/// The desired location of errors incurred during the Import.
#[prost(message, optional, tag = "3")]
pub errors_config: ::std::option::Option<ImportErrorsConfig>,
/// Indicates which fields in the provided imported 'products' to update. If
/// not set, will by default update all fields.
#[prost(message, optional, tag = "4")]
pub update_mask: ::std::option::Option<::prost_types::FieldMask>,
}
/// Request message for the ImportUserEvents request.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ImportUserEventsRequest {
/// Required. "projects/1234/locations/global/catalogs/default_catalog"
#[prost(string, tag = "1")]
pub parent: std::string::String,
/// Required. The desired input location of the data.
#[prost(message, optional, tag = "2")]
pub input_config: ::std::option::Option<UserEventInputConfig>,
/// The desired location of errors incurred during the Import.
#[prost(message, optional, tag = "3")]
pub errors_config: ::std::option::Option<ImportErrorsConfig>,
}
/// The input config source for products.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ProductInputConfig {
/// Required. The source of the input.
#[prost(oneof = "product_input_config::Source", tags = "1, 2, 3")]
pub source: ::std::option::Option<product_input_config::Source>,
}
pub mod product_input_config {
/// Required. The source of the input.
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Source {
/// The Inline source for the input content for products.
#[prost(message, tag = "1")]
ProductInlineSource(super::ProductInlineSource),
/// Google Cloud Storage location for the input content.
#[prost(message, tag = "2")]
GcsSource(super::GcsSource),
/// BigQuery input source.
#[prost(message, tag = "3")]
BigQuerySource(super::BigQuerySource),
}
}
/// The input config source for user events.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct UserEventInputConfig {
/// The source of the input.
#[prost(oneof = "user_event_input_config::Source", tags = "1, 2, 3")]
pub source: ::std::option::Option<user_event_input_config::Source>,
}
pub mod user_event_input_config {
/// The source of the input.
#[derive(Clone, PartialEq, ::prost::Oneof)]
pub enum Source {
/// Required. The Inline source for the input content for UserEvents.
#[prost(message, tag = "1")]
UserEventInlineSource(super::UserEventInlineSource),
/// Required. Google Cloud Storage location for the input content.
#[prost(message, tag = "2")]
GcsSource(super::GcsSource),
/// Required. BigQuery input source.
#[prost(message, tag = "3")]
BigQuerySource(super::BigQuerySource),
}
}
/// Metadata related to the progress of the Import operation. This will be
/// returned by the google.longrunning.Operation.metadata field.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ImportMetadata {
/// Name of the operation.
#[prost(string, tag = "1")]
pub name: std::string::String,
/// Operation create time.
#[prost(message, optional, tag = "2")]
pub create_time: ::std::option::Option<::prost_types::Timestamp>,
/// Operation last update time. If the operation is done, this is also the
/// finish time.
#[prost(message, optional, tag = "3")]
pub update_time: ::std::option::Option<::prost_types::Timestamp>,
/// Count of entries that were processed successfully.
#[prost(int64, tag = "4")]
pub success_count: i64,
/// Count of entries that encountered errors while processing.
#[prost(int64, tag = "5")]
pub failure_count: i64,
}
/// Response of the
/// [ImportProductsRequest][google.cloud.retail.v2.ImportProductsRequest]. If the
/// long running operation is done, then this message is returned by the
/// google.longrunning.Operations.response field if the operation was successful.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ImportProductsResponse {
/// A sample of errors encountered while processing the request.
#[prost(message, repeated, tag = "1")]
pub error_samples: ::std::vec::Vec<super::super::super::rpc::Status>,
/// Echoes the destination for the complete errors in the request if set.
#[prost(message, optional, tag = "2")]
pub errors_config: ::std::option::Option<ImportErrorsConfig>,
}
/// Response of the ImportUserEventsRequest. If the long running
/// operation was successful, then this message is returned by the
/// google.longrunning.Operations.response field if the operation was successful.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ImportUserEventsResponse {
/// A sample of errors encountered while processing the request.
#[prost(message, repeated, tag = "1")]
pub error_samples: ::std::vec::Vec<super::super::super::rpc::Status>,
/// Echoes the destination for the complete errors if this field was set in
/// the request.
#[prost(message, optional, tag = "2")]
pub errors_config: ::std::option::Option<ImportErrorsConfig>,
/// Aggregated statistics of user event import status.
#[prost(message, optional, tag = "3")]
pub import_summary: ::std::option::Option<UserEventImportSummary>,
}
/// A summary of import result. The UserEventImportSummary summarizes
/// the import status for user events.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct UserEventImportSummary {
/// Count of user events imported with complete existing catalog information.
#[prost(int64, tag = "1")]
pub joined_events_count: i64,
/// Count of user events imported, but with catalog information not found
/// in the imported catalog.
#[prost(int64, tag = "2")]
pub unjoined_events_count: i64,
}
/// Request message for Predict method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PredictRequest {
/// Required. Full resource name of the format:
/// {name=projects/*/locations/global/catalogs/default_catalog/placements/*}
/// The id of the recommendation engine placement. This id is used to identify
/// the set of models that will be used to make the prediction.
///
/// We currently support three placements with the following IDs by default:
///
/// * `shopping_cart`: Predicts products frequently bought together with one or
/// more products in the same shopping session. Commonly displayed after
/// `add-to-cart` events, on product detail pages, or on the shopping cart
/// page.
///
/// * `home_page`: Predicts the next product that a user will most likely
/// engage with or purchase based on the shopping or viewing history of the
/// specified `userId` or `visitorId`. For example - Recommendations for you.
///
/// * `product_detail`: Predicts the next product that a user will most likely
/// engage with or purchase. The prediction is based on the shopping or
/// viewing history of the specified `userId` or `visitorId` and its
/// relevance to a specified `CatalogItem`. Typically used on product detail
/// pages. For example - More products like this.
///
/// * `recently_viewed_default`: Returns up to 75 products recently viewed by
/// the specified `userId` or `visitorId`, most recent ones first. Returns
/// nothing if neither of them has viewed any products yet. For example -
/// Recently viewed.
///
/// The full list of available placements can be seen at
///
/// https:
/// //console.cloud.google.com/recommendatio
/// // n/datafeeds/default_catalog/dashboard
#[prost(string, tag = "1")]
pub placement: std::string::String,
/// Required. Context about the user, what they are looking at and what action
/// they took to trigger the predict request. Note that this user event detail
/// won't be ingested to userEvent logs. Thus, a separate userEvent write
/// request is required for event logging.
#[prost(message, optional, tag = "2")]
pub user_event: ::std::option::Option<UserEvent>,
/// Maximum number of results to return per page. Set this property
/// to the number of prediction results needed. If zero, the service will
/// choose a reasonable default. The maximum allowed value is 100. Values
/// above 100 will be coerced to 100.
#[prost(int32, tag = "3")]
pub page_size: i32,
/// The previous PredictResponse.next_page_token.
#[prost(string, tag = "4")]
pub page_token: std::string::String,
/// Filter for restricting prediction results. Accepts values for
/// tags and the `filterOutOfStockItems` flag.
///
/// * Tag expressions. Restricts predictions to products that match all of the
/// specified tags. Boolean operators `OR` and `NOT` are supported if the
/// expression is enclosed in parentheses, and must be separated from the
/// tag values by a space. `-"tagA"` is also supported and is equivalent to
/// `NOT "tagA"`. Tag values must be double quoted UTF-8 encoded strings
/// with a size limit of 1 KiB.
///
/// * filterOutOfStockItems. Restricts predictions to products that do not
/// have a
/// stockState value of OUT_OF_STOCK.
///
/// Examples:
///
/// * tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT "promotional")
/// * filterOutOfStockItems tag=(-"promotional")
/// * filterOutOfStockItems
///
/// If your filter blocks all prediction results, nothing will be returned. If
/// you want generic (unfiltered) popular products to be returned instead, set
/// `strictFiltering` to false in `PredictRequest.params`.
#[prost(string, tag = "5")]
pub filter: std::string::String,
/// Use validate only mode for this prediction query. If set to true, a
/// dummy model will be used that returns arbitrary products.
/// Note that the validate only mode should only be used for testing the API,
/// or if the model is not ready.
#[prost(bool, tag = "6")]
pub validate_only: bool,
/// Additional domain specific parameters for the predictions.
///
/// Allowed values:
///
/// * `returnProduct`: Boolean. If set to true, the associated product
/// object will be returned in the `results.metadata` field in the
/// prediction response.
/// * `returnScore`: Boolean. If set to true, the prediction 'score'
/// corresponding to each returned product will be set in the
/// `results.metadata` field in the prediction response. The given
/// 'score' indicates the probability of an product being clicked/purchased
/// given the user's context and history.
/// * `strictFiltering`: Boolean. True by default. If set to false, the service
/// will return generic (unfiltered) popular products instead of empty if
/// your filter blocks all prediction results.
#[prost(map = "string, message", tag = "7")]
pub params: ::std::collections::HashMap<std::string::String, ::prost_types::Value>,
/// The labels for the predict request.
///
/// * Label keys can contain lowercase letters, digits and hyphens, must start
/// with a letter, and must end with a letter or digit.
/// * Non-zero label values can contain lowercase letters, digits and hyphens,
/// must start with a letter, and must end with a letter or digit.
/// * No more than 64 labels can be associated with a given request.
///
/// See https://goo.gl/xmQnxf for more information on and examples of labels.
#[prost(map = "string, string", tag = "8")]
pub labels: ::std::collections::HashMap<std::string::String, std::string::String>,
}
/// Response message for predict method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PredictResponse {
/// A list of recommended products. The order represents the ranking (from the
/// most relevant product to the least).
#[prost(message, repeated, tag = "1")]
pub results: ::std::vec::Vec<predict_response::PredictionResult>,
/// A unique attribution token. This should be included in the
/// [UserEvent][google.cloud.retail.v2.UserEvent] logs resulting from this
/// recommendation, which enables accurate attribution of recommendation model
/// performance.
#[prost(string, tag = "2")]
pub attribution_token: std::string::String,
/// IDs of products in the request that were missing from the inventory.
#[prost(string, repeated, tag = "3")]
pub missing_ids: ::std::vec::Vec<std::string::String>,
/// True if the validateOnly property was set in the request.
#[prost(bool, tag = "4")]
pub validate_only: bool,
}
pub mod predict_response {
/// PredictionResult represents the recommendation prediction results.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PredictionResult {
/// ID of the recommended product
#[prost(string, tag = "1")]
pub id: std::string::String,
/// Additional product metadata / annotations.
///
/// Possible values:
///
/// * `product`: JSON representation of the product. Will be set if
/// `returnProduct` is set to true in `PredictRequest.params`.
/// * `score`: Prediction score in double value. Will be set if
/// `returnScore` is set to true in `PredictRequest.params`.
#[prost(map = "string, message", tag = "2")]
pub metadata: ::std::collections::HashMap<std::string::String, ::prost_types::Value>,
}
}
#[doc = r" Generated client implementations."]
pub mod prediction_service_client {
#![allow(unused_variables, dead_code, missing_docs)]
use tonic::codegen::*;
#[doc = " Service for making recommendation prediction."]
pub struct PredictionServiceClient<T> {
inner: tonic::client::Grpc<T>,
}
impl<T> PredictionServiceClient<T>
where
T: tonic::client::GrpcService<tonic::body::BoxBody>,
T::ResponseBody: Body + HttpBody + Send + 'static,
T::Error: Into<StdError>,
<T::ResponseBody as HttpBody>::Error: Into<StdError> + Send,
{
pub fn new(inner: T) -> Self {
let inner = tonic::client::Grpc::new(inner);
Self { inner }
}
pub fn with_interceptor(inner: T, interceptor: impl Into<tonic::Interceptor>) -> Self {
let inner = tonic::client::Grpc::with_interceptor(inner, interceptor);
Self { inner }
}
#[doc = " Makes a recommendation prediction."]
pub async fn predict(
&mut self,
request: impl tonic::IntoRequest<super::PredictRequest>,
) -> Result<tonic::Response<super::PredictResponse>, tonic::Status> {
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/google.cloud.retail.v2.PredictionService/Predict",
);
self.inner.unary(request.into_request(), path, codec).await
}
}
impl<T: Clone> Clone for PredictionServiceClient<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
impl<T> std::fmt::Debug for PredictionServiceClient<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "PredictionServiceClient {{ ... }}")
}
}
}
/// Metadata related to the progress of the Purge operation.
/// This will be returned by the google.longrunning.Operation.metadata field.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PurgeMetadata {
/// The ID of the request / operation.
#[prost(string, tag = "1")]
pub operation: std::string::String,
/// Operation create time.
#[prost(message, optional, tag = "2")]
pub create_time: ::std::option::Option<::prost_types::Timestamp>,
}
/// Request message for PurgeProducts method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PurgeProductsRequest {
/// Required. The resource name of the catalog under which the products are
/// created. The format is
/// "projects/${projectId}/locations/global/catalogs/${catalogId}"
#[prost(string, tag = "1")]
pub parent: std::string::String,
/// Required. Filter matching the products to be purged. Only supported value
/// at the moment is "*" (all items).
#[prost(string, tag = "2")]
pub filter: std::string::String,
/// The default value is false. Override this flag to true to
/// actually perform the purge. If the field is not set to true, a sampling of
/// products to be deleted will be returned.
#[prost(bool, tag = "3")]
pub force: bool,
}
/// Response of the PurgeProductsRequest. If the long running operation is
/// successfully done, then this message is returned by the
/// google.longrunning.Operations.response field.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PurgeProductsResponse {
/// The total count of products purged as a result of the operation.
#[prost(int64, tag = "1")]
pub purged_count: i64,
/// A random sampling of products deleted (or will be deleted) depending
/// on the `force` property in the request. Max of 500 items will be returned.
/// Currently, this is only populated if force=false.
#[prost(message, repeated, tag = "2")]
pub products_sample: ::std::vec::Vec<Product>,
}
/// Request message for PurgeUserEvents method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PurgeUserEventsRequest {
/// Required. The resource name of the event_store under which the events are
/// created. The format is
///
/// "projects/${projectId}/locations/global/catalogs/${catalogId}/eventStores/${eventStoreId}"
#[prost(string, tag = "1")]
pub parent: std::string::String,
/// Required. The filter string to specify the events to be deleted. Empty
/// string filter is not allowed. The eligible fields
/// for filtering are:
///
/// * `eventType`: UserEvent.eventType field of type string.
/// * `eventTime`: in ISO 8601 "zulu" format.
/// * `visitorId`: field of type string. Specifying this will delete all
/// events associated with a visitor.
/// * `userId`: field of type string. Specifying this will delete all events
/// associated with a user.
///
/// Examples:
///
/// * Deleting all events in a time range:
/// `eventTime > "2012-04-23T18:25:43.511Z"
/// eventTime < "2012-04-23T18:30:43.511Z"`
/// * Deleting specific eventType in time range:
/// `eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`
/// * Deleting all events for a specific visitor:
/// `visitorId = "visitor1024"`
///
/// The filtering fields are assumed to have an implicit AND.
#[prost(string, tag = "2")]
pub filter: std::string::String,
/// The default value is false. Override this flag to true to
/// actually perform the purge. If the field is not set to true, a sampling of
/// events to be deleted will be returned.
#[prost(bool, tag = "3")]
pub force: bool,
}
/// Response of the PurgeUserEventsRequest. If the long running operation is
/// successfully done, then this message is returned by the
/// google.longrunning.Operations.response field.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct PurgeUserEventsResponse {
/// The total count of events purged as a result of the operation.
#[prost(int64, tag = "1")]
pub purged_events_count: i64,
/// A sampling of events deleted (or will be deleted) depending on the `force`
/// property in the request. Max of 500 items will be returned.
#[prost(message, repeated, tag = "2")]
pub user_events_sample: ::std::vec::Vec<UserEvent>,
}
/// Request message for [CreateProduct][] method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CreateProductRequest {
/// Required. The parent catalog resource name, such as
///
/// "projects/*/locations/global/catalogs/default_catalog/branches/default_branch".
#[prost(string, tag = "1")]
pub parent: std::string::String,
/// Required. The [Product][google.cloud.retail.v2.Product] to create.
#[prost(message, optional, tag = "2")]
pub product: ::std::option::Option<Product>,
/// Required. The ID to use for the [Product][google.cloud.retail.v2.Product],
/// which will become the final component of the
/// [Product.name][google.cloud.retail.v2.Product.name].
///
/// If the caller does not have permission to create the
/// [Product][google.cloud.retail.v2.Product], regardless of whether or not it
/// exists, a PERMISSION_DENIED error is returned.
///
/// This field must be unique among all
/// [Product][google.cloud.retail.v2.Product]s with the same
/// [parent][google.cloud.retail.v2.CreateProductRequest.parent]. Otherwise, an
/// ALREADY_EXISTS error is returned.
///
/// This field must be a UTF-8 encoded string with a length limit of 128 bytes.
/// Otherwise, an INVALID_ARGUMENT error is returned.
#[prost(string, tag = "3")]
pub product_id: std::string::String,
}
/// Request message for [GetProduct][] method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct GetProductRequest {
/// Required. Full resource name of [Product][google.cloud.retail.v2.Product],
/// such as
///
/// "projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id".
///
/// If the caller does not have permission to access the
/// [Product][google.cloud.retail.v2.Product], regardless of whether or not it
/// exists, a PERMISSION_DENIED error is returned.
///
/// If the requested [Product][google.cloud.retail.v2.Product] does not exist,
/// a NOT_FOUND error is returned.
#[prost(string, tag = "1")]
pub name: std::string::String,
}
/// Request message for [UpdateProduct][] method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct UpdateProductRequest {
/// Required. The product to update/create.
///
/// If the caller does not have permission to update the
/// [Product][google.cloud.retail.v2.Product], regardless of whether or not it
/// exists, a PERMISSION_DENIED error is returned.
///
/// If the [Product][google.cloud.retail.v2.Product] to update does not exist,
/// a NOT_FOUND error is returned.
#[prost(message, optional, tag = "1")]
pub product: ::std::option::Option<Product>,
/// Indicates which fields in the provided
/// [Product][google.cloud.retail.v2.Product] to update. The immutable and
/// output only fields are NOT supported. If not set, all supported fields (the
/// fields that are neither immutable nor output only) are updated.
///
/// If an unsupported or unknown field is provided, an INVALID_ARGUMENT error
/// is returned.
#[prost(message, optional, tag = "2")]
pub update_mask: ::std::option::Option<::prost_types::FieldMask>,
}
/// Request message for [DeleteProduct][] method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct DeleteProductRequest {
/// Required. Full resource name of [Product][google.cloud.retail.v2.Product],
/// such as
///
/// "projects/*/locations/global/catalogs/default_catalog/branches/default_branch/products/some_product_id".
///
/// If the caller does not have permission to delete the
/// [Product][google.cloud.retail.v2.Product], regardless of whether or not it
/// exists, a PERMISSION_DENIED error is returned.
///
/// If the [Product][google.cloud.retail.v2.Product] to delete does not exist,
/// a NOT_FOUND error is returned.
///
/// The [Product][google.cloud.retail.v2.Product] to delete can neither be a
/// non-empty [Product.Type.COLLECTION][]
/// [Product][google.cloud.retail.v2.Product] nor a [Product.Type.PRIMARY][]
/// [Product][google.cloud.retail.v2.Product] with more than one
/// [variants][Product.Type.VARIANT]. Otherwise, a FAILED_PRECONDITION error is
/// returned.
#[prost(string, tag = "1")]
pub name: std::string::String,
}
#[doc = r" Generated client implementations."]
pub mod product_service_client {
#![allow(unused_variables, dead_code, missing_docs)]
use tonic::codegen::*;
#[doc = " Service for ingesting [Product][google.cloud.retail.v2.Product] information"]
#[doc = " of the customer's website."]
pub struct ProductServiceClient<T> {
inner: tonic::client::Grpc<T>,
}
impl<T> ProductServiceClient<T>
where
T: tonic::client::GrpcService<tonic::body::BoxBody>,
T::ResponseBody: Body + HttpBody + Send + 'static,
T::Error: Into<StdError>,
<T::ResponseBody as HttpBody>::Error: Into<StdError> + Send,
{
pub fn new(inner: T) -> Self {
let inner = tonic::client::Grpc::new(inner);
Self { inner }
}
pub fn with_interceptor(inner: T, interceptor: impl Into<tonic::Interceptor>) -> Self {
let inner = tonic::client::Grpc::with_interceptor(inner, interceptor);
Self { inner }
}
#[doc = " Creates a [Product][google.cloud.retail.v2.Product]."]
pub async fn create_product(
&mut self,
request: impl tonic::IntoRequest<super::CreateProductRequest>,
) -> Result<tonic::Response<super::Product>, tonic::Status> {
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/google.cloud.retail.v2.ProductService/CreateProduct",
);
self.inner.unary(request.into_request(), path, codec).await
}
#[doc = " Gets a [Product][google.cloud.retail.v2.Product]."]
pub async fn get_product(
&mut self,
request: impl tonic::IntoRequest<super::GetProductRequest>,
) -> Result<tonic::Response<super::Product>, tonic::Status> {
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/google.cloud.retail.v2.ProductService/GetProduct",
);
self.inner.unary(request.into_request(), path, codec).await
}
#[doc = " Updates a [Product][google.cloud.retail.v2.Product]. Non-existing items"]
#[doc = " will be created."]
pub async fn update_product(
&mut self,
request: impl tonic::IntoRequest<super::UpdateProductRequest>,
) -> Result<tonic::Response<super::Product>, tonic::Status> {
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/google.cloud.retail.v2.ProductService/UpdateProduct",
);
self.inner.unary(request.into_request(), path, codec).await
}
#[doc = " Deletes a [Product][google.cloud.retail.v2.Product]."]
pub async fn delete_product(
&mut self,
request: impl tonic::IntoRequest<super::DeleteProductRequest>,
) -> Result<tonic::Response<()>, tonic::Status> {
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/google.cloud.retail.v2.ProductService/DeleteProduct",
);
self.inner.unary(request.into_request(), path, codec).await
}
#[doc = " Permanently deletes all [Product][google.cloud.retail.v2.Product]s under a"]
#[doc = " branch."]
#[doc = ""]
#[doc = " Depending on the number of [Product][google.cloud.retail.v2.Product]s, this"]
#[doc = " operation could take hours to complete. To get a sample of"]
#[doc = " [Product][google.cloud.retail.v2.Product]s that would be deleted, set"]
#[doc = " [PurgeProductsRequest.force][google.cloud.retail.v2.PurgeProductsRequest.force]"]
#[doc = " to false."]
pub async fn purge_products(
&mut self,
request: impl tonic::IntoRequest<super::PurgeProductsRequest>,
) -> Result<
tonic::Response<super::super::super::super::longrunning::Operation>,
tonic::Status,
> {
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/google.cloud.retail.v2.ProductService/PurgeProducts",
);
self.inner.unary(request.into_request(), path, codec).await
}
#[doc = " Bulk import of multiple [Product][google.cloud.retail.v2.Product]s."]
#[doc = ""]
#[doc = " Request processing may be synchronous. No partial updating is supported."]
#[doc = " Non-existing items are created."]
#[doc = ""]
#[doc = " Note that it is possible for a subset of the"]
#[doc = " [Product][google.cloud.retail.v2.Product]s to be successfully updated."]
pub async fn import_products(
&mut self,
request: impl tonic::IntoRequest<super::ImportProductsRequest>,
) -> Result<
tonic::Response<super::super::super::super::longrunning::Operation>,
tonic::Status,
> {
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/google.cloud.retail.v2.ProductService/ImportProducts",
);
self.inner.unary(request.into_request(), path, codec).await
}
}
impl<T: Clone> Clone for ProductServiceClient<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
impl<T> std::fmt::Debug for ProductServiceClient<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ProductServiceClient {{ ... }}")
}
}
}
/// Request message for WriteUserEvent method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct WriteUserEventRequest {
/// Required. The parent eventStore resource name, such as
/// "projects/1234/locations/global/catalogs/default_catalog".
#[prost(string, tag = "1")]
pub parent: std::string::String,
/// Required. User event to write.
#[prost(message, optional, tag = "2")]
pub user_event: ::std::option::Option<UserEvent>,
}
/// Request message for CollectUserEvent method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CollectUserEventRequest {
/// Required. The parent eventStore name, such as
/// "projects/1234/locations/global/catalogs/default_catalog".
#[prost(string, tag = "1")]
pub parent: std::string::String,
/// Required. URL encoded UserEvent proto.
#[prost(string, tag = "2")]
pub user_event: std::string::String,
/// The url including cgi-parameters but excluding the hash fragment. The URL
/// must be truncated to 1.5K bytes to conservatively be under the 2K bytes.
/// This is often more useful than the referer url, because many browsers only
/// send the domain for 3rd party requests.
#[prost(string, tag = "3")]
pub uri: std::string::String,
/// The event timestamp in milliseconds. This prevents browser caching of
/// otherwise identical get requests. The name is abbreviated to reduce the
/// payload bytes.
#[prost(int64, tag = "4")]
pub ets: i64,
}
/// Request message for CatalogRejoin method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct RejoinUserEventsRequest {
/// Required. Full resource name of user event, such as
/// "projects/*/locations/*/catalogs/default_catalog".
#[prost(string, tag = "1")]
pub parent: std::string::String,
/// Required. The type of the catalog rejoin to define the scope and range of
/// the user events to be rejoined with catalog items.
#[prost(
enumeration = "rejoin_user_events_request::UserEventRejoinScope",
tag = "2"
)]
pub user_event_rejoin_scope: i32,
}
pub mod rejoin_user_events_request {
/// The scope of events to be rejoined with latest catalog. If the rejoining
/// aims at reducing number of unjoined events, set UserEventRejoinScope to
/// UNJOINED_EVENTS. If the rejoining aims at correcting catalog information
/// in joined_events, set UserEventRejoinScope to JOINED_EVENTS. If all events
/// needs to be rejoined, set UserEventRejoinScope to
/// USER_EVENT_REJOIN_SCOPE_UNSPECIFIED.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
#[repr(i32)]
pub enum UserEventRejoinScope {
/// Rejoin catalogs with all events including both joined events and
/// unjoined events.
Unspecified = 0,
/// Only rejoin catalogs with joined events.
JoinedEvents = 1,
/// Only rejoin catalogs with unjoined events.
UnjoinedEvents = 2,
}
}
/// Response message for RejoinUserEvents method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct RejoinUserEventsResponse {
/// Number of user events that were joined with latest catalog items.
#[prost(int64, tag = "1")]
pub rejoined_user_events_count: i64,
}
/// Metadata for RejoinUserEvents method.
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct RejoinUserEventsMetadata {}
#[doc = r" Generated client implementations."]
pub mod user_event_service_client {
#![allow(unused_variables, dead_code, missing_docs)]
use tonic::codegen::*;
#[doc = " Service for ingesting end user actions on the customer website."]
pub struct UserEventServiceClient<T> {
inner: tonic::client::Grpc<T>,
}
impl<T> UserEventServiceClient<T>
where
T: tonic::client::GrpcService<tonic::body::BoxBody>,
T::ResponseBody: Body + HttpBody + Send + 'static,
T::Error: Into<StdError>,
<T::ResponseBody as HttpBody>::Error: Into<StdError> + Send,
{
pub fn new(inner: T) -> Self {
let inner = tonic::client::Grpc::new(inner);
Self { inner }
}
pub fn with_interceptor(inner: T, interceptor: impl Into<tonic::Interceptor>) -> Self {
let inner = tonic::client::Grpc::with_interceptor(inner, interceptor);
Self { inner }
}
#[doc = " Writes a single user event."]
pub async fn write_user_event(
&mut self,
request: impl tonic::IntoRequest<super::WriteUserEventRequest>,
) -> Result<tonic::Response<super::UserEvent>, tonic::Status> {
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/google.cloud.retail.v2.UserEventService/WriteUserEvent",
);
self.inner.unary(request.into_request(), path, codec).await
}
#[doc = " Writes a single user event from the browser. This uses a GET request to"]
#[doc = " due to browser restriction of POST-ing to a 3rd party domain."]
#[doc = ""]
#[doc = " This method is used only by the Recommendations AI JavaScript pixel and"]
#[doc = " Google Tag Manager. Users should not call this method directly."]
pub async fn collect_user_event(
&mut self,
request: impl tonic::IntoRequest<super::CollectUserEventRequest>,
) -> Result<tonic::Response<super::super::super::super::api::HttpBody>, tonic::Status>
{
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/google.cloud.retail.v2.UserEventService/CollectUserEvent",
);
self.inner.unary(request.into_request(), path, codec).await
}
#[doc = " Deletes permanently all user events specified by the filter provided."]
#[doc = " Depending on the number of events specified by the filter, this operation"]
#[doc = " could take hours or days to complete. To test a filter, use the list"]
#[doc = " command first."]
pub async fn purge_user_events(
&mut self,
request: impl tonic::IntoRequest<super::PurgeUserEventsRequest>,
) -> Result<
tonic::Response<super::super::super::super::longrunning::Operation>,
tonic::Status,
> {
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/google.cloud.retail.v2.UserEventService/PurgeUserEvents",
);
self.inner.unary(request.into_request(), path, codec).await
}
#[doc = " Bulk import of User events. Request processing might be"]
#[doc = " synchronous. Events that already exist are skipped."]
#[doc = " Use this method for backfilling historical user events."]
#[doc = ""]
#[doc = " Operation.response is of type ImportResponse. Note that it is"]
#[doc = " possible for a subset of the items to be successfully inserted."]
#[doc = " Operation.metadata is of type ImportMetadata."]
pub async fn import_user_events(
&mut self,
request: impl tonic::IntoRequest<super::ImportUserEventsRequest>,
) -> Result<
tonic::Response<super::super::super::super::longrunning::Operation>,
tonic::Status,
> {
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/google.cloud.retail.v2.UserEventService/ImportUserEvents",
);
self.inner.unary(request.into_request(), path, codec).await
}
#[doc = " Triggers a user event rejoin operation with latest catalog data. Events"]
#[doc = " will not be annotated with detailed catalog information if catalog item is"]
#[doc = " missing at the time the user event is ingested, and these events are stored"]
#[doc = " as unjoined events with a limited usage on training and serving. This API"]
#[doc = " can be used to trigger a 'join' operation on specified events with latest"]
#[doc = " version of catalog items. It can also be used to correct events joined with"]
#[doc = " wrong catalog items."]
pub async fn rejoin_user_events(
&mut self,
request: impl tonic::IntoRequest<super::RejoinUserEventsRequest>,
) -> Result<
tonic::Response<super::super::super::super::longrunning::Operation>,
tonic::Status,
> {
self.inner.ready().await.map_err(|e| {
tonic::Status::new(
tonic::Code::Unknown,
format!("Service was not ready: {}", e.into()),
)
})?;
let codec = tonic::codec::ProstCodec::default();
let path = http::uri::PathAndQuery::from_static(
"/google.cloud.retail.v2.UserEventService/RejoinUserEvents",
);
self.inner.unary(request.into_request(), path, codec).await
}
}
impl<T: Clone> Clone for UserEventServiceClient<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
impl<T> std::fmt::Debug for UserEventServiceClient<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "UserEventServiceClient {{ ... }}")
}
}
}
| 46.688913 | 112 | 0.641098 |
d79299bdc454981824082355397ac13b8d9c5b65 | 7,107 | use super::*;
use crate::process;
#[derive(Debug)]
struct PgrpInner {
pgid: pid_t,
process_group: HashMap<pid_t, ProcessRef>, // process id, process ref
leader_process: Option<ProcessRef>,
}
#[derive(Debug)]
pub struct ProcessGrp {
inner: RwLock<PgrpInner>,
}
impl ProcessGrp {
pub fn default() -> Self {
ProcessGrp {
inner: RwLock::new(PgrpInner {
pgid: 0,
process_group: HashMap::new(),
leader_process: None,
}),
}
}
pub fn pgid(&self) -> pid_t {
self.inner.read().unwrap().pgid
}
pub fn get_process_number(&self) -> usize {
self.inner.read().unwrap().process_group.len()
}
pub fn set_pgid(&self, pgid: pid_t) {
self.inner.write().unwrap().pgid = pgid;
}
pub fn leader_process_is_set(&self) -> bool {
self.inner.read().unwrap().leader_process.is_some()
}
pub fn get_leader_process(&self) -> Option<ProcessRef> {
self.inner.read().unwrap().leader_process.clone()
}
pub fn set_leader_process(&self, new_leader: ProcessRef) {
self.inner.write().unwrap().leader_process = Some(new_leader);
}
pub fn add_new_process(&self, process: ProcessRef) {
self.inner
.write()
.unwrap()
.process_group
.insert(process.pid(), process);
}
pub fn get_all_processes(&self) -> Vec<ProcessRef> {
self.inner
.read()
.unwrap()
.process_group
.values()
.cloned()
.collect()
}
// Create a new process group
pub fn new(process: ProcessRef) -> Result<Self> {
let pgrp = Self::default();
let pid = process.pid();
pgrp.set_pgid(pid);
pgrp.set_leader_process(process.clone());
pgrp.add_new_process(process);
Ok(pgrp)
}
// Create a new process group with given pid
pub fn new_with_pid(pid: pid_t) -> Result<Self> {
let leader_process = table::get_process(pid)?;
Self::new(leader_process)
}
// Remove process from process group when process exit
pub fn remove_process(&self, process: &ProcessRef) -> Result<isize> {
let pgid = self.pgid();
let leader_process_is_set = self.leader_process_is_set();
let pgrp_process_num = self.inner.read().unwrap().process_group.len();
let process_pid = process.pid();
if pgrp_process_num < 1 {
return_errno!(EINVAL, "This process group is empty");
}
let leader_process_pid = if leader_process_is_set {
Some(self.get_leader_process().unwrap().pid())
} else {
None
};
if pgrp_process_num == 1 {
table::del_pgrp(pgid);
}
{
// Release lock after removing to avoid deadlock
let mut process_group_inner = &mut self.inner.write().unwrap().process_group;
process_group_inner
.remove(&process_pid)
.ok_or_else(|| errno!(EINVAL, "This process doesn't belong to this pgrp"))?;
}
if leader_process_pid.is_some() && leader_process_pid.unwrap() == process.pid() {
self.inner.write().unwrap().leader_process = None;
}
return Ok(0);
}
}
pub fn do_getpgid(pid: pid_t) -> Result<pid_t> {
let process =
table::get_process(pid).map_err(|e| errno!(ESRCH, "pid does not match any process"))?;
Ok(process.pgid())
}
// do_setpgid can be called under two cases:
// 1. a running process is calling for itself
// 2. a parent process is calling for its children
// Thus, parent can't setpgid to child if it is executing and only can do that when creating
// it.
pub fn do_setpgid(pid: pid_t, pgid: pid_t, is_executing: bool) -> Result<isize> {
// If pid is zero, pid is the calling process's pid.
let pid = if pid == 0 {
super::do_getpid::do_getpid()
} else {
pid
};
// If pgid is zero, pgid is made the same as process ID specified by "pid"
let pgid = if pgid == 0 { pid } else { pgid };
debug!("setpgid: pid: {:?}, pgid: {:?}", pid, pgid);
let process = table::get_process(pid)?;
let current_pid = current!().process().pid();
// if setpgid to a pgroup other than self, the pgroup must exist
if pgid != pid && table::get_pgrp(pgid).is_err() {
return_errno!(EPERM, "process group not exist");
}
// can't setpgid to a running process other than self
if current_pid != pid && is_executing {
return_errno!(EACCES, "can't setpgid to a running child process");
}
if let Ok(pgrp) = table::get_pgrp(pgid) {
// pgrp exists
let pgrp_ref = process.pgrp();
pgrp_ref.remove_process(&process);
process.update_pgrp(pgrp.clone());
pgrp.add_new_process(process);
} else {
// pgrp not exist
if is_executing {
// First remove process from previous process group. New process
// setpgid doesn't need this. This is done for self only.
debug_assert!(current_pid == pid);
let pgrp_ref = process.pgrp();
pgrp_ref.remove_process(&process);
}
let pgrp_ref = Arc::new(ProcessGrp::new_with_pid(pid)?);
process.update_pgrp(pgrp_ref.clone());
table::add_pgrp(pgrp_ref);
}
Ok(0)
}
pub fn get_spawn_attribute_pgrp(spawn_attributes: Option<SpawnAttr>) -> Result<Option<pid_t>> {
if spawn_attributes.is_some() && spawn_attributes.unwrap().process_group.is_some() {
let pgid = spawn_attributes.unwrap().process_group.unwrap();
if pgid != 0 && table::get_pgrp(pgid).is_err() {
return_errno!(EPERM, "process group not exist");
} else {
return Ok(Some(pgid));
}
} else {
return Ok(None);
}
}
// Check process group attribute here before exec.
// This must be done after process is ready.
pub fn update_pgrp_for_new_process(
new_process_ref: &ProcessRef,
pgid: Option<pid_t>,
) -> Result<()> {
if let Some(pgid) = pgid {
if pgid == 0 {
// create a new process group and add self process
let pgrp_ref = Arc::new(ProcessGrp::new(new_process_ref.clone())?);
new_process_ref.update_pgrp(pgrp_ref.clone());
table::add_pgrp(pgrp_ref);
} else {
// pgrp must exist when updating
let pgrp = table::get_pgrp(pgid).unwrap();
new_process_ref.update_pgrp(pgrp.clone());
pgrp.add_new_process(new_process_ref.clone());
}
} else {
// By default, new process's process group is same as its parent.
let pgrp_ref = new_process_ref.pgrp();
pgrp_ref.add_new_process(new_process_ref.clone());
}
Ok(())
}
pub fn clean_pgrp_when_exit(process: &ProcessRef) {
let pgrp_ref = process.pgrp();
// Remove process from pgrp
pgrp_ref.remove_process(process);
// Remove pgrp info from process
process.remove_pgrp();
}
| 31.034934 | 95 | 0.595469 |
fe0bfc033213de77f2b4ba6df4c6136ad890e184 | 637 | struct Nil;
struct Pair(i32, f32);
struct Point {
x: f32,
y: f32,
}
#[allow(dead_code)]
struct Rectangle {
p1: Point,
p2: Point,
}
fn main() {
let point: Point = Point {x: 0.3, y: 0.4};
println!("point coordinates: ({}, {})", point.x, point.y);
let Point { x: my_x, y: my_y } = point;
let _rectangle = Rectangle {
p1: Point { x: my_y, y: my_x },
p2: point,
};
let _nil = Nil;
let pair = Pair(1, 0.1);
println!("Pair contains {:?} and {:?}", pair.0, pair.1);
let Pair(integer, decimal) = pair;
println!("pair contains {:?} and {:?}", integer, decimal);
}
| 17.216216 | 62 | 0.530612 |
d717e0dfc23c396fd54d720c0b358bbf60f11ef3 | 1,735 | use std::io::{Read, Bytes};
use crate::parser::{Parser, Action};
pub struct ReaderParser<R: Read> {
inner: Option<Bytes<R>>,
parser: Parser,
stashed: Option<u8>,
}
impl<R: Read> Iterator for ReaderParser<R> {
type Item = Action;
fn next(&mut self) -> Option<Self::Item> {
let mut c = None;
loop {
if c.is_none() {
c = if let Some(c) = self.stashed.take() {
Some(c)
} else if let Some(mut inner) = self.inner.take() {
match inner.next() {
Some(Ok(c)) => {
self.inner = Some(inner); // restore inner iterator
Some(c)
}
Some(Err(e)) => {
return Some(Action::InputError(e));
}
None => None,
}
} else {
None
};
}
if let Some(action) = self.parser.step(&mut c) {
if let Some(unused_char) = c {
// if the parser didn't use the character, stash it for next time around.
self.stashed = Some(unused_char);
}
if let Action::Eof = action {
self.inner = None;
return None;
} else {
return Some(action);
}
}
}
}
}
impl<R: Read> ReaderParser<R> {
pub fn new(input: R) -> Self {
Self {
inner: Some(input.bytes()),
parser: Parser::default(),
stashed: None,
}
}
}
| 28.916667 | 93 | 0.39366 |
e9b22d12e11cc986e434b9cbb602769f0348d4f6 | 5,351 | //!
//! # Calculator:
//!
//! Given an arithmetic equation consisting of positive integers, +, -, * and / (no parentheses), compute the result.
//!
//! EXAMPLE
//!
//! Input: 2*3+5/6*3+15
//! Output: 23.5
//!
//! Hints: #527, #624, #665, #698
//!
use std::str::Chars;
// Every parser's favorite example.
//
// While the CtCI solutions use a more direct, targeted approach,
// this solution does what a general-purpose parser and evaluator would:
// Read the source into a (binary) expression-tree,
// then in a separate step evaluate the tree to a numeric result.
/// Enumerated, Supported Binary Operations
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinOp {
Add,
Sub,
Mul,
Div,
}
/// Arithmetic Expression Enumeration
#[derive(Debug, Clone)]
pub enum Expr {
Num(f64),
BinOp {
left: Box<Expr>,
op: BinOp,
right: Box<Expr>,
},
}
/// Primary Implementation
///
/// Parse the source string into an [Expr] tree,
/// and then evaluate the tree to a numeric result.
///
pub fn calculator(src: &str) -> Result<f64, Error> {
let expr = Parser::parse(src)?;
let rv = eval(&expr);
Ok(rv)
}
/// Expression Parser
///
/// Creates an [Expr] tree from a source string.
/// Traditional lexing and parsing are generally intertwined here;
/// this object does both, without an explicit Token stream or type.
///
struct Parser<'src> {
chars: Chars<'src>,
next: Option<char>,
}
impl<'src> Parser<'src> {
/// Primary Entry Point. Parse source-string `src`.
pub fn parse(src: &str) -> Result<Expr, Error> {
let mut parser = Parser::new(src);
parser.parse_expr()
}
/// Create a new parser over `src`.
fn new(src: &'src str) -> Self {
let mut chars = src.chars();
let next = chars.next();
Self { chars, next }
}
/// Parse an [Expr], as a cascade of additions and subtractions
fn parse_expr(&mut self) -> Result<Expr, Error> {
// Parse an initial term
let mut expr = self.parse_term()?;
// And expand across any additions and subtractions
while let Some('+') | Some('-') = self.peek() {
let op = self.parse_op()?;
let right = self.parse_term()?;
expr = Expr::BinOp {
op,
left: Box::new(expr),
right: Box::new(right),
}
}
Ok(expr)
}
/// Parse a cascade of multiplies and divides
fn parse_term(&mut self) -> Result<Expr, Error> {
// Parse an initial number
let mut expr = self.parse_num()?;
// And expand across any additions and subtractions
while let Some('*') | Some('/') = self.peek() {
let op = self.parse_op()?;
let right = self.parse_num()?;
expr = Expr::BinOp {
op,
left: Box::new(expr),
right: Box::new(right),
}
}
Ok(expr)
}
/// Parse a numeric value
fn parse_num(&mut self) -> Result<Expr, Error> {
let mut chars = Vec::new();
while let Some(c) = self.peek() {
if c.is_digit(10) {
chars.push(*c);
self.advance();
} else {
break;
}
}
let s: String = chars.into_iter().collect();
let f = s.parse::<f64>().unwrap();
Ok(Expr::Num(f))
}
/// Parse an operator to a [BinOp]
fn parse_op(&mut self) -> Result<BinOp, Error> {
let op = match self.peek() {
Some('+') => Ok(BinOp::Add),
Some('-') => Ok(BinOp::Sub),
Some('*') => Ok(BinOp::Mul),
Some('/') => Ok(BinOp::Div),
_ => Err(Error),
}?;
// Advance, only in the non-error cases
self.advance();
// And return the operator
Ok(op)
}
/// Peek at (a reference to) the next character
fn peek(&self) -> &Option<char> {
&self.next
}
/// Advance a character. Returns a reference to the new `next`.
fn advance(&mut self) -> &Option<char> {
self.next = self.chars.next();
self.peek()
}
}
/// Evaluate potentially-nested expression `expr`
fn eval(expr: &Expr) -> f64 {
match expr {
Expr::Num(num) => *num, // Numbers are "already evaluated"
Expr::BinOp {
op,
ref left,
ref right,
} => {
// Recursively evaluate the left and right sides
let left = eval(left);
let right = eval(right);
// And apply the operator
match op {
BinOp::Add => left + right,
BinOp::Sub => left - right,
BinOp::Mul => left * right,
BinOp::Div => left / right,
}
}
}
}
#[test]
fn test_calculator() {
let s = "1";
assert_eq!(calculator(&s).unwrap(), 1.0);
let s = "1+2";
assert_eq!(calculator(&s).unwrap(), 3.0);
let s = "1+2*3";
assert_eq!(calculator(&s).unwrap(), 7.0);
let s = "1*2+3";
assert_eq!(calculator(&s).unwrap(), 5.0);
let s = "2*3+5/6*3+15";
assert_eq!(calculator(&s).unwrap(), 23.5);
let s = "2-6-7*8/2+5";
assert_eq!(calculator(&s).unwrap(), -27.);
}
/// Local Error Type
#[derive(Debug)]
pub struct Error;
| 28.015707 | 117 | 0.526631 |
cc5ce5382eff0f581f67337c3013846c0930e63b | 785 | use efm32gg_hal::gpio;
use embedded_hal::digital::InputPin;
use efm32gg_hal::gpio::EFM32Pin;
pub struct Buttons {
button0: gpio::pins::PB9<gpio::Input>,
button1: gpio::pins::PB10<gpio::Input>,
}
/// A representation of the two user buttons on the STK3700
impl Buttons {
pub fn new(pb9: gpio::pins::PB9<gpio::Disabled>, pb10: gpio::pins::PB10<gpio::Disabled>) -> Self {
Buttons { button0: pb9.as_input(), button1: pb10.as_input() }
}
/// Return true if PB0 in depressed state at the time of the invocation.
pub fn button0_pressed(&self) -> bool
{
self.button0.is_low()
}
/// Return true if PB1 in depressed state at the time of the invocation.
pub fn button1_pressed(&self) -> bool
{
self.button1.is_low()
}
}
| 28.035714 | 102 | 0.652229 |
dd69d358313181b66690daf5c06aff76fbe2ce29 | 30,699 | use rustc::ty::{self, Ty, TypeFoldable, UpvarSubsts, Instance};
use rustc::ty::layout::{TyLayout, HasTyCtxt, FnTypeExt};
use rustc::mir::{self, Body};
use rustc::session::config::DebugInfo;
use rustc_target::abi::call::{FnType, PassMode, IgnoreMode};
use rustc_target::abi::{Variants, VariantIdx};
use crate::base;
use crate::debuginfo::{self, VariableAccess, VariableKind, FunctionDebugContext};
use crate::traits::*;
use syntax_pos::{DUMMY_SP, NO_EXPANSION, BytePos, Span};
use syntax::symbol::kw;
use std::iter;
use rustc_data_structures::bit_set::BitSet;
use rustc_data_structures::indexed_vec::IndexVec;
use self::analyze::CleanupKind;
use self::place::PlaceRef;
use rustc::mir::traversal;
use self::operand::{OperandRef, OperandValue};
/// Master context for codegenning from MIR.
pub struct FunctionCx<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>> {
instance: Instance<'tcx>,
mir: &'a mir::Body<'tcx>,
debug_context: FunctionDebugContext<Bx::DIScope>,
llfn: Bx::Value,
cx: &'a Bx::CodegenCx,
fn_ty: FnType<'tcx, Ty<'tcx>>,
/// When unwinding is initiated, we have to store this personality
/// value somewhere so that we can load it and re-use it in the
/// resume instruction. The personality is (afaik) some kind of
/// value used for C++ unwinding, which must filter by type: we
/// don't really care about it very much. Anyway, this value
/// contains an alloca into which the personality is stored and
/// then later loaded when generating the DIVERGE_BLOCK.
personality_slot: Option<PlaceRef<'tcx, Bx::Value,>>,
/// A `Block` for each MIR `BasicBlock`
blocks: IndexVec<mir::BasicBlock, Bx::BasicBlock>,
/// The funclet status of each basic block
cleanup_kinds: IndexVec<mir::BasicBlock, analyze::CleanupKind>,
/// When targeting MSVC, this stores the cleanup info for each funclet
/// BB. This is initialized as we compute the funclets' head block in RPO.
funclets: IndexVec<mir::BasicBlock, Option<Bx::Funclet>>,
/// This stores the landing-pad block for a given BB, computed lazily on GNU
/// and eagerly on MSVC.
landing_pads: IndexVec<mir::BasicBlock, Option<Bx::BasicBlock>>,
/// Cached unreachable block
unreachable_block: Option<Bx::BasicBlock>,
/// The location where each MIR arg/var/tmp/ret is stored. This is
/// usually an `PlaceRef` representing an alloca, but not always:
/// sometimes we can skip the alloca and just store the value
/// directly using an `OperandRef`, which makes for tighter LLVM
/// IR. The conditions for using an `OperandRef` are as follows:
///
/// - the type of the local must be judged "immediate" by `is_llvm_immediate`
/// - the operand must never be referenced indirectly
/// - we should not take its address using the `&` operator
/// - nor should it appear in a place path like `tmp.a`
/// - the operand must be defined by an rvalue that can generate immediate
/// values
///
/// Avoiding allocs can also be important for certain intrinsics,
/// notably `expect`.
locals: IndexVec<mir::Local, LocalRef<'tcx, Bx::Value>>,
/// Debug information for MIR scopes.
scopes: IndexVec<mir::SourceScope, debuginfo::MirDebugScope<Bx::DIScope>>,
/// If this function is a C-variadic function, this contains the `PlaceRef` of the
/// "spoofed" `VaList`.
va_list_ref: Option<PlaceRef<'tcx, Bx::Value>>,
}
impl<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
pub fn monomorphize<T>(&self, value: &T) -> T
where T: TypeFoldable<'tcx>
{
self.cx.tcx().subst_and_normalize_erasing_regions(
self.instance.substs,
ty::ParamEnv::reveal_all(),
value,
)
}
pub fn set_debug_loc(
&mut self,
bx: &mut Bx,
source_info: mir::SourceInfo
) {
let (scope, span) = self.debug_loc(source_info);
bx.set_source_location(&mut self.debug_context, scope, span);
}
pub fn debug_loc(&self, source_info: mir::SourceInfo) -> (Option<Bx::DIScope>, Span) {
// Bail out if debug info emission is not enabled.
match self.debug_context {
FunctionDebugContext::DebugInfoDisabled |
FunctionDebugContext::FunctionWithoutDebugInfo => {
return (self.scopes[source_info.scope].scope_metadata, source_info.span);
}
FunctionDebugContext::RegularContext(_) =>{}
}
// In order to have a good line stepping behavior in debugger, we overwrite debug
// locations of macro expansions with that of the outermost expansion site
// (unless the crate is being compiled with `-Z debug-macros`).
if source_info.span.ctxt() == NO_EXPANSION ||
self.cx.sess().opts.debugging_opts.debug_macros {
let scope = self.scope_metadata_for_loc(source_info.scope, source_info.span.lo());
(scope, source_info.span)
} else {
// Walk up the macro expansion chain until we reach a non-expanded span.
// We also stop at the function body level because no line stepping can occur
// at the level above that.
let span = syntax_pos::hygiene::walk_chain(source_info.span, self.mir.span.ctxt());
let scope = self.scope_metadata_for_loc(source_info.scope, span.lo());
// Use span of the outermost expansion site, while keeping the original lexical scope.
(scope, span)
}
}
// DILocations inherit source file name from the parent DIScope. Due to macro expansions
// it may so happen that the current span belongs to a different file than the DIScope
// corresponding to span's containing source scope. If so, we need to create a DIScope
// "extension" into that file.
fn scope_metadata_for_loc(&self, scope_id: mir::SourceScope, pos: BytePos)
-> Option<Bx::DIScope> {
let scope_metadata = self.scopes[scope_id].scope_metadata;
if pos < self.scopes[scope_id].file_start_pos ||
pos >= self.scopes[scope_id].file_end_pos {
let sm = self.cx.sess().source_map();
let defining_crate = self.debug_context.get_ref(DUMMY_SP).defining_crate;
Some(self.cx.extend_scope_to_file(
scope_metadata.unwrap(),
&sm.lookup_char_pos(pos).file,
defining_crate
))
} else {
scope_metadata
}
}
}
enum LocalRef<'tcx, V> {
Place(PlaceRef<'tcx, V>),
/// `UnsizedPlace(p)`: `p` itself is a thin pointer (indirect place).
/// `*p` is the fat pointer that references the actual unsized place.
/// Every time it is initialized, we have to reallocate the place
/// and update the fat pointer. That's the reason why it is indirect.
UnsizedPlace(PlaceRef<'tcx, V>),
Operand(Option<OperandRef<'tcx, V>>),
}
impl<'a, 'tcx: 'a, V: CodegenObject> LocalRef<'tcx, V> {
fn new_operand<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
bx: &mut Bx,
layout: TyLayout<'tcx>,
) -> LocalRef<'tcx, V> {
if layout.is_zst() {
// Zero-size temporaries aren't always initialized, which
// doesn't matter because they don't contain data, but
// we need something in the operand.
LocalRef::Operand(Some(OperandRef::new_zst(bx, layout)))
} else {
LocalRef::Operand(None)
}
}
}
///////////////////////////////////////////////////////////////////////////
pub fn codegen_mir<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
cx: &'a Bx::CodegenCx,
llfn: Bx::Value,
mir: &'a Body<'tcx>,
instance: Instance<'tcx>,
sig: ty::FnSig<'tcx>,
) {
assert!(!instance.substs.needs_infer());
let fn_ty = FnType::new(cx, sig, &[]);
debug!("fn_ty: {:?}", fn_ty);
let mut debug_context =
cx.create_function_debug_context(instance, sig, llfn, mir);
let mut bx = Bx::new_block(cx, llfn, "start");
if mir.basic_blocks().iter().any(|bb| bb.is_cleanup) {
bx.set_personality_fn(cx.eh_personality());
}
let cleanup_kinds = analyze::cleanup_kinds(&mir);
// Allocate a `Block` for every basic block, except
// the start block, if nothing loops back to it.
let reentrant_start_block = !mir.predecessors_for(mir::START_BLOCK).is_empty();
let block_bxs: IndexVec<mir::BasicBlock, Bx::BasicBlock> =
mir.basic_blocks().indices().map(|bb| {
if bb == mir::START_BLOCK && !reentrant_start_block {
bx.llbb()
} else {
bx.build_sibling_block(&format!("{:?}", bb)).llbb()
}
}).collect();
// Compute debuginfo scopes from MIR scopes.
let scopes = cx.create_mir_scopes(mir, &mut debug_context);
let (landing_pads, funclets) = create_funclets(mir, &mut bx, &cleanup_kinds, &block_bxs);
let mut fx = FunctionCx {
instance,
mir,
llfn,
fn_ty,
cx,
personality_slot: None,
blocks: block_bxs,
unreachable_block: None,
cleanup_kinds,
landing_pads,
funclets,
scopes,
locals: IndexVec::new(),
debug_context,
va_list_ref: None,
};
let memory_locals = analyze::non_ssa_locals(&fx);
// Allocate variable and temp allocas
fx.locals = {
// FIXME(dlrobertson): This is ugly. Find a better way of getting the `PlaceRef` or
// `LocalRef` from `arg_local_refs`
let mut va_list_ref = None;
let args = arg_local_refs(&mut bx, &fx, &memory_locals, &mut va_list_ref);
fx.va_list_ref = va_list_ref;
let mut allocate_local = |local| {
let decl = &mir.local_decls[local];
let layout = bx.layout_of(fx.monomorphize(&decl.ty));
assert!(!layout.ty.has_erasable_regions());
if let Some(name) = decl.name {
// User variable
let debug_scope = fx.scopes[decl.visibility_scope];
let dbg = debug_scope.is_valid() &&
bx.sess().opts.debuginfo == DebugInfo::Full;
if !memory_locals.contains(local) && !dbg {
debug!("alloc: {:?} ({}) -> operand", local, name);
return LocalRef::new_operand(&mut bx, layout);
}
debug!("alloc: {:?} ({}) -> place", local, name);
if layout.is_unsized() {
let indirect_place =
PlaceRef::alloca_unsized_indirect(&mut bx, layout, &name.as_str());
// FIXME: add an appropriate debuginfo
LocalRef::UnsizedPlace(indirect_place)
} else {
let place = PlaceRef::alloca(&mut bx, layout, &name.as_str());
if dbg {
let (scope, span) = fx.debug_loc(mir::SourceInfo {
span: decl.source_info.span,
scope: decl.visibility_scope,
});
bx.declare_local(&fx.debug_context, name, layout.ty, scope.unwrap(),
VariableAccess::DirectVariable { alloca: place.llval },
VariableKind::LocalVariable, span);
}
LocalRef::Place(place)
}
} else {
// Temporary or return place
if local == mir::RETURN_PLACE && fx.fn_ty.ret.is_indirect() {
debug!("alloc: {:?} (return place) -> place", local);
let llretptr = bx.get_param(0);
LocalRef::Place(PlaceRef::new_sized(llretptr, layout, layout.align.abi))
} else if memory_locals.contains(local) {
debug!("alloc: {:?} -> place", local);
if layout.is_unsized() {
let indirect_place = PlaceRef::alloca_unsized_indirect(
&mut bx,
layout,
&format!("{:?}", local),
);
LocalRef::UnsizedPlace(indirect_place)
} else {
LocalRef::Place(PlaceRef::alloca(&mut bx, layout, &format!("{:?}", local)))
}
} else {
// If this is an immediate local, we do not create an
// alloca in advance. Instead we wait until we see the
// definition and update the operand there.
debug!("alloc: {:?} -> operand", local);
LocalRef::new_operand(&mut bx, layout)
}
}
};
let retptr = allocate_local(mir::RETURN_PLACE);
iter::once(retptr)
.chain(args.into_iter())
.chain(mir.vars_and_temps_iter().map(allocate_local))
.collect()
};
// Branch to the START block, if it's not the entry block.
if reentrant_start_block {
bx.br(fx.blocks[mir::START_BLOCK]);
}
// Up until here, IR instructions for this function have explicitly not been annotated with
// source code location, so we don't step into call setup code. From here on, source location
// emitting should be enabled.
debuginfo::start_emitting_source_locations(&mut fx.debug_context);
let rpo = traversal::reverse_postorder(&mir);
let mut visited = BitSet::new_empty(mir.basic_blocks().len());
// Codegen the body of each block using reverse postorder
for (bb, _) in rpo {
visited.insert(bb.index());
fx.codegen_block(bb);
}
// Remove blocks that haven't been visited, or have no
// predecessors.
for bb in mir.basic_blocks().indices() {
// Unreachable block
if !visited.contains(bb.index()) {
debug!("codegen_mir: block {:?} was not visited", bb);
unsafe {
bx.delete_basic_block(fx.blocks[bb]);
}
}
}
}
fn create_funclets<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
mir: &'a Body<'tcx>,
bx: &mut Bx,
cleanup_kinds: &IndexVec<mir::BasicBlock, CleanupKind>,
block_bxs: &IndexVec<mir::BasicBlock, Bx::BasicBlock>)
-> (IndexVec<mir::BasicBlock, Option<Bx::BasicBlock>>,
IndexVec<mir::BasicBlock, Option<Bx::Funclet>>)
{
block_bxs.iter_enumerated().zip(cleanup_kinds).map(|((bb, &llbb), cleanup_kind)| {
match *cleanup_kind {
CleanupKind::Funclet if base::wants_msvc_seh(bx.sess()) => {}
_ => return (None, None)
}
let funclet;
let ret_llbb;
match mir[bb].terminator.as_ref().map(|t| &t.kind) {
// This is a basic block that we're aborting the program for,
// notably in an `extern` function. These basic blocks are inserted
// so that we assert that `extern` functions do indeed not panic,
// and if they do we abort the process.
//
// On MSVC these are tricky though (where we're doing funclets). If
// we were to do a cleanuppad (like below) the normal functions like
// `longjmp` would trigger the abort logic, terminating the
// program. Instead we insert the equivalent of `catch(...)` for C++
// which magically doesn't trigger when `longjmp` files over this
// frame.
//
// Lots more discussion can be found on #48251 but this codegen is
// modeled after clang's for:
//
// try {
// foo();
// } catch (...) {
// bar();
// }
Some(&mir::TerminatorKind::Abort) => {
let mut cs_bx = bx.build_sibling_block(&format!("cs_funclet{:?}", bb));
let mut cp_bx = bx.build_sibling_block(&format!("cp_funclet{:?}", bb));
ret_llbb = cs_bx.llbb();
let cs = cs_bx.catch_switch(None, None, 1);
cs_bx.add_handler(cs, cp_bx.llbb());
// The "null" here is actually a RTTI type descriptor for the
// C++ personality function, but `catch (...)` has no type so
// it's null. The 64 here is actually a bitfield which
// represents that this is a catch-all block.
let null = bx.const_null(bx.type_i8p());
let sixty_four = bx.const_i32(64);
funclet = cp_bx.catch_pad(cs, &[null, sixty_four, null]);
cp_bx.br(llbb);
}
_ => {
let mut cleanup_bx = bx.build_sibling_block(&format!("funclet_{:?}", bb));
ret_llbb = cleanup_bx.llbb();
funclet = cleanup_bx.cleanup_pad(None, &[]);
cleanup_bx.br(llbb);
}
};
(Some(ret_llbb), Some(funclet))
}).unzip()
}
/// Produces, for each argument, a `Value` pointing at the
/// argument's value. As arguments are places, these are always
/// indirect.
fn arg_local_refs<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
bx: &mut Bx,
fx: &FunctionCx<'a, 'tcx, Bx>,
memory_locals: &BitSet<mir::Local>,
va_list_ref: &mut Option<PlaceRef<'tcx, Bx::Value>>,
) -> Vec<LocalRef<'tcx, Bx::Value>> {
let mir = fx.mir;
let tcx = fx.cx.tcx();
let mut idx = 0;
let mut llarg_idx = fx.fn_ty.ret.is_indirect() as usize;
// Get the argument scope, if it exists and if we need it.
let arg_scope = fx.scopes[mir::OUTERMOST_SOURCE_SCOPE];
let arg_scope = if bx.sess().opts.debuginfo == DebugInfo::Full {
arg_scope.scope_metadata
} else {
None
};
// Store the index of the last argument. This is used to
// call va_start on the va_list instead of attempting
// to store_fn_arg.
let last_arg_idx = if fx.fn_ty.args.is_empty() {
None
} else {
Some(fx.fn_ty.args.len() - 1)
};
mir.args_iter().enumerate().map(|(arg_index, local)| {
let arg_decl = &mir.local_decls[local];
let name = if let Some(name) = arg_decl.name {
name.as_str().to_string()
} else {
format!("arg{}", arg_index)
};
if Some(local) == mir.spread_arg {
// This argument (e.g., the last argument in the "rust-call" ABI)
// is a tuple that was spread at the ABI level and now we have
// to reconstruct it into a tuple local variable, from multiple
// individual LLVM function arguments.
let arg_ty = fx.monomorphize(&arg_decl.ty);
let tupled_arg_tys = match arg_ty.sty {
ty::Tuple(ref tys) => tys,
_ => bug!("spread argument isn't a tuple?!")
};
let place = PlaceRef::alloca(bx, bx.layout_of(arg_ty), &name);
for i in 0..tupled_arg_tys.len() {
let arg = &fx.fn_ty.args[idx];
idx += 1;
if arg.pad.is_some() {
llarg_idx += 1;
}
let pr_field = place.project_field(bx, i);
bx.store_fn_arg(arg, &mut llarg_idx, pr_field);
}
// Now that we have one alloca that contains the aggregate value,
// we can create one debuginfo entry for the argument.
arg_scope.map(|scope| {
let variable_access = VariableAccess::DirectVariable {
alloca: place.llval
};
bx.declare_local(
&fx.debug_context,
arg_decl.name.unwrap_or(kw::Invalid),
arg_ty, scope,
variable_access,
VariableKind::ArgumentVariable(arg_index + 1),
DUMMY_SP
);
});
return LocalRef::Place(place);
}
let arg = &fx.fn_ty.args[idx];
idx += 1;
if arg.pad.is_some() {
llarg_idx += 1;
}
if arg_scope.is_none() && !memory_locals.contains(local) {
// We don't have to cast or keep the argument in the alloca.
// FIXME(eddyb): We should figure out how to use llvm.dbg.value instead
// of putting everything in allocas just so we can use llvm.dbg.declare.
let local = |op| LocalRef::Operand(Some(op));
match arg.mode {
PassMode::Ignore(IgnoreMode::Zst) => {
return local(OperandRef::new_zst(bx, arg.layout));
}
PassMode::Ignore(IgnoreMode::CVarArgs) => {}
PassMode::Direct(_) => {
let llarg = bx.get_param(llarg_idx);
bx.set_value_name(llarg, &name);
llarg_idx += 1;
return local(
OperandRef::from_immediate_or_packed_pair(bx, llarg, arg.layout));
}
PassMode::Pair(..) => {
let a = bx.get_param(llarg_idx);
bx.set_value_name(a, &(name.clone() + ".0"));
llarg_idx += 1;
let b = bx.get_param(llarg_idx);
bx.set_value_name(b, &(name + ".1"));
llarg_idx += 1;
return local(OperandRef {
val: OperandValue::Pair(a, b),
layout: arg.layout
});
}
_ => {}
}
}
let place = if arg.is_sized_indirect() {
// Don't copy an indirect argument to an alloca, the caller
// already put it in a temporary alloca and gave it up.
// FIXME: lifetimes
let llarg = bx.get_param(llarg_idx);
bx.set_value_name(llarg, &name);
llarg_idx += 1;
PlaceRef::new_sized(llarg, arg.layout, arg.layout.align.abi)
} else if arg.is_unsized_indirect() {
// As the storage for the indirect argument lives during
// the whole function call, we just copy the fat pointer.
let llarg = bx.get_param(llarg_idx);
llarg_idx += 1;
let llextra = bx.get_param(llarg_idx);
llarg_idx += 1;
let indirect_operand = OperandValue::Pair(llarg, llextra);
let tmp = PlaceRef::alloca_unsized_indirect(bx, arg.layout, &name);
indirect_operand.store(bx, tmp);
tmp
} else {
if fx.fn_ty.c_variadic && last_arg_idx.map(|idx| arg_index == idx).unwrap_or(false) {
let va_list_impl = match arg_decl.ty.ty_adt_def() {
Some(adt) => adt.non_enum_variant(),
None => bug!("`va_list` language item improperly constructed")
};
match tcx.type_of(va_list_impl.fields[0].did).sty {
ty::Ref(_, ty, _) => {
// If the underlying structure the `VaList` contains is a structure,
// we need to allocate it (e.g., X86_64 on Linux).
let tmp = PlaceRef::alloca(bx, arg.layout, &name);
if let ty::Adt(..) = ty.sty {
let layout = bx.layout_of(ty);
// Create an unnamed allocation for the backing structure
// and store it in the the spoofed `VaList`.
let backing = PlaceRef::alloca(bx, layout, "");
bx.store(backing.llval, tmp.llval, layout.align.abi);
}
// Call `va_start` on the spoofed `VaList`.
bx.va_start(tmp.llval);
*va_list_ref = Some(tmp);
tmp
}
_ => bug!("improperly constructed `va_list` lang item"),
}
} else {
let tmp = PlaceRef::alloca(bx, arg.layout, &name);
bx.store_fn_arg(arg, &mut llarg_idx, tmp);
tmp
}
};
let upvar_debuginfo = &mir.__upvar_debuginfo_codegen_only_do_not_use;
arg_scope.map(|scope| {
// Is this a regular argument?
if arg_index > 0 || upvar_debuginfo.is_empty() {
// The Rust ABI passes indirect variables using a pointer and a manual copy, so we
// need to insert a deref here, but the C ABI uses a pointer and a copy using the
// byval attribute, for which LLVM always does the deref itself,
// so we must not add it.
let variable_access = VariableAccess::DirectVariable {
alloca: place.llval
};
bx.declare_local(
&fx.debug_context,
arg_decl.name.unwrap_or(kw::Invalid),
arg.layout.ty,
scope,
variable_access,
VariableKind::ArgumentVariable(arg_index + 1),
DUMMY_SP
);
return;
}
let pin_did = tcx.lang_items().pin_type();
// Or is it the closure environment?
let (closure_layout, env_ref) = match arg.layout.ty.sty {
ty::RawPtr(ty::TypeAndMut { ty, .. }) |
ty::Ref(_, ty, _) => (bx.layout_of(ty), true),
ty::Adt(def, substs) if Some(def.did) == pin_did => {
match substs.type_at(0).sty {
ty::Ref(_, ty, _) => (bx.layout_of(ty), true),
_ => (arg.layout, false),
}
}
_ => (arg.layout, false)
};
let (def_id, upvar_substs) = match closure_layout.ty.sty {
ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs)),
ty::Generator(def_id, substs, _) => (def_id, UpvarSubsts::Generator(substs)),
_ => bug!("upvar debuginfo with non-closure arg0 type `{}`", closure_layout.ty)
};
let upvar_tys = upvar_substs.upvar_tys(def_id, tcx);
let extra_locals = {
let upvars = upvar_debuginfo
.iter()
.zip(upvar_tys)
.enumerate()
.map(|(i, (upvar, ty))| {
(None, i, upvar.debug_name, upvar.by_ref, ty, scope, DUMMY_SP)
});
let generator_fields = mir.generator_layout.as_ref().map(|generator_layout| {
let (def_id, gen_substs) = match closure_layout.ty.sty {
ty::Generator(def_id, substs, _) => (def_id, substs),
_ => bug!("generator layout without generator substs"),
};
let state_tys = gen_substs.state_tys(def_id, tcx);
generator_layout.variant_fields.iter()
.zip(state_tys)
.enumerate()
.flat_map(move |(variant_idx, (fields, tys))| {
let variant_idx = Some(VariantIdx::from(variant_idx));
fields.iter()
.zip(tys)
.enumerate()
.filter_map(move |(i, (field, ty))| {
let decl = &generator_layout.
__local_debuginfo_codegen_only_do_not_use[*field];
if let Some(name) = decl.name {
let ty = fx.monomorphize(&ty);
let (var_scope, var_span) = fx.debug_loc(mir::SourceInfo {
span: decl.source_info.span,
scope: decl.visibility_scope,
});
let var_scope = var_scope.unwrap_or(scope);
Some((variant_idx, i, name, false, ty, var_scope, var_span))
} else {
None
}
})
})
}).into_iter().flatten();
upvars.chain(generator_fields)
};
for (variant_idx, field, name, by_ref, ty, var_scope, var_span) in extra_locals {
let fields = match variant_idx {
Some(variant_idx) => {
match &closure_layout.variants {
Variants::Multiple { variants, .. } => {
&variants[variant_idx].fields
},
_ => bug!("variant index on univariant layout"),
}
}
None => &closure_layout.fields,
};
let byte_offset_of_var_in_env = fields.offset(field).bytes();
let ops = bx.debuginfo_upvar_ops_sequence(byte_offset_of_var_in_env);
// The environment and the capture can each be indirect.
let mut ops = if env_ref { &ops[..] } else { &ops[1..] };
let ty = if let (true, &ty::Ref(_, ty, _)) = (by_ref, &ty.sty) {
ty
} else {
ops = &ops[..ops.len() - 1];
ty
};
let variable_access = VariableAccess::IndirectVariable {
alloca: place.llval,
address_operations: &ops
};
bx.declare_local(
&fx.debug_context,
name,
ty,
var_scope,
variable_access,
VariableKind::LocalVariable,
var_span
);
}
});
if arg.is_unsized_indirect() {
LocalRef::UnsizedPlace(place)
} else {
LocalRef::Place(place)
}
}).collect()
}
mod analyze;
mod block;
pub mod constant;
pub mod place;
pub mod operand;
mod rvalue;
mod statement;
| 41.485135 | 100 | 0.528649 |
5080312ffb48a95d23e3e08a4e0f59280a9a3915 | 3,874 | //! Totalização dos produtos e serviços
use super::Error;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::str::FromStr;
/// Totalização da nota fiscal
#[derive(Debug, PartialEq, Clone)]
pub struct Totalizacao {
/// Base de cálculo do ICMS
pub valor_base_calculo: f32,
/// Valor total do ICMS
pub valor_icms: f32,
/// Valor total dos produtos e serviços
pub valor_produtos: f32,
/// Valor total do frete
pub valor_frete: f32,
/// Valor total do seguro
pub valor_seguro: f32,
/// Valor total do desconto
pub valor_desconto: f32,
/// Outras despesas acessórias
pub valor_outros: f32,
/// Valor total do PIS
pub valor_pis: f32,
/// Valor total do COFINS
pub valor_cofins: f32,
/// Valor total da nota
pub valor_total: f32,
/// Valor aproximado total de tributos federais, estaduais e municipais.
pub valor_aproximado_tributos: f32,
}
impl FromStr for Totalizacao {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
quick_xml::de::from_str(s).map_err(|e| e.into())
}
}
impl ToString for Totalizacao {
fn to_string(&self) -> String {
quick_xml::se::to_string(self).expect("Falha ao serializar a totalização")
}
}
impl Serialize for Totalizacao {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let icms = IcmsTot {
valor_base_calculo: self.valor_base_calculo,
valor_icms: self.valor_icms,
valor_produtos: self.valor_produtos,
valor_frete: self.valor_frete,
valor_seguro: self.valor_seguro,
valor_desconto: self.valor_desconto,
valor_outros: self.valor_outros,
valor_pis: self.valor_pis,
valor_cofins: self.valor_cofins,
valor_total: self.valor_total,
valor_aproximado_tributos: self.valor_aproximado_tributos,
};
let total = TotalContainer { icms };
total.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for Totalizacao {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let helper = TotalContainer::deserialize(deserializer)?;
Ok(Totalizacao {
valor_base_calculo: helper.icms.valor_base_calculo,
valor_icms: helper.icms.valor_icms,
valor_produtos: helper.icms.valor_produtos,
valor_frete: helper.icms.valor_frete,
valor_seguro: helper.icms.valor_seguro,
valor_desconto: helper.icms.valor_desconto,
valor_outros: helper.icms.valor_outros,
valor_pis: helper.icms.valor_pis,
valor_cofins: helper.icms.valor_cofins,
valor_total: helper.icms.valor_total,
valor_aproximado_tributos: helper.icms.valor_aproximado_tributos,
})
}
}
#[derive(Deserialize, Serialize)]
#[serde(rename = "total")]
struct TotalContainer {
#[serde(rename = "ICMSTot")]
icms: IcmsTot,
}
#[derive(Deserialize, Serialize)]
struct IcmsTot {
#[serde(rename = "$unflatten=vBC")]
valor_base_calculo: f32,
#[serde(rename = "$unflatten=vICMS")]
valor_icms: f32,
#[serde(rename = "$unflatten=vProd")]
valor_produtos: f32,
#[serde(rename = "$unflatten=vFrete")]
valor_frete: f32,
#[serde(rename = "$unflatten=vSeg")]
valor_seguro: f32,
#[serde(rename = "$unflatten=vDesc")]
valor_desconto: f32,
#[serde(rename = "$unflatten=vOutro")]
valor_outros: f32,
#[serde(rename = "$unflatten=vPIS")]
valor_pis: f32,
#[serde(rename = "$unflatten=vCOFINS")]
valor_cofins: f32,
#[serde(rename = "$unflatten=vNF")]
valor_total: f32,
#[serde(rename = "$unflatten=vTotTrib")]
valor_aproximado_tributos: f32,
}
| 30.503937 | 82 | 0.641972 |
50c174c3e95a6159edab3b64db9aef2d401fbf6f | 1,404 | use failure::Error;
use graphql_parser::schema::*;
use std::fmt;
use schema::ast;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Strings(Vec<String>);
impl fmt::Display for Strings {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
let s = (&self.0).join(", ");
write!(f, "{}", s)
}
}
#[derive(Clone, Debug, Serialize, Fail)]
pub enum SchemaValidationError {
#[fail(
display = "@entity directive missing on the following types: {}",
_0
)]
EntityDirectivesMissing(Strings),
}
/// Validates whether a GraphQL schema is compatible with The Graph.
pub fn validate_schema(schema: &Document) -> Result<(), Error> {
validate_schema_types(schema)?;
Ok(())
}
/// Validates whether all object types in the schema are declared with an @entity directive.
fn validate_schema_types(schema: &Document) -> Result<(), SchemaValidationError> {
use self::SchemaValidationError::*;
let types_without_entity_directive = ast::get_object_type_definitions(schema)
.iter()
.filter(|t| ast::get_object_type_directive(t, String::from("entity")).is_none())
.map(|t| t.name.to_owned())
.collect::<Vec<_>>();
if types_without_entity_directive.is_empty() {
Ok(())
} else {
Err(EntityDirectivesMissing(Strings(
types_without_entity_directive,
)))
}
}
| 28.08 | 92 | 0.645299 |
21d884063102f22bc881b037f6998dcbb56cec66 | 5,568 | use crate::lang::reification::ExprInterface;
use crate::lang::*;
use aries_core::*;
use std::cmp::Ordering;
/// Normal form of an expression with component of type `X`.
/// It can be either: a literal, an expression of type `X`
/// or the negation of an expression of type `X`.
pub enum NormalExpr<X> {
Literal(Lit),
Pos(X),
Neg(X),
}
impl<X: ExprInterface> NormalExpr<X> {
pub fn validity_scope(&self, presence: &dyn Fn(VarRef) -> Lit) -> ValidityScope {
match self {
NormalExpr::Literal(l) => ValidityScope::new([presence(l.variable())], []),
NormalExpr::Pos(x) => x.validity_scope(presence),
NormalExpr::Neg(x) => x.validity_scope(presence),
}
}
}
impl<T> std::ops::Not for NormalExpr<T> {
type Output = Self;
fn not(self) -> Self::Output {
match self {
NormalExpr::Literal(l) => NormalExpr::Literal(!l),
NormalExpr::Pos(e) => NormalExpr::Neg(e),
NormalExpr::Neg(e) => NormalExpr::Pos(e),
}
}
}
impl<T> From<Lit> for NormalExpr<T> {
fn from(l: Lit) -> Self {
Self::Literal(l)
}
}
impl<T> From<bool> for NormalExpr<T> {
fn from(l: bool) -> Self {
Self::Literal(l.into())
}
}
/// Canonical representation of an inequality: `lhs <= rhs + rhs_add`
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct NFLeq {
pub lhs: VarRef,
pub rhs: VarRef,
pub rhs_add: IntCst,
}
impl NFLeq {
pub fn new(lhs: VarRef, rhs: VarRef, rhs_add: IntCst) -> Self {
debug_assert!(lhs < rhs, "Violated lexical order invariant");
debug_assert_ne!(lhs, VarRef::ZERO);
debug_assert_ne!(rhs, VarRef::ZERO);
NFLeq { lhs, rhs, rhs_add }
}
pub fn geq<A: Into<IAtom>, B: Into<IAtom>>(a: A, b: B) -> NormalExpr<Self> {
Self::leq(b, a)
}
pub fn gt<A: Into<IAtom>, B: Into<IAtom>>(a: A, b: B) -> NormalExpr<Self> {
Self::lt(b, a)
}
pub fn lt<A: Into<IAtom>, B: Into<IAtom>>(a: A, b: B) -> NormalExpr<Self> {
Self::leq(a.into() + 1, b)
}
pub fn leq<A: Into<IAtom>, B: Into<IAtom>>(lhs: A, rhs: B) -> NormalExpr<Self> {
let lhs = lhs.into();
let rhs = rhs.into();
// normalize, transfer the shift from right to left
let rhs_add = rhs.shift - lhs.shift;
let lhs: VarRef = lhs.var.into();
let rhs: VarRef = rhs.var.into();
// Only encode as a LEQ the patterns with two variables.
// Other are treated either are constant (if provable as so)
// or as literals on a single variable
if lhs == rhs {
// X <= X + rhs_add <=> 0 <= rhs_add
return (0 <= rhs_add).into();
}
if rhs == VarRef::ZERO {
// lhs <= rhs_add
return Lit::leq(lhs, rhs_add).into();
}
if lhs == VarRef::ZERO {
// 0 <= rhs + rhs_add <=> -rhs_add <= rhs
return Lit::geq(rhs, -rhs_add).into();
}
// maintain the invariant that left side of the LEQ has a small lexical order
match lhs.cmp(&rhs) {
Ordering::Less => NormalExpr::Pos(Self::new(lhs, rhs, rhs_add)),
Ordering::Equal => unreachable!(),
Ordering::Greater => {
// (lhs <= rhs + rhs_add) <=> (not (rhs <= lhs - rhs_add -1)
NormalExpr::Neg(Self::new(rhs, lhs, -rhs_add - 1))
}
}
}
}
impl ExprInterface for NFLeq {
fn validity_scope(&self, presence: &dyn Fn(VarRef) -> Lit) -> ValidityScope {
ValidityScope::new([presence(self.lhs), presence(self.rhs)], [])
}
}
/// lhs = rhs + rhs_add
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct NFEq {
pub lhs: VarRef,
pub rhs: VarRef,
pub rhs_add: IntCst,
}
impl NFEq {
pub fn new(lhs: VarRef, rhs: VarRef, rhs_add: IntCst) -> Self {
debug_assert!(lhs < rhs, "Invariant violated");
NFEq { lhs, rhs, rhs_add }
}
/// Builds the normal form for this equality.
pub fn eq<A: Into<Atom>, B: Into<Atom>>(a: A, b: B) -> NormalExpr<NFEq> {
let a = a.into();
let b = b.into();
if a == b {
Lit::TRUE.into()
} else if a.kind() != b.kind() {
panic!("Attempting to build an equality between expression with incompatible types.");
} else {
use Atom::*;
match (a, b) {
(Bool(_a), Bool(_b)) => todo!(),
(Int(a), Int(b)) => Self::int_eq(a, b),
(Sym(a), Sym(b)) => Self::int_eq(a.int_view(), b.int_view()),
(Fixed(a), Fixed(b)) => {
debug_assert_eq!(a.denom, b.denom); // should be guarded by the kind comparison
Self::int_eq(a.num, b.num)
}
_ => unreachable!(), // guarded by kind comparison
}
}
}
pub fn int_eq(a: IAtom, b: IAtom) -> NormalExpr<NFEq> {
let b_add = b.shift - a.shift;
let a: VarRef = a.var.into();
let b: VarRef = b.var.into();
match a.cmp(&b) {
Ordering::Less => NormalExpr::Pos(Self::new(a, b, b_add)),
Ordering::Equal => (b_add == 0).into(),
Ordering::Greater => NormalExpr::Pos(Self::new(b, a, -b_add)),
}
}
}
impl ExprInterface for NFEq {
fn validity_scope(&self, presence: &dyn Fn(VarRef) -> Lit) -> ValidityScope {
ValidityScope::new([presence(self.lhs), presence(self.rhs)], [])
}
}
| 32.752941 | 99 | 0.536458 |
d54acfbae358d0043f4706877d621b82cdcfece7 | 1,200 | // Copyright (c) 2019, Facebook, Inc.
// All rights reserved.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use crate::common::{gen_helpers, to_snake};
use super::context::Context;
pub fn gen(ctx: &Context) -> TokenStream {
let uses = gen_helpers::gen_module_uses(ctx.modules());
let visit_functions = ctx.types().map(gen_visit_function).collect::<Vec<_>>();
quote! {
#![allow(unused_variables)]
#uses
use super::node::Node;
pub trait Visitor<'a> {
fn object(&mut self) -> &mut dyn Visitor<'a>;
#(#visit_functions)*
}
}
}
fn gen_visit_function(ast: &syn::DeriveInput) -> TokenStream {
let ty = &ast.ident;
let name = gen_visit_fn_name(ty.to_string());
let (_, ty_generics, _) = ast.generics.split_for_impl();
quote! {
fn #name(&mut self, p: &'a #ty #ty_generics) {
p.recurse(self.object())
}
}
}
pub fn gen_visit_fn_name(ty: impl AsRef<str>) -> syn::Ident {
format_ident!("visit_{}", to_snake(ty.as_ref()))
}
| 26.086957 | 82 | 0.621667 |
28ba19fb24db0eeffe5ac2c91d13d5e4b5d99d95 | 765 | // Copyright (c) The XPeer Core Contributors
// SPDX-License-Identifier: Apache-2.0
/// Builds the proto files needed for the network crate.
fn main() {
let proto_files = [
"src/proto/network.proto",
"src/proto/mempool.proto",
"src/proto/consensus.proto",
];
for file in &proto_files {
println!("cargo:rerun-if-changed={}", file);
}
protoc_rust::run(protoc_rust::Args {
out_dir: "src/proto",
input: &proto_files,
includes: &["../types/src/proto", "src/proto"],
customize: protoc_rust::Customize {
carllerche_bytes_for_bytes: Some(true),
carllerche_bytes_for_string: Some(true),
..Default::default()
},
})
.expect("protoc");
}
| 27.321429 | 56 | 0.589542 |
9c926ceaaba28aabf85baa8c92ce4f7ab87bba6d | 458 | fn a1(
#[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] a: u8,
) {
}
fn b1(
#[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] bb: u8,
) {
}
fn a2(
#[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] a: u8,
) {
}
fn b2(
#[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa] bb: u8,
) {
}
| 26.941176 | 101 | 0.816594 |
d63c2438b44ad1b5670c35852ae39777b291e019 | 2,427 | // Copyright (c) Meta Platforms, Inc. and affiliates.
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use hackrs::{
decl_defs::{folded::FoldedClass, shallow},
decl_parser::DeclParser,
folded_decl_provider,
reason::BReason,
};
use ocamlrep_ocamlpool::{ocaml_ffi_with_arena, Bump};
use oxidized_by_ref::decl_defs::DeclClassType;
use pos::{RelativePath, RelativePathCtx, ToOxidized};
use std::collections::BTreeMap;
use std::path::Path;
use std::sync::Arc;
ocaml_ffi_with_arena! {
fn fold_classes_in_files_ffi<'a>(
arena: &'a Bump,
root: &'a Path,
files: &'a [oxidized_by_ref::relative_path::RelativePath<'a>],
) -> BTreeMap<RelativePath, Vec<DeclClassType<'a>>> {
let files: Vec<RelativePath> = files.iter().map(Into::into).collect();
let path_ctx = Arc::new(RelativePathCtx {
root: root.into(),
..Default::default()
});
let decl_parser = DeclParser::new(path_ctx);
let folded_decl_provider: Arc<dyn folded_decl_provider::FoldedDeclProvider<BReason>> =
hackrs_test_utils::decl_provider::make_folded_decl_provider(
None,
&decl_parser,
files.iter().copied(),
);
files
.into_iter()
.map(|filename| {
(
filename,
decl_parser
.parse(filename)
.expect("failed to parse")
.into_iter()
.filter_map(|decl| match decl {
shallow::Decl::Class(name, _) => Some(
folded_decl_provider
.get_class(name.into(), name)
.expect("failed to fold class")
.expect("failed to look up class"),
),
_ => None,
})
.map(|cls| cls.to_oxidized(arena))
.collect(),
)
})
.collect()
}
fn show_decl_class_type_ffi<'a>(arena: &'a Bump, decl: &'a DeclClassType<'a>) -> String {
let decl = <FoldedClass<BReason>>::from(decl);
format!("{:#?}", decl)
}
}
| 36.772727 | 94 | 0.509271 |
488075e19c8f52eaa65e337bb1da73c4b1ca72da | 737 | pub fn count_bits(integer: i64) -> u32 {
let mut n = integer as u32;
let mut count = 0u32;
while n!=0 {
count += n%2;
n /= 2;
}
count
}
pub fn count_bits_spec(integer: i64) -> u32 {
integer.count_ones()
}
#[cfg(test)]
mod tests {
#[test]
fn returns_expected() {
returns_expected_common(super::count_bits);
}
#[test]
fn returns_expected_spec() {
returns_expected_common(super::count_bits_spec);
}
fn returns_expected_common(count_bits: fn(i64)->u32) {
assert_eq!(count_bits(0), 0);
assert_eq!(count_bits(4), 1);
assert_eq!(count_bits(7), 3);
assert_eq!(count_bits(9), 2);
assert_eq!(count_bits(10), 2);
}
} | 21.676471 | 58 | 0.579376 |
4ae82df94cefbb9e12791573e723dfb21048bca4 | 39,767 | use crate::transport;
use crate::utils;
use crate::validate::Validate;
use crate::{devicemgmt as tds, onvif as tt};
use macro_utils::*;
use std::io::{Read, Write};
use std::str::FromStr;
use xsd_types::types as xs;
use yaserde::{YaDeserialize, YaSerialize};
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetServiceCapabilities {}
impl Validate for GetServiceCapabilities {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetServiceCapabilitiesResponse {
// The capabilities for the device IO service is returned in the
// Capabilities element.
#[yaserde(prefix = "tmd", rename = "Capabilities")]
pub capabilities: Capabilities,
}
impl Validate for GetServiceCapabilitiesResponse {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct Capabilities {
// Number of video sources (defaults to none).
#[yaserde(attribute, rename = "VideoSources")]
pub video_sources: Option<i32>,
// Number of video outputs (defaults to none).
#[yaserde(attribute, rename = "VideoOutputs")]
pub video_outputs: Option<i32>,
// Number of audio sources (defaults to none).
#[yaserde(attribute, rename = "AudioSources")]
pub audio_sources: Option<i32>,
// Number of audio outputs (defaults to none).
#[yaserde(attribute, rename = "AudioOutputs")]
pub audio_outputs: Option<i32>,
// Number of relay outputs (defaults to none).
#[yaserde(attribute, rename = "RelayOutputs")]
pub relay_outputs: Option<i32>,
// Number of serial ports (defaults to none).
#[yaserde(attribute, rename = "SerialPorts")]
pub serial_ports: Option<i32>,
// Number of digital inputs (defaults to none).
#[yaserde(attribute, rename = "DigitalInputs")]
pub digital_inputs: Option<i32>,
// Indicates support for DigitalInput configuration of the idle state
// (defaults to false).
#[yaserde(attribute, rename = "DigitalInputOptions")]
pub digital_input_options: Option<bool>,
}
impl Validate for Capabilities {}
// pub type Capabilities = Capabilities;
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetRelayOutputOptions {
// Optional reference token to the relay for which the options are
// requested.
#[yaserde(prefix = "tmd", rename = "RelayOutputToken")]
pub relay_output_token: Option<tt::ReferenceToken>,
}
impl Validate for GetRelayOutputOptions {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetRelayOutputOptionsResponse {
// Valid values and ranges for the configuration of a relay output.
#[yaserde(prefix = "tmd", rename = "RelayOutputOptions")]
pub relay_output_options: Vec<RelayOutputOptions>,
}
impl Validate for GetRelayOutputOptionsResponse {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct RelayOutputOptions {
// Supported Modes.
#[yaserde(prefix = "tmd", rename = "Mode")]
pub mode: Vec<tt::RelayMode>,
// Supported delay time range or discrete values in seconds. This element
// must be present if MonoStable mode is supported.
#[yaserde(prefix = "tmd", rename = "DelayTimes")]
pub delay_times: Option<DelayTimes>,
// True if the relay only supports the exact values for the DelayTimes
// listed. Default is false.
#[yaserde(prefix = "tmd", rename = "Discrete")]
pub discrete: Option<bool>,
#[yaserde(prefix = "tmd", rename = "Extension")]
pub extension: Option<RelayOutputOptionsExtension>,
// Token of the relay output.
#[yaserde(attribute, rename = "token")]
pub token: tt::ReferenceToken,
}
impl Validate for RelayOutputOptions {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct RelayOutputOptionsExtension {}
impl Validate for RelayOutputOptionsExtension {}
#[derive(Default, PartialEq, Debug, UtilsTupleIo, UtilsDefaultSerde)]
pub struct DelayTimes(pub Vec<f64>);
impl Validate for DelayTimes {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct Get {}
impl Validate for Get {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetResponse {
// List tokens of a physical IO of a device.
#[yaserde(prefix = "tmd", rename = "Token")]
pub token: Vec<tt::ReferenceToken>,
}
impl Validate for GetResponse {}
pub type GetVideoSources = Get;
pub type GetVideoSourcesResponse = GetResponse;
pub type GetAudioSources = Get;
pub type GetAudioSourcesResponse = GetResponse;
pub type GetAudioOutputs = Get;
pub type GetAudioOutputsResponse = GetResponse;
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetVideoOutputs {}
impl Validate for GetVideoOutputs {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetVideoOutputsResponse {
// List containing all physical Video output connections of a device.
#[yaserde(prefix = "tmd", rename = "VideoOutputs")]
pub video_outputs: Vec<tt::VideoOutput>,
}
impl Validate for GetVideoOutputsResponse {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetAudioSourceConfiguration {
// Token of the requested AudioSource.
#[yaserde(prefix = "tmd", rename = "AudioSourceToken")]
pub audio_source_token: tt::ReferenceToken,
}
impl Validate for GetAudioSourceConfiguration {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetAudioSourceConfigurationResponse {
// Current configuration of the Audio input.
#[yaserde(prefix = "tmd", rename = "AudioSourceConfiguration")]
pub audio_source_configuration: tt::AudioSourceConfiguration,
}
impl Validate for GetAudioSourceConfigurationResponse {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetAudioOutputConfiguration {
// Token of the physical Audio output.
#[yaserde(prefix = "tmd", rename = "AudioOutputToken")]
pub audio_output_token: tt::ReferenceToken,
}
impl Validate for GetAudioOutputConfiguration {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetAudioOutputConfigurationResponse {
// Current configuration of the Audio output.
#[yaserde(prefix = "tmd", rename = "AudioOutputConfiguration")]
pub audio_output_configuration: tt::AudioOutputConfiguration,
}
impl Validate for GetAudioOutputConfigurationResponse {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetVideoSourceConfiguration {
// Token of the requested VideoSource.
#[yaserde(prefix = "tmd", rename = "VideoSourceToken")]
pub video_source_token: tt::ReferenceToken,
}
impl Validate for GetVideoSourceConfiguration {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetVideoSourceConfigurationResponse {
// Current configuration of the Video input.
#[yaserde(prefix = "tmd", rename = "VideoSourceConfiguration")]
pub video_source_configuration: tt::VideoSourceConfiguration,
}
impl Validate for GetVideoSourceConfigurationResponse {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetVideoOutputConfiguration {
// Token of the requested VideoOutput.
#[yaserde(prefix = "tmd", rename = "VideoOutputToken")]
pub video_output_token: tt::ReferenceToken,
}
impl Validate for GetVideoOutputConfiguration {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetVideoOutputConfigurationResponse {
// Current configuration of the Video output.
#[yaserde(prefix = "tmd", rename = "VideoOutputConfiguration")]
pub video_output_configuration: tt::VideoOutputConfiguration,
}
impl Validate for GetVideoOutputConfigurationResponse {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct SetAudioSourceConfiguration {
#[yaserde(prefix = "tmd", rename = "Configuration")]
pub configuration: tt::AudioSourceConfiguration,
// The ForcePersistence element determines how configuration
// changes shall be stored. If true, changes shall be persistent. If false,
// changes MAY revert to previous values
// after reboot.
#[yaserde(prefix = "tmd", rename = "ForcePersistence")]
pub force_persistence: bool,
}
impl Validate for SetAudioSourceConfiguration {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct SetAudioSourceConfigurationResponse {}
impl Validate for SetAudioSourceConfigurationResponse {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct SetAudioOutputConfiguration {
#[yaserde(prefix = "tmd", rename = "Configuration")]
pub configuration: tt::AudioOutputConfiguration,
// The ForcePersistence element determines how configuration
// changes shall be stored. If true, changes shall be persistent. If false,
// changes MAY revert to previous values
// after reboot.
#[yaserde(prefix = "tmd", rename = "ForcePersistence")]
pub force_persistence: bool,
}
impl Validate for SetAudioOutputConfiguration {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct SetAudioOutputConfigurationResponse {}
impl Validate for SetAudioOutputConfigurationResponse {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct SetVideoSourceConfiguration {
#[yaserde(prefix = "tmd", rename = "Configuration")]
pub configuration: tt::VideoSourceConfiguration,
// The ForcePersistence element determines how configuration
// changes shall be stored. If true, changes shall be persistent. If false,
// changes MAY revert to previous values
// after reboot.
#[yaserde(prefix = "tmd", rename = "ForcePersistence")]
pub force_persistence: bool,
}
impl Validate for SetVideoSourceConfiguration {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct SetVideoSourceConfigurationResponse {}
impl Validate for SetVideoSourceConfigurationResponse {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct SetVideoOutputConfiguration {
#[yaserde(prefix = "tmd", rename = "Configuration")]
pub configuration: tt::VideoOutputConfiguration,
// The ForcePersistence element determines how configuration
// changes shall be stored. If true, changes shall be persistent. If false,
// changes MAY revert to previous values
// after reboot.
#[yaserde(prefix = "tmd", rename = "ForcePersistence")]
pub force_persistence: bool,
}
impl Validate for SetVideoOutputConfiguration {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct SetVideoOutputConfigurationResponse {}
impl Validate for SetVideoOutputConfigurationResponse {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetVideoSourceConfigurationOptions {
// Token of the Video input whose options are requested..
#[yaserde(prefix = "tmd", rename = "VideoSourceToken")]
pub video_source_token: tt::ReferenceToken,
}
impl Validate for GetVideoSourceConfigurationOptions {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetVideoSourceConfigurationOptionsResponse {
#[yaserde(prefix = "tmd", rename = "VideoSourceConfigurationOptions")]
pub video_source_configuration_options: tt::VideoSourceConfigurationOptions,
}
impl Validate for GetVideoSourceConfigurationOptionsResponse {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetVideoOutputConfigurationOptions {
// Token of the Video Output whose options are requested..
#[yaserde(prefix = "tmd", rename = "VideoOutputToken")]
pub video_output_token: tt::ReferenceToken,
}
impl Validate for GetVideoOutputConfigurationOptions {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetVideoOutputConfigurationOptionsResponse {
#[yaserde(prefix = "tmd", rename = "VideoOutputConfigurationOptions")]
pub video_output_configuration_options: tt::VideoOutputConfigurationOptions,
}
impl Validate for GetVideoOutputConfigurationOptionsResponse {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetAudioSourceConfigurationOptions {
// Token of the physical Audio input whose options are requested..
#[yaserde(prefix = "tmd", rename = "AudioSourceToken")]
pub audio_source_token: tt::ReferenceToken,
}
impl Validate for GetAudioSourceConfigurationOptions {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetAudioSourceConfigurationOptionsResponse {
// Returns the AudioSourceToken available.
#[yaserde(prefix = "tmd", rename = "AudioSourceOptions")]
pub audio_source_options: tt::AudioSourceConfigurationOptions,
}
impl Validate for GetAudioSourceConfigurationOptionsResponse {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetAudioOutputConfigurationOptions {
// Token of the physical Audio Output whose options are requested..
#[yaserde(prefix = "tmd", rename = "AudioOutputToken")]
pub audio_output_token: tt::ReferenceToken,
}
impl Validate for GetAudioOutputConfigurationOptions {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetAudioOutputConfigurationOptionsResponse {
// Available settings and ranges for the requested Audio output.
#[yaserde(prefix = "tmd", rename = "AudioOutputOptions")]
pub audio_output_options: tt::AudioOutputConfigurationOptions,
}
impl Validate for GetAudioOutputConfigurationOptionsResponse {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct SetRelayOutputSettings {
#[yaserde(prefix = "tmd", rename = "RelayOutput")]
pub relay_output: tt::RelayOutput,
}
impl Validate for SetRelayOutputSettings {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct SetRelayOutputSettingsResponse {}
impl Validate for SetRelayOutputSettingsResponse {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetDigitalInputs {}
impl Validate for GetDigitalInputs {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetDigitalInputsResponse {
#[yaserde(prefix = "tmd", rename = "DigitalInputs")]
pub digital_inputs: Vec<tt::DigitalInput>,
}
impl Validate for GetDigitalInputsResponse {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct DigitalInputConfigurationOptions {
// Configuration Options for a digital input.
#[yaserde(prefix = "tmd", rename = "IdleState")]
pub idle_state: Vec<tt::DigitalIdleState>,
}
impl Validate for DigitalInputConfigurationOptions {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetDigitalInputConfigurationOptions {
#[yaserde(prefix = "tmd", rename = "Token")]
pub token: Option<tt::ReferenceToken>,
}
impl Validate for GetDigitalInputConfigurationOptions {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetDigitalInputConfigurationOptionsResponse {
#[yaserde(prefix = "tmd", rename = "DigitalInputOptions")]
pub digital_input_options: DigitalInputConfigurationOptions,
}
impl Validate for GetDigitalInputConfigurationOptionsResponse {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct SetDigitalInputConfigurations {
#[yaserde(prefix = "tmd", rename = "DigitalInputs")]
pub digital_inputs: Vec<tt::DigitalInput>,
}
impl Validate for SetDigitalInputConfigurations {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct SetDigitalInputConfigurationsResponse {}
impl Validate for SetDigitalInputConfigurationsResponse {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetSerialPorts {}
impl Validate for GetSerialPorts {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetSerialPortsResponse {
#[yaserde(prefix = "tmd", rename = "SerialPort")]
pub serial_port: Vec<SerialPort>,
}
impl Validate for GetSerialPortsResponse {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetSerialPortConfiguration {
#[yaserde(prefix = "tmd", rename = "SerialPortToken")]
pub serial_port_token: tt::ReferenceToken,
}
impl Validate for GetSerialPortConfiguration {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetSerialPortConfigurationResponse {
#[yaserde(prefix = "tmd", rename = "SerialPortConfiguration")]
pub serial_port_configuration: SerialPortConfiguration,
}
impl Validate for GetSerialPortConfigurationResponse {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct SetSerialPortConfiguration {
#[yaserde(prefix = "tmd", rename = "SerialPortConfiguration")]
pub serial_port_configuration: SerialPortConfiguration,
#[yaserde(prefix = "tmd", rename = "ForcePersistance")]
pub force_persistance: bool,
}
impl Validate for SetSerialPortConfiguration {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct SetSerialPortConfigurationResponse {}
impl Validate for SetSerialPortConfigurationResponse {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetSerialPortConfigurationOptions {
#[yaserde(prefix = "tmd", rename = "SerialPortToken")]
pub serial_port_token: tt::ReferenceToken,
}
impl Validate for GetSerialPortConfigurationOptions {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct GetSerialPortConfigurationOptionsResponse {
#[yaserde(prefix = "tmd", rename = "SerialPortOptions")]
pub serial_port_options: SerialPortConfigurationOptions,
}
impl Validate for GetSerialPortConfigurationOptionsResponse {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct SendReceiveSerialCommand {
// The physical serial port reference to be used when this request is
// invoked.
#[yaserde(prefix = "tmd", rename = "Token")]
pub token: Option<tt::ReferenceToken>,
// The serial port data.
#[yaserde(prefix = "tmd", rename = "SerialData")]
pub serial_data: Option<SerialData>,
// Indicates that the command should be responded back within the specified
// period of time.
#[yaserde(prefix = "tmd", rename = "TimeOut")]
pub time_out: Option<xs::Duration>,
// This element may be put in the case that data length returned from the
// connected serial device is already determined as some fixed bytes length.
// It indicates the length of received data which can be regarded as
// available.
#[yaserde(prefix = "tmd", rename = "DataLength")]
pub data_length: Option<xs::Integer>,
// This element may be put in the case that the delimiter codes returned
// from the connected serial device is already known. It indicates the
// termination data sequence of the responded data. In case the string has
// more than one character a device shall interpret the whole string as a
// single delimiter. Furthermore a device shall return the delimiter
// character(s) to the client.
#[yaserde(prefix = "tmd", rename = "Delimiter")]
pub delimiter: Option<String>,
}
impl Validate for SendReceiveSerialCommand {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct SendReceiveSerialCommandResponse {
#[yaserde(prefix = "tmd", rename = "SerialData")]
pub serial_data: Option<SerialData>,
}
impl Validate for SendReceiveSerialCommandResponse {}
#[derive(PartialEq, Debug, YaSerialize, YaDeserialize)]
pub enum SerialDataChoice {
Binary(String),
String(String),
__Unknown__(String),
}
impl Default for SerialDataChoice {
fn default() -> SerialDataChoice {
Self::__Unknown__("No valid variants".into())
}
}
impl Validate for SerialDataChoice {}
// The serial port data.
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct SerialData {
#[yaserde(flatten)]
pub serial_data_choice: SerialDataChoice,
}
impl Validate for SerialData {}
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct SerialPort {
pub base: tt::DeviceEntity,
}
impl Validate for SerialPort {}
// The type of serial port.Generic can be signaled as a vendor specific serial
// port type.
#[derive(PartialEq, Debug, YaSerialize, YaDeserialize)]
pub enum SerialPortType {
#[yaserde(rename = "RS232")]
Rs232,
#[yaserde(rename = "RS422HalfDuplex")]
Rs422HalfDuplex,
#[yaserde(rename = "RS422FullDuplex")]
Rs422FullDuplex,
#[yaserde(rename = "RS485HalfDuplex")]
Rs485HalfDuplex,
#[yaserde(rename = "RS485FullDuplex")]
Rs485FullDuplex,
Generic,
__Unknown__(String),
}
impl Default for SerialPortType {
fn default() -> SerialPortType {
Self::__Unknown__("No valid variants".into())
}
}
impl Validate for SerialPortType {}
// The parameters for configuring the serial port.
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct SerialPortConfiguration {
// The transfer bitrate.
#[yaserde(prefix = "tmd", rename = "BaudRate")]
pub baud_rate: i32,
// The parity for the data error detection.
#[yaserde(prefix = "tmd", rename = "ParityBit")]
pub parity_bit: ParityBit,
// The bit length for each character.
#[yaserde(prefix = "tmd", rename = "CharacterLength")]
pub character_length: i32,
// The number of stop bits used to terminate each character.
#[yaserde(prefix = "tmd", rename = "StopBit")]
pub stop_bit: f64,
#[yaserde(attribute, rename = "token")]
pub token: tt::ReferenceToken,
#[yaserde(attribute, rename = "type")]
pub _type: SerialPortType,
}
impl Validate for SerialPortConfiguration {}
// The parity for the data error detection.
#[derive(PartialEq, Debug, YaSerialize, YaDeserialize)]
pub enum ParityBit {
None,
Even,
Odd,
Mark,
Space,
Extended,
__Unknown__(String),
}
impl Default for ParityBit {
fn default() -> ParityBit {
Self::__Unknown__("No valid variants".into())
}
}
impl Validate for ParityBit {}
// The configuration options that relates to serial port.
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct SerialPortConfigurationOptions {
// The list of configurable transfer bitrate.
#[yaserde(prefix = "tmd", rename = "BaudRateList")]
pub baud_rate_list: tt::IntList,
// The list of configurable parity for the data error detection.
#[yaserde(prefix = "tmd", rename = "ParityBitList")]
pub parity_bit_list: ParityBitList,
// The list of configurable bit length for each character.
#[yaserde(prefix = "tmd", rename = "CharacterLengthList")]
pub character_length_list: tt::IntList,
// The list of configurable number of stop bits used to terminate each
// character.
#[yaserde(prefix = "tmd", rename = "StopBitList")]
pub stop_bit_list: tt::FloatList,
#[yaserde(attribute, rename = "token")]
pub token: tt::ReferenceToken,
}
impl Validate for SerialPortConfigurationOptions {}
// The list of configurable parity for the data error detection.
#[derive(Default, PartialEq, Debug, YaSerialize, YaDeserialize)]
#[yaserde(
prefix = "tmd",
namespace = "tmd: http://www.onvif.org/ver10/deviceIO/wsdl"
)]
pub struct ParityBitList {
#[yaserde(prefix = "tmd", rename = "Items")]
pub items: Vec<ParityBit>,
}
impl Validate for ParityBitList {}
// Returns the capabilities of the device IO service. The result is returned in
// a typed answer.
pub async fn get_service_capabilities<T: transport::Transport>(
transport: &T,
request: &GetServiceCapabilities,
) -> Result<GetServiceCapabilitiesResponse, transport::Error> {
transport::request(transport, request).await
}
// Request the available settings and ranges for one or all relay outputs. A
// device that has one or more RelayOutputs should support this command.
pub async fn get_relay_output_options<T: transport::Transport>(
transport: &T,
request: &GetRelayOutputOptions,
) -> Result<GetRelayOutputOptionsResponse, transport::Error> {
transport::request(transport, request).await
}
// List all available audio sources for the device. The device that has one or
// more audio sources shall support the listing of available audio inputs
// through the GetAudioSources command.
pub async fn get_audio_sources<T: transport::Transport>(
transport: &T,
request: &GetAudioSources,
) -> Result<GetAudioSourcesResponse, transport::Error> {
transport::request(transport, request).await
}
// List all available audio outputs of a device. A device that has one ore more
// physical audio outputs shall support listing of available audio outputs
// through the GetAudioOutputs command.
pub async fn get_audio_outputs<T: transport::Transport>(
transport: &T,
request: &GetAudioOutputs,
) -> Result<GetAudioOutputsResponse, transport::Error> {
transport::request(transport, request).await
}
// List all available video sources for the device. The device that has one or
// more video inputs shall support the listing of available video sources
// through the GetVideoSources command.
pub async fn get_video_sources<T: transport::Transport>(
transport: &T,
request: &GetVideoSources,
) -> Result<GetVideoSourcesResponse, transport::Error> {
transport::request(transport, request).await
}
// List all available video outputs of a device. A device that has one or more
// physical video outputs shall support listing of available video outputs
// through the GetVideoOutputs command.
pub async fn get_video_outputs<T: transport::Transport>(
transport: &T,
request: &GetVideoOutputs,
) -> Result<GetVideoOutputsResponse, transport::Error> {
transport::request(transport, request).await
}
// Get the video source configurations of a VideoSource. A device with one or
// more video sources shall support the GetVideoSourceConfigurations command.
pub async fn get_video_source_configuration<T: transport::Transport>(
transport: &T,
request: &GetVideoSourceConfiguration,
) -> Result<GetVideoSourceConfigurationResponse, transport::Error> {
transport::request(transport, request).await
}
// Get the configuration of a Video Output. A device that has one or more Video
// Outputs shall support the retrieval of the VideoOutputConfiguration through
// this command.
pub async fn get_video_output_configuration<T: transport::Transport>(
transport: &T,
request: &GetVideoOutputConfiguration,
) -> Result<GetVideoOutputConfigurationResponse, transport::Error> {
transport::request(transport, request).await
}
// List the configuration of an Audio Input. A device with one or more audio
// inputs shall support the GetAudioSourceConfiguration command.
pub async fn get_audio_source_configuration<T: transport::Transport>(
transport: &T,
request: &GetAudioSourceConfiguration,
) -> Result<GetAudioSourceConfigurationResponse, transport::Error> {
transport::request(transport, request).await
}
// Request the current configuration of a physical Audio output. A device that
// has one or more AudioOutputs shall support the retrieval of the
// AudioOutputConfiguration through this command.
pub async fn get_audio_output_configuration<T: transport::Transport>(
transport: &T,
request: &GetAudioOutputConfiguration,
) -> Result<GetAudioOutputConfigurationResponse, transport::Error> {
transport::request(transport, request).await
}
// Modify a video input configuration. A device that has one or more video
// sources shall support the setting of the VideoSourceConfiguration through
// this command.
pub async fn set_video_source_configuration<T: transport::Transport>(
transport: &T,
request: &SetVideoSourceConfiguration,
) -> Result<SetVideoSourceConfigurationResponse, transport::Error> {
transport::request(transport, request).await
}
// Modify a video output configuration. A device that has one or more video
// outputs shall support the setting of its video output configuration through
// this command.
pub async fn set_video_output_configuration<T: transport::Transport>(
transport: &T,
request: &SetVideoOutputConfiguration,
) -> Result<SetVideoOutputConfigurationResponse, transport::Error> {
transport::request(transport, request).await
}
// Modify an audio source configuration. A device that has a one or more audio
// sources shall support the setting of the AudioSourceConfiguration through
// this command.
pub async fn set_audio_source_configuration<T: transport::Transport>(
transport: &T,
request: &SetAudioSourceConfiguration,
) -> Result<SetAudioSourceConfigurationResponse, transport::Error> {
transport::request(transport, request).await
}
// Modify an audio output configuration. A device that has one ore more audio
// outputs shall support the setting of the AudioOutputConfiguration through
// this command.
pub async fn set_audio_output_configuration<T: transport::Transport>(
transport: &T,
request: &SetAudioOutputConfiguration,
) -> Result<SetAudioOutputConfigurationResponse, transport::Error> {
transport::request(transport, request).await
}
// Request the VideoSourceConfigurationOptions of a VideoSource. A device with
// one or more video sources shall support this command.
pub async fn get_video_source_configuration_options<T: transport::Transport>(
transport: &T,
request: &GetVideoSourceConfigurationOptions,
) -> Result<GetVideoSourceConfigurationOptionsResponse, transport::Error> {
transport::request(transport, request).await
}
// Request the VideoOutputConfigurationOptions of a VideoOutput. A device that
// has one or more video outputs shall support the retrieval of
// VideoOutputConfigurationOptions through this command.
pub async fn get_video_output_configuration_options<T: transport::Transport>(
transport: &T,
request: &GetVideoOutputConfigurationOptions,
) -> Result<GetVideoOutputConfigurationOptionsResponse, transport::Error> {
transport::request(transport, request).await
}
// Request the AudioSourceConfigurationOptions of an AudioSource. A device with
// one ore more AudioSources shall support this command.
pub async fn get_audio_source_configuration_options<T: transport::Transport>(
transport: &T,
request: &GetAudioSourceConfigurationOptions,
) -> Result<GetAudioSourceConfigurationOptionsResponse, transport::Error> {
transport::request(transport, request).await
}
// Request the available settings and ranges for a physical Audio output. A
// device that has one or more AudioOutputs shall support this command.
pub async fn get_audio_output_configuration_options<T: transport::Transport>(
transport: &T,
request: &GetAudioOutputConfigurationOptions,
) -> Result<GetAudioOutputConfigurationOptionsResponse, transport::Error> {
transport::request(transport, request).await
}
// This operation gets a list of all available relay outputs and their settings.
pub async fn get_relay_outputs<T: transport::Transport>(
transport: &T,
request: &tds::GetRelayOutputs,
) -> Result<tds::GetRelayOutputsResponse, transport::Error> {
transport::request(transport, request).await
}
// This operation sets the settings of a relay output.
// The relay can work in two relay modes:
pub async fn set_relay_output_settings<T: transport::Transport>(
transport: &T,
request: &SetRelayOutputSettings,
) -> Result<SetRelayOutputSettingsResponse, transport::Error> {
transport::request(transport, request).await
}
// Modify the relay state.
pub async fn set_relay_output_state<T: transport::Transport>(
transport: &T,
request: &tds::SetRelayOutputState,
) -> Result<tds::SetRelayOutputStateResponse, transport::Error> {
transport::request(transport, request).await
}
// This operation gets a list of all available digital inputs.
pub async fn get_digital_inputs<T: transport::Transport>(
transport: &T,
request: &GetDigitalInputs,
) -> Result<GetDigitalInputsResponse, transport::Error> {
transport::request(transport, request).await
}
// This operation lists what configuration is available for digital inputs.
pub async fn get_digital_input_configuration_options<T: transport::Transport>(
transport: &T,
request: &GetDigitalInputConfigurationOptions,
) -> Result<GetDigitalInputConfigurationOptionsResponse, transport::Error> {
transport::request(transport, request).await
}
// Modify a digital input configuration.
pub async fn set_digital_input_configurations<T: transport::Transport>(
transport: &T,
request: &SetDigitalInputConfigurations,
) -> Result<SetDigitalInputConfigurationsResponse, transport::Error> {
transport::request(transport, request).await
}
pub async fn get_serial_ports<T: transport::Transport>(
transport: &T,
request: &GetSerialPorts,
) -> Result<GetSerialPortsResponse, transport::Error> {
transport::request(transport, request).await
}
pub async fn get_serial_port_configuration<T: transport::Transport>(
transport: &T,
request: &GetSerialPortConfiguration,
) -> Result<GetSerialPortConfigurationResponse, transport::Error> {
transport::request(transport, request).await
}
pub async fn set_serial_port_configuration<T: transport::Transport>(
transport: &T,
request: &SetSerialPortConfiguration,
) -> Result<SetSerialPortConfigurationResponse, transport::Error> {
transport::request(transport, request).await
}
pub async fn get_serial_port_configuration_options<T: transport::Transport>(
transport: &T,
request: &GetSerialPortConfigurationOptions,
) -> Result<GetSerialPortConfigurationOptionsResponse, transport::Error> {
transport::request(transport, request).await
}
pub async fn send_receive_serial_command<T: transport::Transport>(
transport: &T,
request: &SendReceiveSerialCommand,
) -> Result<SendReceiveSerialCommandResponse, transport::Error> {
transport::request(transport, request).await
}
| 33.844255 | 80 | 0.732869 |
dd979c162713a622da353c72cb1f63183a494351 | 2,044 | use crate::{BoxFuture, Context, Extract, Future, Handler, Response, Result};
macro_rules! peel {
($T0:ident, $($T:ident,)*) => (tuple! { $($T,)* })
}
macro_rules! tuple {
() => (
#[doc(hidden)]
impl Extract for ()
{
type Error = Response;
fn extract(_: &mut Context) -> BoxFuture<'_, Result<Self, Self::Error>> {
Box::pin(async { Ok(()) })
}
}
#[doc(hidden)]
impl<Func, Fut > Handler<()> for Func
where
Func: Fn() -> Fut + Clone + 'static,
Fut: Future + Send + 'static,
Fut::Output: Into<Response>,
{
type Output = Fut::Output;
type Future = Fut;
fn call(&self, _: ()) -> Self::Future {
(self)()
}
}
);
($($T:ident,)+) => (
#[doc(hidden)]
impl<$($T),+> Extract for ($($T,)+)
where
$($T: Extract + Send,)+
$($T::Error: Into<Response> + Send + 'static,)+
{
type Error = Response;
fn extract(cx: &mut Context) -> BoxFuture<'_, Result<Self, Self::Error>> {
Box::pin(async move {
Ok((
$(
$T::extract(cx).await.map_err(Into::<Response>::into)?,
)+
))
})
}
}
#[doc(hidden)]
impl<Func, $($T,)+ Fut> Handler<($($T,)+)> for Func
where
Func: Fn($($T,)+) -> Fut + Clone + 'static,
Fut: Future + Send + 'static,
Fut::Output: Into<Response>,
{
type Output = Fut::Output;
type Future = Fut;
fn call(&self, args: ($($T,)+)) -> Self::Future {
#[allow(non_snake_case)]
let ($($T,)+) = args;
(self)($($T,)+)
}
}
peel! { $($T,)+ }
)
}
tuple! { A, B, C, D, E, F, G, H, I, J, K, L, }
| 26.894737 | 86 | 0.380137 |
4b1045f0edf4a7a910ac037ad10a68153eca5feb | 425 | extern crate bstr;
use std::error::Error;
use std::io::{self, Write};
use bstr::{io::BufReadExt, ByteSlice};
fn main() -> Result<(), Box<dyn Error>> {
let stdin = io::stdin();
let mut stdout = io::BufWriter::new(io::stdout());
stdin.lock().for_byte_line_with_terminator(|line| {
if line.contains_str("Dimension") {
stdout.write_all(line)?;
}
Ok(true)
})?;
Ok(())
}
| 21.25 | 55 | 0.574118 |
698e6d277a29d9ef08f0228cea7bb788b90e5ecb | 3,608 | // Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::fmt::Debug;
use std::hash::Hash;
use boxfuture::BoxFuture;
use hashing::Digest;
use futures::future::Future;
use petgraph::stable_graph;
use entry::Entry;
use Graph;
// 2^32 Nodes ought to be more than enough for anyone!
pub type EntryId = stable_graph::NodeIndex<u32>;
///
/// Defines executing a cacheable/memoizable step within the given NodeContext.
///
/// Note that it is assumed that Nodes are very cheap to clone.
///
pub trait Node: Clone + Debug + Eq + Hash + Send + 'static {
type Context: NodeContext<Node = Self>;
type Item: Clone + Debug + Eq + Send + 'static;
type Error: NodeError;
fn run(self, context: Self::Context) -> BoxFuture<Self::Item, Self::Error>;
// TODO: Use a `Display` bound instead.
fn format(&self) -> String;
///
/// If the given Node output represents an FS operation, returns its Digest.
///
fn digest(result: Self::Item) -> Option<Digest>;
///
/// If the node result is cacheable, return true.
///
fn cacheable(&self) -> bool;
}
pub trait NodeError: Clone + Debug + Eq + Send {
///
/// Creates an instance that represents that a Node was invalidated out of the
/// Graph (generally while running).
///
fn invalidated() -> Self;
///
/// Creates an instance that represents that a Node dependency was cyclic.
///
fn cyclic() -> Self;
}
///
/// A trait used to visualize Nodes in either DOT/GraphViz format.
///
pub trait NodeVisualizer<N: Node> {
///
/// Returns a GraphViz color scheme name for this visualizer.
///
fn color_scheme(&self) -> &str;
///
/// Returns a GraphViz color name/id within Self::color_scheme for the given Entry.
///
fn color(&mut self, entry: &Entry<N>) -> String;
}
///
/// A trait used to visualize Nodes for the purposes of CLI-output tracing.
///
pub trait NodeTracer<N: Node> {
///
/// Returns true if the given Node Result represents the "bottom" of a trace.
///
/// A trace represents a sub-dag of the entire Graph, and a "bottom" Node result represents
/// a boundary that the trace stops before (ie, a bottom Node will not be rendered in the trace,
/// but anything that depends on a bottom Node will be).
///
fn is_bottom(result: Option<Result<N::Item, N::Error>>) -> bool;
///
/// Renders the given result for a trace. The trace will already be indented by `indent`, but
/// an implementer creating a multi-line output would need to indent them as well.
///
fn state_str(indent: &str, result: Option<Result<N::Item, N::Error>>) -> String;
}
///
/// A context passed between Nodes that also stores an EntryId to uniquely identify them.
///
pub trait NodeContext: Clone + Send + 'static {
///
/// The type generated when this Context is cloned for another Node.
///
type Node: Node;
///
/// Creates a clone of this NodeContext to be used for a different Node.
///
/// To clone a Context for use for the same Node, `Clone` is used directly.
///
fn clone_for(&self, entry_id: EntryId) -> <Self::Node as Node>::Context;
///
/// Returns a reference to the Graph for this Context.
///
fn graph(&self) -> &Graph<Self::Node>;
///
/// Spawns a Future on an Executor provided by the context.
///
/// NB: Unlike the futures `Executor` trait itself, this implementation _must_ spawn the work
/// on another thread, as it is called from within the Graph lock.
///
fn spawn<F>(&self, future: F)
where
F: Future<Item = (), Error = ()> + Send + 'static;
}
| 28.864 | 98 | 0.66602 |
f905e74c368b063a0a7a84b3836bb66b0accc288 | 1,499 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Make sure we can handle explicit copy_nonoverlapping on empty string
// TODO: https://github.com/model-checking/rmc/issues/241
// The copy_nonoverlapping succeeds, but the final copy back to a slice
// fails:
// [...copy_empty_string_by_intrinsic.assertion.2] line 1035 unreachable code: FAILURE
// [...copy_empty_string_by_intrinsic.assertion.1] line 1037 a panicking function std::result::unwrap_failed is invoked: FAILURE
// [...copy_string.assertion.2] line 28 assertion failed: dest_as_str.len() == l: FAILURE
#![feature(rustc_private)]
extern crate libc;
use std::mem::size_of;
use std::ptr::copy_nonoverlapping;
use std::slice::from_raw_parts;
use std::str;
fn copy_string(s: &str, l: usize) {
unsafe {
// Unsafe buffer
let size: libc::size_t = size_of::<u8>();
let dest: *mut u8 = libc::malloc(size * l) as *mut u8;
// Copy
let src = from_raw_parts(s.as_ptr(), l).as_ptr();
copy_nonoverlapping(src, dest, l);
// The chunk below causes the 3 failures at the top of the file
// Back to str, check length
let dest_slice: &[u8] = from_raw_parts(dest, l);
let dest_as_str: &str = str::from_utf8(dest_slice).unwrap();
assert!(dest_as_str.len() == l);
}
}
pub fn main() {
// Verification fails for both of these cases.
copy_string("x", 1);
copy_string("", 0);
}
| 33.311111 | 128 | 0.671114 |
c1dabfd97de9d561f1d8810659b5a9b3c70729f7 | 61 | fn main() -> std::process::ExitCode {
sane_fmt::main()
}
| 15.25 | 37 | 0.590164 |
2172878c344ee49d51a2576c5dc2d0ecacf9eb9c | 5,577 | use super::bin_reader::BinaryReader;
use crate::{
defs::{SWord, Word},
emulator::{atom, heap::heap_trait::THeap},
fail::{RtErr, RtResult},
term::{
boxed::{self, bignum::sign::Sign},
term_builder::{ListBuilder, TupleBuilder},
value::Term,
},
};
#[repr(u8)]
#[allow(dead_code)]
enum Tag {
ETF = 131,
NewFloat = 70,
BitBinary = 77,
AtomCacheRef_ = 82,
SmallInteger = 97,
Integer = 98,
Float = 99,
AtomDeprecated = 100,
Reference = 101,
Port = 102,
Pid = 103,
SmallTuple = 104,
LargeTuple = 105,
Nil = 106,
String = 107,
List = 108,
Binary = 109,
SmallBig = 110,
LargeBig = 111,
NewFun = 112,
Export = 113,
NewReference = 114,
SmallAtomDeprecated = 115,
Map = 116,
Fun = 117,
AtomUtf8 = 118,
SmallAtomUtf8 = 119,
}
fn module() -> &'static str {
"external_term_format: "
}
fn fail<TermType: Copy>(msg: String) -> RtResult<TermType> {
Err(RtErr::ETFParseError(msg))
}
/// Given a binary reader `r` parse term and return it, `heap` is used to
/// allocate space for larger boxed terms.
pub fn decode(r: &mut BinaryReader, hp: &mut THeap) -> RtResult<Term> {
let etf_tag = r.read_u8();
if etf_tag != Tag::ETF as u8 {
let msg = format!("{}Expected ETF tag byte 131, got {}", module(), etf_tag);
return fail(msg);
}
decode_naked(r, hp)
}
/// Given an encoded term without ETF tag (131u8), read the term from `r` and
/// place boxed term parts on heap `heap`.
pub fn decode_naked(r: &mut BinaryReader, hp: &mut THeap) -> RtResult<Term> {
let term_tag = r.read_u8();
match term_tag {
x if x == Tag::List as u8 => decode_list(r, hp),
x if x == Tag::String as u8 => decode_string(r, hp),
x if x == Tag::AtomDeprecated as u8 => decode_atom_latin1(r, hp),
x if x == Tag::SmallInteger as u8 => decode_u8(r, hp),
x if x == Tag::Integer as u8 => decode_s32(r, hp),
x if x == Tag::Nil as u8 => Ok(Term::nil()),
x if x == Tag::LargeTuple as u8 => {
let size = r.read_u32be() as Word;
decode_tuple(r, size, hp)
}
x if x == Tag::SmallTuple as u8 => {
let size = r.read_u8() as Word;
decode_tuple(r, size, hp)
}
x if x == Tag::LargeBig as u8 => {
let size = r.read_u32be() as Word;
decode_big(r, size, hp)
}
x if x == Tag::SmallBig as u8 => {
let size = r.read_u8() as Word;
decode_big(r, size, hp)
}
x if x == Tag::Binary as u8 => decode_binary(r, hp),
x if x == Tag::Map as u8 => {
let size = r.read_u32be() as Word;
decode_map(r, size, hp)
}
_ => {
let msg = format!(
"Don't know how to decode ETF value tag 0x{:x} ({})",
term_tag, term_tag
);
fail(msg)
}
}
}
/// Given `size`, read digits for a bigint.
fn decode_big(r: &mut BinaryReader, size: Word, hp: &mut THeap) -> RtResult<Term> {
let sign = if r.read_u8() == 0 {
Sign::Positive
} else {
Sign::Negative
};
let digits = r.read_bytes(size)?;
// Determine storage size in words and create
unsafe { boxed::Bignum::create_le(hp, sign, digits) }
}
fn decode_binary(r: &mut BinaryReader, hp: &mut THeap) -> RtResult<Term> {
let n_bytes = r.read_u32be() as usize;
if n_bytes == 0 {
return Ok(Term::empty_binary());
}
let data = r.read_bytes(n_bytes)?;
unsafe {
let btrait = boxed::Binary::create_with_data(&data, hp)?;
Ok((*btrait).make_term())
}
}
/// Given arity, allocate a tuple and read its elements sequentially.
fn decode_tuple(r: &mut BinaryReader, size: usize, hp: &mut THeap) -> RtResult<Term> {
let tb = TupleBuilder::with_arity(size, hp)?;
for i in 0..size {
let elem = decode_naked(r, hp)?;
unsafe { tb.set_element(i, elem) }
}
Ok(tb.make_term())
}
/// Given size, create a map of given size and read `size` pairs.
fn decode_map(r: &mut BinaryReader, size: usize, hp: &mut THeap) -> RtResult<Term> {
let map_ptr = boxed::Map::create_into(hp, size)?;
for _i in 0..size {
let key = decode_naked(r, hp)?;
let val = decode_naked(r, hp)?;
unsafe { boxed::Map::add(map_ptr, key, val)? }
}
Ok(Term::make_boxed(map_ptr))
}
fn decode_u8(r: &mut BinaryReader, _hp: &mut THeap) -> RtResult<Term> {
let val = r.read_u8();
Ok(Term::make_small_signed(val as SWord))
}
fn decode_s32(r: &mut BinaryReader, _hp: &mut THeap) -> RtResult<Term> {
let val = r.read_u32be() as i32;
Ok(Term::make_small_signed(val as SWord))
}
fn decode_atom_latin1(r: &mut BinaryReader, _hp: &mut THeap) -> RtResult<Term> {
let sz = r.read_u16be();
let val = r.read_str_latin1(sz as Word).unwrap();
Ok(atom::from_str(&val))
}
fn decode_list(r: &mut BinaryReader, hp: &mut THeap) -> RtResult<Term> {
let n_elem = r.read_u32be();
if n_elem == 0 {
return Ok(Term::nil());
}
let mut lb = ListBuilder::new()?;
for _i in 0..n_elem {
let another = decode_naked(r, hp)?;
unsafe {
lb.append(another, hp)?;
}
}
// Decode tail, possibly a nil
let tl = decode_naked(r, hp)?;
unsafe { Ok(lb.make_term_with_tail(tl)) }
}
/// A string of bytes encoded as tag 107 (String) with 16-bit length.
fn decode_string(r: &mut BinaryReader, hp: &mut THeap) -> RtResult<Term> {
let n_elem = r.read_u16be();
if n_elem == 0 {
return Ok(Term::nil());
}
// Using mutability build list forward creating many cells and linking them
let mut lb = ListBuilder::new()?;
for _i in 0..n_elem {
let elem = r.read_u8();
unsafe {
let another = Term::make_small_signed(elem as SWord);
lb.append(another, hp)?;
}
}
Ok(lb.make_term())
}
| 25.465753 | 86 | 0.613771 |
5b632ae755c556cbe72d221752b009de352e5290 | 3,858 | use std::rc::Rc;
use super::state::*;
use shared::{
api::endpoints::{ApiEndpoint, user::*,},
domain::auth::SigninSuccess,
error::EmptyError
};
use utils::{
routes::*,
firebase::*,
fetch::api_with_token,
storage,
};
use dominator::clone;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::{JsFuture, spawn_local, future_to_promise};
use crate::firebase::*;
use futures_signals::signal::{Mutable, Signal, SignalExt};
use futures::future::ready;
use crate::register::state::{Step, StartData};
pub fn register_email(state: Rc<State>) {
state.clear_email_status();
state.clear_password_status();
let mut early_exit = false;
if state.password_strength.get() != PasswordStrength::Strong {
state.password_status.set(Some(PasswordStatus::PwWeak));
early_exit = true;
}
let email:String = state.email.borrow().clone();
let password:String = state.password.borrow().clone();
if email.is_empty() {
state.email_status.set(Some(EmailStatus::EmptyEmail));
early_exit = true;
}
if early_exit {
return;
}
state.loader.load(clone!(state => async move {
let token_promise = unsafe { firebase_register_email(&email, &password) };
match JsFuture::from(token_promise).await {
Ok(info) => {
let user:EmailUserInfo = serde_wasm_bindgen::from_value(info).unwrap_throw();
next_step(state, user.token, user.email, user.email_verified);
},
Err(err) => {
match serde_wasm_bindgen::from_value::<FirebaseError>(err) {
Ok(err) => {
log::info!("{:?}", err);
match err.code.as_ref() {
"auth/invalid-email" => state.email_status.set(Some(EmailStatus::InvalidEmail)),
"auth/email-already-in-use" => state.email_status.set(Some(EmailStatus::EmailExists)),
//TODO - remove this check?
//If we trust our own vetting - should be fine
//and it's possible for the two approaches to be out of sync
"auth/weak-password" => {
log::warn!("firebase says it's weak... this shouldn't happen!");
state.password_strength.set(PasswordStrength::Weak);
state.password_status.set(Some(PasswordStatus::PwWeak))
},
_ => state.email_status.set(Some(EmailStatus::UnknownFirebase))
}
},
Err(_) => {
state.email_status.set(Some(EmailStatus::Technical));
}
}
}
}
}));
}
pub fn register_google(state: Rc<State>) {
state.clear_email_status();
state.clear_password_status();
state.loader.load(clone!(state => async move {
let token_promise = unsafe { firebase_register_google() };
match JsFuture::from(token_promise).await {
Ok(info) => {
let user:GoogleUserInfo = serde_wasm_bindgen::from_value(info).unwrap_throw();
next_step(state, user.token, user.email, user.email_verified);
},
Err(err) => {
//Just canceled?
state.email_status.set(None);
}
}
}));
}
fn next_step(state: Rc<State>, token: String, email: String, email_verified: bool) {
state.step.set(Step::One(StartData{token, email, email_verified}));
}
pub fn update_password_strength(state: &Rc<State>) {
let password:&str = &state.password.borrow();
state.password_strength.set(PasswordStrength::Strong);
//TODO...
}
| 33.547826 | 114 | 0.558061 |
db564a7e8abb31c5335366943a984f302a740bd3 | 1,552 | use core::fmt;
//use super::rdma_socket::*;
use super::super::super::qlib::kernel::guestfdnotifier::*;
use super::super::super::qlib::linux_def::*;
#[derive(Clone)]
pub enum SockInfo {
File, // it is not socket
Socket, // normal socket
//RDMAServerSocket(RDMAServerSock), //
//RDMADataSocket(RDMADataSock), //
//RDMAContext,
}
impl fmt::Debug for SockInfo {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::File => write!(f, "SockInfo::File"),
Self::Socket => write!(f, "SockInfo::Socket"),
//Self::RDMAServerSocket(_) => write!(f, "SockInfo::RDMAServerSocket"),
//Self::RDMADataSocket(_) => write!(f, "SockInfo::RDMADataSocket"),
//Self::RDMAContext => write!(f, "SockInfo::RDMAContext"),
}
}
}
impl SockInfo {
pub fn Notify(&self, eventmask: EventMask, waitinfo: FdWaitInfo) {
match self {
Self::File => {
waitinfo.Notify(eventmask);
}
Self::Socket => {
waitinfo.Notify(eventmask);
} /*Self::RDMAServerSocket(ref sock) => {
sock.Notify(eventmask, waitinfo)
}
Self::RDMADataSocket(ref sock) => {
sock.Notify(eventmask, waitinfo)
}
Self::RDMAContext => {
//RDMA.PollCompletion().expect("RDMA.PollCompletion fail");
//error!("RDMAContextEpoll");
}*/
}
}
}
| 31.673469 | 83 | 0.525129 |
ab382ad9b2f66cdf09a62a996fc799ef204423ea | 1,047 | use super::*;
use rand;
/// Python random policy
py_class!(pub class PyPolicy |py| {
def __call__(&self, _turn: PyObject, boards: PyObject) -> PyResult<PyObject> {
let len = boards.cast_into::<PyList>(py)?.len(py);
let value = (0..len)
.map(|_| rand::random::<f32>().to_py_object(py).into_object())
.collect::<Vec<PyObject>>();
let value = PyList::new(py, value.as_slice()).into_object();
let policy = (0..len).map(|_| {
let rand_policy = (0..BOARD_CAPACITY)
.map(|_| rand::random::<f32>().to_py_object(py).into_object())
.collect::<Vec<PyObject>>();
PyList::new(py, rand_policy.as_slice()).into_object()
}).collect::<Vec<PyObject>>();
let policy = PyList::new(py, policy.as_slice()).into_object();
Ok(PyTuple::new(py, &[value, policy]).into_object())
}
});
/// py_policy generator
#[allow(dead_code)]
pub fn create_pypolicy(py: Python) -> PyResult<PyPolicy> {
PyPolicy::create_instance(py)
}
| 32.71875 | 82 | 0.585482 |
cc636163e3c0bcbc77224ce2ecf001012b54af6d | 2,348 | // Copyright 2020 Nym Technologies SA
//
// 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.
// Commenting config out temporarily, we'll undoubtedly need it back soon.
// use crate::commands::override_config;
// use crate::config::Config;
// use config::NymConfig;
use crate::validator::Validator;
use clap::{App, Arg, ArgMatches};
pub fn command_args<'a, 'b>() -> clap::App<'a, 'b> {
App::new("run")
.about("Starts the validator")
.arg(
Arg::with_name("id")
.long("id")
.help("Id of the nym-validator we want to run")
.takes_value(true)
.required(true),
)
// the rest of arguments are optional, they are used to override settings in config file
.arg(
Arg::with_name("location")
.long("location")
.help("Optional geographical location of this node")
.takes_value(true),
)
.arg(
Arg::with_name("config")
.long("config")
.help("Custom path to the nym-validator configuration file")
.takes_value(true),
)
.arg(
Arg::with_name("directory")
.long("directory")
.help("Address of the directory server the validator is sending presence to and uses for mix mining")
.takes_value(true),
)
}
pub fn execute(matches: &ArgMatches) {
let id = matches.value_of("id").unwrap();
println!("Starting validator {}...", id);
// let mut config =
// Config::load_from_file(matches.value_of("config").map(|path| path.into()), Some(id))
// .expect("Failed to load config file");
// config = override_config(config, matches);
let validator = Validator::new();
validator.start()
}
| 35.044776 | 117 | 0.601789 |
8f66034db81f14bd5f12e16db9a761e7f1c84054 | 67,603 | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
diag,
expansion::ast::{self as E, AbilitySet, Fields, ModuleIdent},
hlir::ast::{self as H, Block, MoveOpAnnotation},
naming::ast as N,
parser::ast::{BinOp_, ConstantName, Field, FunctionName, StructName, Var},
shared::{unique_map::UniqueMap, *},
typing::ast as T,
FullyCompiledProgram,
};
use move_ir_types::location::*;
use move_symbol_pool::Symbol;
use once_cell::sync::Lazy;
use std::{
collections::{BTreeMap, BTreeSet, VecDeque},
convert::TryInto,
};
//**************************************************************************************************
// Vars
//**************************************************************************************************
const NEW_NAME_DELIM: &str = "#";
fn new_name(context: &mut Context, n: Symbol) -> Symbol {
format!("{}{}{}", n, NEW_NAME_DELIM, context.counter_next()).into()
}
const TEMP_PREFIX: &str = "%";
static TEMP_PREFIX_SYMBOL: Lazy<Symbol> = Lazy::new(|| TEMP_PREFIX.into());
fn new_temp_name(context: &mut Context) -> Symbol {
new_name(context, *TEMP_PREFIX_SYMBOL)
}
pub fn is_temp_name(s: Symbol) -> bool {
s.starts_with(TEMP_PREFIX)
}
pub enum DisplayVar {
Orig(String),
Tmp,
}
pub fn display_var(s: Symbol) -> DisplayVar {
if is_temp_name(s) {
DisplayVar::Tmp
} else {
let mut orig = s.as_str().to_string();
orig.truncate(orig.find('#').unwrap_or(s.len()));
DisplayVar::Orig(orig)
}
}
//**************************************************************************************************
// Context
//**************************************************************************************************
struct Context<'env> {
env: &'env mut CompilationEnv,
structs: UniqueMap<StructName, UniqueMap<Field, usize>>,
function_locals: UniqueMap<Var, H::SingleType>,
local_scope: UniqueMap<Var, Var>,
used_locals: BTreeSet<Var>,
signature: Option<H::FunctionSignature>,
tmp_counter: usize,
}
impl<'env> Context<'env> {
pub fn new(env: &'env mut CompilationEnv) -> Self {
Context {
env,
structs: UniqueMap::new(),
function_locals: UniqueMap::new(),
local_scope: UniqueMap::new(),
used_locals: BTreeSet::new(),
signature: None,
tmp_counter: 0,
}
}
pub fn has_empty_locals(&self) -> bool {
self.function_locals.is_empty() && self.local_scope.is_empty()
}
pub fn extract_function_locals(&mut self) -> (UniqueMap<Var, H::SingleType>, BTreeSet<Var>) {
self.local_scope = UniqueMap::new();
self.tmp_counter = 0;
let locals = std::mem::replace(&mut self.function_locals, UniqueMap::new());
let used = std::mem::take(&mut self.used_locals);
(locals, used)
}
pub fn new_temp(&mut self, loc: Loc, t: H::SingleType) -> Var {
let new_var = Var(sp(loc, new_temp_name(self)));
self.function_locals.add(new_var, t).unwrap();
self.local_scope.add(new_var, new_var).unwrap();
self.used_locals.insert(new_var);
new_var
}
pub fn bind_local(&mut self, v: Var, t: H::SingleType) {
let new_var = if !self.function_locals.contains_key(&v) {
v
} else {
Var(sp(v.loc(), new_name(self, v.value())))
};
self.function_locals.add(new_var, t).unwrap();
self.local_scope.remove(&v);
assert!(!self.local_scope.contains_key(&new_var));
self.local_scope.add(v, new_var).unwrap();
}
pub fn remapped_local(&mut self, v: Var) -> Var {
let remapped = *self.local_scope.get(&v).unwrap();
self.used_locals.insert(remapped);
remapped
}
pub fn add_struct_fields(&mut self, structs: &UniqueMap<StructName, H::StructDefinition>) {
assert!(self.structs.is_empty());
for (sname, sdef) in structs.key_cloned_iter() {
let mut fields = UniqueMap::new();
let field_map = match &sdef.fields {
H::StructFields::Native(_) => continue,
H::StructFields::Defined(m) => m,
};
for (idx, (field, _)) in field_map.iter().enumerate() {
fields.add(*field, idx).unwrap();
}
self.structs.add(sname, fields).unwrap();
}
}
pub fn fields(&self, struct_name: &StructName) -> Option<&UniqueMap<Field, usize>> {
let fields = self.structs.get(struct_name);
// if fields are none, the struct must be defined in another module,
// in that case, there should be errors
assert!(fields.is_some() || self.env.has_diags());
fields
}
fn counter_next(&mut self) -> usize {
self.tmp_counter += 1;
self.tmp_counter
}
}
//**************************************************************************************************
// Entry
//**************************************************************************************************
pub fn program(
compilation_env: &mut CompilationEnv,
_pre_compiled_lib: Option<&FullyCompiledProgram>,
prog: T::Program,
) -> H::Program {
let mut context = Context::new(compilation_env);
let T::Program {
modules: tmodules,
scripts: tscripts,
} = prog;
let modules = modules(&mut context, tmodules);
let scripts = scripts(&mut context, tscripts);
H::Program { modules, scripts }
}
fn modules(
context: &mut Context,
modules: UniqueMap<ModuleIdent, T::ModuleDefinition>,
) -> UniqueMap<ModuleIdent, H::ModuleDefinition> {
let hlir_modules = modules
.into_iter()
.map(|(mname, m)| module(context, mname, m));
UniqueMap::maybe_from_iter(hlir_modules).unwrap()
}
fn module(
context: &mut Context,
module_ident: ModuleIdent,
mdef: T::ModuleDefinition,
) -> (ModuleIdent, H::ModuleDefinition) {
let T::ModuleDefinition {
attributes,
is_source_module,
dependency_order,
friends,
structs: tstructs,
functions: tfunctions,
constants: tconstants,
} = mdef;
let structs = tstructs.map(|name, s| struct_def(context, name, s));
context.add_struct_fields(&structs);
let constants = tconstants.map(|name, c| constant(context, name, c));
let functions = tfunctions.map(|name, f| function(context, name, f));
context.structs = UniqueMap::new();
(
module_ident,
H::ModuleDefinition {
attributes,
is_source_module,
dependency_order,
friends,
structs,
constants,
functions,
},
)
}
fn scripts(
context: &mut Context,
tscripts: BTreeMap<Symbol, T::Script>,
) -> BTreeMap<Symbol, H::Script> {
tscripts
.into_iter()
.map(|(n, s)| (n, script(context, s)))
.collect()
}
fn script(context: &mut Context, tscript: T::Script) -> H::Script {
let T::Script {
attributes,
loc,
constants: tconstants,
function_name,
function: tfunction,
} = tscript;
let constants = tconstants.map(|name, c| constant(context, name, c));
let function = function(context, function_name, tfunction);
H::Script {
attributes,
loc,
constants,
function_name,
function,
}
}
//**************************************************************************************************
// Functions
//**************************************************************************************************
fn function(context: &mut Context, _name: FunctionName, f: T::Function) -> H::Function {
assert!(context.has_empty_locals());
assert!(context.tmp_counter == 0);
let attributes = f.attributes;
let visibility = f.visibility;
let signature = function_signature(context, f.signature);
let acquires = f.acquires;
let body = function_body(context, &signature, f.body);
H::Function {
attributes,
visibility,
signature,
acquires,
body,
}
}
fn function_signature(context: &mut Context, sig: N::FunctionSignature) -> H::FunctionSignature {
let type_parameters = sig.type_parameters;
let parameters = sig
.parameters
.into_iter()
.map(|(v, tty)| {
let ty = single_type(context, tty);
context.bind_local(v, ty.clone());
(v, ty)
})
.collect();
let return_type = type_(context, sig.return_type);
H::FunctionSignature {
type_parameters,
parameters,
return_type,
}
}
fn function_body(
context: &mut Context,
sig: &H::FunctionSignature,
sp!(loc, tb_): T::FunctionBody,
) -> H::FunctionBody {
use H::FunctionBody_ as HB;
use T::FunctionBody_ as TB;
let b_ = match tb_ {
TB::Native => {
context.extract_function_locals();
HB::Native
}
TB::Defined(seq) => {
let (locals, body) = function_body_defined(context, sig, loc, seq);
HB::Defined { locals, body }
}
};
sp(loc, b_)
}
fn function_body_defined(
context: &mut Context,
signature: &H::FunctionSignature,
loc: Loc,
seq: T::Sequence,
) -> (UniqueMap<Var, H::SingleType>, Block) {
let mut body = VecDeque::new();
context.signature = Some(signature.clone());
let final_exp = block(context, &mut body, loc, Some(&signature.return_type), seq);
match &final_exp.exp.value {
H::UnannotatedExp_::Unreachable => (),
_ => {
use H::{Command_ as C, Statement_ as S};
let eloc = final_exp.exp.loc;
let ret = sp(
eloc,
C::Return {
from_user: false,
exp: final_exp,
},
);
body.push_back(sp(eloc, S::Command(ret)))
}
}
let (mut locals, used) = context.extract_function_locals();
let unused = check_unused_locals(context, &mut locals, used);
check_trailing_unit(context, &mut body);
remove_unused_bindings(&unused, &mut body);
context.signature = None;
(locals, body)
}
//**************************************************************************************************
// Constants
//**************************************************************************************************
fn constant(context: &mut Context, _name: ConstantName, cdef: T::Constant) -> H::Constant {
let T::Constant {
attributes,
loc,
signature: tsignature,
value: tvalue,
} = cdef;
let signature = base_type(context, tsignature);
let eloc = tvalue.exp.loc;
let tseq = {
let mut v = T::Sequence::new();
v.push_back(sp(eloc, T::SequenceItem_::Seq(Box::new(tvalue))));
v
};
let function_signature = H::FunctionSignature {
type_parameters: vec![],
parameters: vec![],
return_type: H::Type_::base(signature.clone()),
};
let (locals, body) = function_body_defined(context, &function_signature, eloc, tseq);
H::Constant {
attributes,
loc,
signature,
value: (locals, body),
}
}
//**************************************************************************************************
// Structs
//**************************************************************************************************
fn struct_def(
context: &mut Context,
_name: StructName,
sdef: N::StructDefinition,
) -> H::StructDefinition {
let attributes = sdef.attributes;
let abilities = sdef.abilities;
let type_parameters = sdef.type_parameters;
let fields = struct_fields(context, sdef.fields);
H::StructDefinition {
attributes,
abilities,
type_parameters,
fields,
}
}
fn struct_fields(context: &mut Context, tfields: N::StructFields) -> H::StructFields {
let tfields_map = match tfields {
N::StructFields::Native(loc) => return H::StructFields::Native(loc),
N::StructFields::Defined(m) => m,
};
let mut indexed_fields = tfields_map
.into_iter()
.map(|(f, (idx, t))| (idx, (f, base_type(context, t))))
.collect::<Vec<_>>();
indexed_fields.sort_by(|(idx1, _), (idx2, _)| idx1.cmp(idx2));
H::StructFields::Defined(indexed_fields.into_iter().map(|(_, f_ty)| f_ty).collect())
}
//**************************************************************************************************
// Types
//**************************************************************************************************
fn type_name(_context: &Context, sp!(loc, ntn_): N::TypeName) -> H::TypeName {
use H::TypeName_ as HT;
use N::TypeName_ as NT;
let tn_ = match ntn_ {
NT::Multiple(_) => panic!(
"ICE type constraints failed {}:{}-{}",
loc.file_hash(),
loc.start(),
loc.end()
),
NT::Builtin(bt) => HT::Builtin(bt),
NT::ModuleType(m, s) => HT::ModuleType(m, s),
};
sp(loc, tn_)
}
fn base_types<R: std::iter::FromIterator<H::BaseType>>(
context: &Context,
tys: impl IntoIterator<Item = N::Type>,
) -> R {
tys.into_iter().map(|t| base_type(context, t)).collect()
}
fn base_type(context: &Context, sp!(loc, nb_): N::Type) -> H::BaseType {
use H::BaseType_ as HB;
use N::Type_ as NT;
let b_ = match nb_ {
NT::Var(_) => panic!(
"ICE tvar not expanded: {}:{}-{}",
loc.file_hash(),
loc.start(),
loc.end()
),
NT::Apply(None, n, tys) => {
crate::shared::ast_debug::print_verbose(&NT::Apply(None, n, tys));
panic!("ICE kind not expanded: {:#?}", loc)
}
NT::Apply(Some(k), n, nbs) => HB::Apply(k, type_name(context, n), base_types(context, nbs)),
NT::Param(tp) => HB::Param(tp),
NT::UnresolvedError => HB::UnresolvedError,
NT::Anything => HB::Unreachable,
NT::Ref(_, _) | NT::Unit => {
panic!(
"ICE type constraints failed {}:{}-{}",
loc.file_hash(),
loc.start(),
loc.end()
)
}
};
sp(loc, b_)
}
fn expected_types(context: &Context, loc: Loc, nss: Vec<Option<N::Type>>) -> H::Type {
let any = || {
sp(
loc,
H::SingleType_::Base(sp(loc, H::BaseType_::UnresolvedError)),
)
};
let ss = nss
.into_iter()
.map(|sopt| sopt.map(|s| single_type(context, s)).unwrap_or_else(any))
.collect::<Vec<_>>();
H::Type_::from_vec(loc, ss)
}
fn single_types(context: &Context, ss: Vec<N::Type>) -> Vec<H::SingleType> {
ss.into_iter().map(|s| single_type(context, s)).collect()
}
fn single_type(context: &Context, sp!(loc, ty_): N::Type) -> H::SingleType {
use H::SingleType_ as HS;
use N::Type_ as NT;
let s_ = match ty_ {
NT::Ref(mut_, nb) => HS::Ref(mut_, base_type(context, *nb)),
_ => HS::Base(base_type(context, sp(loc, ty_))),
};
sp(loc, s_)
}
fn type_(context: &Context, sp!(loc, ty_): N::Type) -> H::Type {
use H::Type_ as HT;
use N::{TypeName_ as TN, Type_ as NT};
let t_ = match ty_ {
NT::Unit => HT::Unit,
NT::Apply(None, n, tys) => {
crate::shared::ast_debug::print_verbose(&NT::Apply(None, n, tys));
panic!("ICE kind not expanded: {:#?}", loc)
}
NT::Apply(Some(_), sp!(_, TN::Multiple(_)), ss) => HT::Multiple(single_types(context, ss)),
_ => HT::Single(single_type(context, sp(loc, ty_))),
};
sp(loc, t_)
}
//**************************************************************************************************
// Statements
//**************************************************************************************************
fn block(
context: &mut Context,
result: &mut Block,
loc: Loc,
expected_type_opt: Option<&H::Type>,
mut seq: T::Sequence,
) -> H::Exp {
use T::SequenceItem_ as S;
let last = match seq.pop_back() {
None => {
return H::exp(
sp(loc, H::Type_::Unit),
sp(
loc,
H::UnannotatedExp_::Unit {
case: H::UnitCase::FromUser,
},
),
)
}
Some(sp!(_, S::Seq(last))) => last,
Some(_) => panic!("ICE last sequence item should be exp"),
};
let old_scope = context.local_scope.clone();
for sp!(sloc, seq_item_) in seq {
match seq_item_ {
S::Seq(te) => statement(context, result, *te),
S::Declare(binds) => declare_bind_list(context, &binds),
S::Bind(binds, ty, e) => {
let expected_tys = expected_types(context, sloc, ty);
let res = exp_(context, result, Some(&expected_tys), *e);
declare_bind_list(context, &binds);
assign_command(context, result, sloc, binds, res);
}
}
}
let res = exp_(context, result, expected_type_opt, *last);
context.local_scope = old_scope;
res
}
fn statement(context: &mut Context, result: &mut Block, e: T::Exp) {
use H::Statement_ as S;
use T::UnannotatedExp_ as TE;
let ty = e.ty;
let sp!(eloc, e_) = e.exp;
let stmt_ = match e_ {
TE::IfElse(tb, tt, tf) => {
let cond = exp(context, result, None, *tb);
let mut if_block = Block::new();
let et = exp_(context, &mut if_block, None, *tt);
ignore_and_pop(&mut if_block, et);
let mut else_block = Block::new();
let ef = exp_(context, &mut else_block, None, *tf);
ignore_and_pop(&mut else_block, ef);
S::IfElse {
cond,
if_block,
else_block,
}
}
TE::While(tb, loop_body) => {
let mut cond_block = Block::new();
let cond_exp = exp(context, &mut cond_block, None, *tb);
let mut loop_block = Block::new();
let el = exp_(context, &mut loop_block, None, *loop_body);
ignore_and_pop(&mut loop_block, el);
S::While {
cond: (cond_block, cond_exp),
block: loop_block,
}
}
TE::Loop {
body: loop_body,
has_break,
} => {
let loop_block = statement_loop_body(context, *loop_body);
S::Loop {
block: loop_block,
has_break,
}
}
TE::Block(seq) => {
let res = block(context, result, eloc, None, seq);
ignore_and_pop(result, res);
return;
}
e_ => {
let te = T::exp(ty, sp(eloc, e_));
let e = exp_(context, result, None, te);
ignore_and_pop(result, e);
return;
}
};
result.push_back(sp(eloc, stmt_))
}
fn statement_loop_body(context: &mut Context, body: T::Exp) -> Block {
let mut loop_block = Block::new();
let el = exp_(context, &mut loop_block, None, body);
ignore_and_pop(&mut loop_block, el);
loop_block
}
//**************************************************************************************************
// LValue
//**************************************************************************************************
fn declare_bind_list(context: &mut Context, sp!(_, binds): &T::LValueList) {
binds.iter().for_each(|b| declare_bind(context, b))
}
fn declare_bind(context: &mut Context, sp!(_, bind_): &T::LValue) {
use T::LValue_ as L;
match bind_ {
L::Ignore => (),
L::Var(v, ty) => {
let st = single_type(context, *ty.clone());
context.bind_local(*v, st)
}
L::Unpack(_, _, _, fields) | L::BorrowUnpack(_, _, _, _, fields) => fields
.iter()
.for_each(|(_, _, (_, (_, b)))| declare_bind(context, b)),
}
}
fn assign_command(
context: &mut Context,
result: &mut Block,
loc: Loc,
sp!(_, assigns): T::LValueList,
rvalue: H::Exp,
) {
use H::{Command_ as C, Statement_ as S};
let mut lvalues = vec![];
let mut after = Block::new();
for (idx, a) in assigns.into_iter().enumerate() {
let a_ty = rvalue.ty.value.type_at_index(idx);
let (ls, mut af) = assign(context, result, a, a_ty);
lvalues.push(ls);
after.append(&mut af);
}
result.push_back(sp(
loc,
S::Command(sp(loc, C::Assign(lvalues, Box::new(rvalue)))),
));
result.append(&mut after);
}
fn assign(
context: &mut Context,
result: &mut Block,
sp!(loc, ta_): T::LValue,
rvalue_ty: &H::SingleType,
) -> (H::LValue, Block) {
use H::{LValue_ as L, UnannotatedExp_ as E};
use T::LValue_ as A;
let mut after = Block::new();
let l_ = match ta_ {
A::Ignore => L::Ignore,
A::Var(v, st) => L::Var(
context.remapped_local(v),
Box::new(single_type(context, *st)),
),
A::Unpack(_m, s, tbs, tfields) => {
let bs = base_types(context, tbs);
let mut fields = vec![];
for (decl_idx, f, bt, tfa) in assign_fields(context, &s, tfields) {
assert!(fields.len() == decl_idx);
let st = &H::SingleType_::base(bt);
let (fa, mut fafter) = assign(context, result, tfa, st);
after.append(&mut fafter);
fields.push((f, fa))
}
L::Unpack(s, bs, fields)
}
A::BorrowUnpack(mut_, _m, s, _tss, tfields) => {
let tmp = context.new_temp(loc, rvalue_ty.clone());
let copy_tmp = || {
let copy_tmp_ = E::Copy {
from_user: false,
var: tmp,
};
H::exp(H::Type_::single(rvalue_ty.clone()), sp(loc, copy_tmp_))
};
let fields = assign_fields(context, &s, tfields).into_iter().enumerate();
for (idx, (decl_idx, f, bt, tfa)) in fields {
assert!(idx == decl_idx);
let floc = tfa.loc;
let borrow_ = E::Borrow(mut_, Box::new(copy_tmp()), f);
let borrow_ty = H::Type_::single(sp(floc, H::SingleType_::Ref(mut_, bt)));
let borrow = H::exp(borrow_ty, sp(floc, borrow_));
assign_command(context, &mut after, floc, sp(floc, vec![tfa]), borrow);
}
L::Var(tmp, Box::new(rvalue_ty.clone()))
}
};
(sp(loc, l_), after)
}
fn assign_fields(
context: &Context,
s: &StructName,
tfields: Fields<(N::Type, T::LValue)>,
) -> Vec<(usize, Field, H::BaseType, T::LValue)> {
let decl_fields = context.fields(s);
let mut count = 0;
let mut decl_field = |f: &Field| -> usize {
match decl_fields {
Some(m) => *m.get(f).unwrap(),
None => {
// none can occur with errors in typing
let i = count;
count += 1;
i
}
}
};
let mut tfields_vec = tfields
.into_iter()
.map(|(f, (_idx, (tbt, tfa)))| (decl_field(&f), f, base_type(context, tbt), tfa))
.collect::<Vec<_>>();
tfields_vec.sort_by(|(idx1, _, _, _), (idx2, _, _, _)| idx1.cmp(idx2));
tfields_vec
}
//**************************************************************************************************
// Commands
//**************************************************************************************************
fn ignore_and_pop(result: &mut Block, e: H::Exp) {
match &e.exp.value {
H::UnannotatedExp_::Unreachable => (),
_ => {
let pop_num = match &e.ty.value {
H::Type_::Unit => 0,
H::Type_::Single(_) => 1,
H::Type_::Multiple(tys) => tys.len(),
};
let loc = e.exp.loc;
let c = sp(loc, H::Command_::IgnoreAndPop { pop_num, exp: e });
result.push_back(sp(loc, H::Statement_::Command(c)))
}
}
}
//**************************************************************************************************
// Expressions
//**************************************************************************************************
fn exp(
context: &mut Context,
result: &mut Block,
expected_type_opt: Option<&H::Type>,
te: T::Exp,
) -> Box<H::Exp> {
Box::new(exp_(context, result, expected_type_opt, te))
}
fn exp_<'env>(
context: &mut Context<'env>,
result: &mut Block,
initial_expected_type_opt: Option<&H::Type>,
initial_e: T::Exp,
) -> H::Exp {
use std::{cell::RefCell, rc::Rc};
struct Stack<'a, 'env> {
frames: Vec<Box<dyn FnOnce(&mut Self)>>,
operands: Vec<H::Exp>,
context: &'a mut Context<'env>,
}
macro_rules! inner {
($block:expr, $exp_ty_opt:expr, $e:expr) => {{
let e_result = $block.clone();
let e_exp_ty_opt = $exp_ty_opt;
move |s: &mut Stack| exp_loop(s, e_result, e_exp_ty_opt, $e)
}};
}
fn maybe_freeze(
context: &mut Context,
result: &mut Block,
expected_type_opt: Option<H::Type>,
e: H::Exp,
) -> H::Exp {
match (&e.exp.value, expected_type_opt.as_ref()) {
(H::UnannotatedExp_::Unreachable, _) => e,
(_, Some(exty)) if needs_freeze(context, &e.ty, exty) != Freeze::NotNeeded => {
freeze(context, result, exty, e)
}
_ => e,
}
}
fn exp_loop(
stack: &mut Stack,
result: Rc<RefCell<Block>>,
cur_expected_type_opt: Option<H::Type>,
cur: Box<T::Exp>,
) {
use H::{Statement_ as S, UnannotatedExp_ as HE};
use T::UnannotatedExp_ as TE;
let (tty, sp!(loc, cur_)) = (cur.ty, cur.exp);
let ty = type_(stack.context, tty);
match cur_ {
//***********************************************
// Stack-ified traversal
//***********************************************
TE::IfElse(cond, if_true, if_false) => {
let f_cond = inner!(result, None, cond);
let if_block = Rc::new(RefCell::new(Block::new()));
let f_if = inner!(if_block, Some(ty.clone()), if_true);
let else_block = Rc::new(RefCell::new(Block::new()));
let f_else = inner!(else_block, Some(ty.clone()), if_false);
let f_if_else = move |s: &mut Stack| {
let ef = s.operands.pop().unwrap();
let et = s.operands.pop().unwrap();
let cond = Box::new(s.operands.pop().unwrap());
let mut if_block = Rc::try_unwrap(if_block).unwrap().into_inner();
let mut else_block = Rc::try_unwrap(else_block).unwrap().into_inner();
let result = &mut *result.borrow_mut();
let e_ = match (&et.exp.value, &ef.exp.value) {
(HE::Unreachable, HE::Unreachable) => {
let s_ = S::IfElse {
cond,
if_block,
else_block,
};
result.push_back(sp(loc, s_));
HE::Unreachable
}
_ => {
let tmps = make_temps(s.context, loc, ty.clone());
let tres = bind_exp_(&mut if_block, loc, tmps.clone(), et);
let fres = bind_exp_(&mut else_block, loc, tmps, ef);
let s_ = S::IfElse {
cond,
if_block,
else_block,
};
result.push_back(sp(loc, s_));
match (tres, fres) {
(HE::Unreachable, HE::Unreachable) => unreachable!(),
(HE::Unreachable, res) | (res, HE::Unreachable) | (res, _) => res,
}
}
};
let e_res = H::exp(ty, sp(loc, e_));
// each branch is frozen so no need to freeze
s.operands.push(e_res)
};
stack.frames.push(Box::new(f_if_else));
stack.frames.push(Box::new(f_else));
stack.frames.push(Box::new(f_if));
stack.frames.push(Box::new(f_cond));
}
TE::BinopExp(lhs, op, toperand_ty, rhs) => {
let operand_exp_ty_opt = match &op.value {
BinOp_::And if bind_for_short_circuit(&rhs) => {
let tfalse_ = sp(loc, TE::Value(sp(loc, E::Value_::Bool(false))));
let tfalse = Box::new(T::exp(N::Type_::bool(loc), tfalse_));
let if_else_ = sp(loc, TE::IfElse(lhs, rhs, tfalse));
let if_else = Box::new(T::exp(N::Type_::bool(ty.loc), if_else_));
return exp_loop(stack, result, cur_expected_type_opt, if_else);
}
BinOp_::Or if bind_for_short_circuit(&rhs) => {
let ttrue_ = sp(loc, TE::Value(sp(loc, E::Value_::Bool(true))));
let ttrue = Box::new(T::exp(N::Type_::bool(loc), ttrue_));
let if_else_ = sp(loc, TE::IfElse(lhs, ttrue, rhs));
let if_else = Box::new(T::exp(N::Type_::bool(ty.loc), if_else_));
return exp_loop(stack, result, cur_expected_type_opt, if_else);
}
BinOp_::Eq | BinOp_::Neq => {
let operand_ty = type_(stack.context, *toperand_ty);
Some(freeze_ty(operand_ty))
}
_ => None,
};
let f_lhs = inner!(result, operand_exp_ty_opt.clone(), lhs);
let f_rhs = inner!(result, operand_exp_ty_opt, rhs);
let f_binop = move |s: &mut Stack| {
let rhs = Box::new(s.operands.pop().unwrap());
let lhs = Box::new(s.operands.pop().unwrap());
let result = &mut *result.borrow_mut();
let e_res = H::exp(ty, sp(loc, HE::BinopExp(lhs, op, rhs)));
let e_res = maybe_freeze(s.context, result, cur_expected_type_opt, e_res);
s.operands.push(e_res)
};
stack.frames.push(Box::new(f_binop));
stack.frames.push(Box::new(f_rhs));
stack.frames.push(Box::new(f_lhs));
}
TE::Builtin(bt, arguments)
if matches!(&*bt, sp!(_, T::BuiltinFunction_::Assert(false))) =>
{
let tbool = N::Type_::bool(loc);
let tu64 = N::Type_::u64(loc);
let tunit = sp(loc, N::Type_::Unit);
let vcond = Var(sp(loc, new_temp_name(stack.context)));
let vcode = Var(sp(loc, new_temp_name(stack.context)));
let mut stmts = VecDeque::new();
let bvar = |v, st| sp(loc, T::LValue_::Var(v, st));
let bind_list = sp(
loc,
vec![
bvar(vcond, Box::new(tbool.clone())),
bvar(vcode, Box::new(tu64.clone())),
],
);
let tys = vec![Some(tbool.clone()), Some(tu64.clone())];
let bind = sp(loc, T::SequenceItem_::Bind(bind_list, tys, arguments));
stmts.push_back(bind);
let mvar = |var, st| {
let from_user = false;
let mv = TE::Move { from_user, var };
T::exp(st, sp(loc, mv))
};
let econd = mvar(vcond, tu64);
let ecode = mvar(vcode, tbool);
let eabort = T::exp(tunit.clone(), sp(loc, TE::Abort(Box::new(ecode))));
let eunit = T::exp(tunit.clone(), sp(loc, TE::Unit { trailing: false }));
let inlined_ = TE::IfElse(Box::new(econd), Box::new(eunit), Box::new(eabort));
let inlined = T::exp(tunit.clone(), sp(loc, inlined_));
stmts.push_back(sp(loc, T::SequenceItem_::Seq(Box::new(inlined))));
let block = T::exp(tunit, sp(loc, TE::Block(stmts)));
exp_loop(stack, result, cur_expected_type_opt, Box::new(block));
}
TE::Builtin(bt, arguments)
if matches!(&*bt, sp!(_, T::BuiltinFunction_::Assert(true))) =>
{
use T::ExpListItem as TI;
let tunit = sp(loc, N::Type_::Unit);
let [cond_item, code_item]: [TI; 2] = match arguments.exp.value {
TE::ExpList(arg_list) => arg_list.try_into().unwrap(),
_ => panic!("ICE type checking failed"),
};
let (econd, ecode) = match (cond_item, code_item) {
(TI::Single(econd, _), TI::Single(ecode, _)) => (econd, ecode),
_ => panic!("ICE type checking failed"),
};
let eabort = T::exp(tunit.clone(), sp(loc, TE::Abort(Box::new(ecode))));
let eunit = T::exp(tunit.clone(), sp(loc, TE::Unit { trailing: false }));
let if_else_ = TE::IfElse(Box::new(econd), Box::new(eunit), Box::new(eabort));
let if_else = T::exp(tunit, sp(loc, if_else_));
exp_loop(stack, result, cur_expected_type_opt, Box::new(if_else));
}
te_ => {
let result = &mut *result.borrow_mut();
let e_res = exp_impl(stack.context, result, ty, loc, te_);
let e_res = maybe_freeze(stack.context, result, cur_expected_type_opt, e_res);
stack.operands.push(e_res)
}
}
}
let mut stack = Stack {
frames: vec![],
operands: vec![],
context,
};
let rc_result = Rc::new(RefCell::new(std::mem::take(result)));
exp_loop(
&mut stack,
rc_result.clone(),
initial_expected_type_opt.cloned(),
Box::new(initial_e),
);
while let Some(f) = stack.frames.pop() {
f(&mut stack)
}
let e_res = stack.operands.pop().unwrap();
assert!(stack.frames.is_empty());
assert!(stack.operands.is_empty());
*result = Rc::try_unwrap(rc_result).unwrap().into_inner();
e_res
}
enum TmpItem {
Single(Box<H::SingleType>),
Splat(Loc, Vec<H::SingleType>),
}
fn exp_impl(
context: &mut Context,
result: &mut Block,
ty: H::Type,
eloc: Loc,
e_: T::UnannotatedExp_,
) -> H::Exp {
use H::{Command_ as C, Statement_ as S, UnannotatedExp_ as HE};
use T::UnannotatedExp_ as TE;
let res = match e_ {
// Statement-like expressions
TE::While(tb, loop_body) => {
let mut cond_block = Block::new();
let cond_exp = exp(context, &mut cond_block, None, *tb);
let mut loop_block = Block::new();
let el = exp_(context, &mut loop_block, None, *loop_body);
ignore_and_pop(&mut loop_block, el);
let s_ = S::While {
cond: (cond_block, cond_exp),
block: loop_block,
};
result.push_back(sp(eloc, s_));
HE::Unit {
case: H::UnitCase::Implicit,
}
}
TE::Loop {
has_break,
body: loop_body,
} => {
let loop_block = statement_loop_body(context, *loop_body);
let s_ = S::Loop {
block: loop_block,
has_break,
};
result.push_back(sp(eloc, s_));
if !has_break {
HE::Unreachable
} else {
HE::Unit {
case: H::UnitCase::Implicit,
}
}
}
TE::Block(seq) => return block(context, result, eloc, None, seq),
// Command-like expressions
TE::Return(te) => {
let expected_type = context.signature.as_ref().map(|s| s.return_type.clone());
let e = exp_(context, result, expected_type.as_ref(), *te);
let c = sp(
eloc,
C::Return {
from_user: true,
exp: e,
},
);
result.push_back(sp(eloc, S::Command(c)));
HE::Unreachable
}
TE::Abort(te) => {
let e = exp_(context, result, None, *te);
let c = sp(eloc, C::Abort(e));
result.push_back(sp(eloc, S::Command(c)));
HE::Unreachable
}
TE::Break => {
let c = sp(eloc, C::Break);
result.push_back(sp(eloc, S::Command(c)));
HE::Unreachable
}
TE::Continue => {
let c = sp(eloc, C::Continue);
result.push_back(sp(eloc, S::Command(c)));
HE::Unreachable
}
TE::Assign(assigns, lvalue_ty, te) => {
let expected_type = expected_types(context, eloc, lvalue_ty);
let e = exp_(context, result, Some(&expected_type), *te);
assign_command(context, result, eloc, assigns, e);
HE::Unit {
case: H::UnitCase::Implicit,
}
}
TE::Mutate(tl, tr) => {
let er = exp(context, result, None, *tr);
let el = exp(context, result, None, *tl);
let c = sp(eloc, C::Mutate(el, er));
result.push_back(sp(eloc, S::Command(c)));
HE::Unit {
case: H::UnitCase::Implicit,
}
}
// All other expressiosn
TE::Unit { trailing } => HE::Unit {
case: if trailing {
H::UnitCase::Trailing
} else {
H::UnitCase::FromUser
},
},
TE::Value(ev) => HE::Value(value(context, ev)),
TE::Constant(_m, c) => {
// Currently only private constants exist
HE::Constant(c)
}
TE::Move { from_user, var } => {
let annotation = if from_user {
MoveOpAnnotation::FromUser
} else {
MoveOpAnnotation::InferredNoCopy
};
HE::Move {
annotation,
var: context.remapped_local(var),
}
}
TE::Copy { from_user, var } => HE::Copy {
from_user,
var: context.remapped_local(var),
},
TE::BorrowLocal(mut_, v) => HE::BorrowLocal(mut_, context.remapped_local(v)),
TE::Use(_) => panic!("ICE unexpanded use"),
TE::ModuleCall(call) => {
let T::ModuleCall {
module,
name,
type_arguments,
arguments,
parameter_types,
acquires,
} = *call;
let expected_type = H::Type_::from_vec(eloc, single_types(context, parameter_types));
let htys = base_types(context, type_arguments);
let harg = exp(context, result, Some(&expected_type), *arguments);
let call = H::ModuleCall {
module,
name,
type_arguments: htys,
arguments: harg,
acquires,
};
HE::ModuleCall(Box::new(call))
}
TE::Builtin(bf, targ) => builtin(context, result, eloc, *bf, targ),
TE::Vector(vec_loc, n, tty, targ) => {
let ty = Box::new(base_type(context, *tty));
let arg = exp(context, result, None, *targ);
HE::Vector(vec_loc, n, ty, arg)
}
TE::Dereference(te) => {
let e = exp(context, result, None, *te);
HE::Dereference(e)
}
TE::UnaryExp(op, te) => {
let e = exp(context, result, None, *te);
HE::UnaryExp(op, e)
}
TE::Pack(_, s, tbs, tfields) => {
let bs = base_types(context, tbs);
let decl_fields = context.fields(&s);
let mut count = 0;
let mut decl_field = |f: &Field| -> usize {
match decl_fields {
Some(m) => *m.get(f).unwrap(),
None => {
// none can occur with errors in typing
let i = count;
count += 1;
i
}
}
};
let mut texp_fields: Vec<(usize, Field, usize, N::Type, T::Exp)> = tfields
.into_iter()
.map(|(f, (exp_idx, (bt, tf)))| (decl_field(&f), f, exp_idx, bt, tf))
.collect();
texp_fields.sort_by(|(_, _, eidx1, _, _), (_, _, eidx2, _, _)| eidx1.cmp(eidx2));
let bind_all_fields = texp_fields
.iter()
.any(|(decl_idx, _, exp_idx, _, _)| decl_idx != exp_idx);
let fields = if !bind_all_fields {
let mut fs = vec![];
let tes = texp_fields
.into_iter()
.map(|(_, f, _, bt, te)| {
let bt = base_type(context, bt);
fs.push((f, bt.clone()));
let t = H::Type_::base(bt);
(te, Some(t))
})
.collect();
let es = exp_evaluation_order(context, result, tes);
assert!(
fs.len() == es.len(),
"ICE exp_evaluation_order changed arity"
);
es.into_iter()
.zip(fs)
.map(|(e, (f, bt))| (f, bt, e))
.collect()
} else {
let num_fields = decl_fields.as_ref().map(|m| m.len()).unwrap_or(0);
let mut fields = (0..num_fields).map(|_| None).collect::<Vec<_>>();
for (decl_idx, f, _exp_idx, bt, tf) in texp_fields {
// Might have too many arguments, there will be an error from typing
if decl_idx > fields.len() {
debug_assert!(context.env.has_diags());
break;
}
let bt = base_type(context, bt);
let t = H::Type_::base(bt.clone());
let ef = exp_(context, result, Some(&t), tf);
assert!(fields.get(decl_idx).unwrap().is_none());
let move_tmp = bind_exp(context, result, ef);
fields[decl_idx] = Some((f, bt, move_tmp))
}
// Might have too few arguments, there will be an error from typing if so
fields
.into_iter()
.filter_map(|o| {
// if o is None, context should have errors
debug_assert!(o.is_some() || context.env.has_diags());
o
})
.collect()
};
HE::Pack(s, bs, fields)
}
TE::ExpList(titems) => {
assert!(!titems.is_empty());
let mut tmp_items = vec![];
let mut tes = vec![];
for titem in titems {
match titem {
T::ExpListItem::Single(te, ts) => {
let s = single_type(context, *ts);
tmp_items.push(TmpItem::Single(Box::new(s)));
tes.push((te, None));
}
T::ExpListItem::Splat(sloc, te, tss) => {
let ss = single_types(context, tss);
tmp_items.push(TmpItem::Splat(sloc, ss));
tes.push((te, None));
}
}
}
let es = exp_evaluation_order(context, result, tes);
assert!(
es.len() == tmp_items.len(),
"ICE exp_evaluation_order changed arity"
);
let items = es
.into_iter()
.zip(tmp_items)
.map(|(e, tmp_item)| match tmp_item {
TmpItem::Single(s) => H::ExpListItem::Single(e, s),
TmpItem::Splat(loc, ss) => H::ExpListItem::Splat(loc, e, ss),
})
.collect();
HE::ExpList(items)
}
TE::Borrow(mut_, te, f) => {
let e = exp(context, result, None, *te);
HE::Borrow(mut_, e, f)
}
TE::TempBorrow(mut_, te) => {
let eb = exp_(context, result, None, *te);
let tmp = match bind_exp_impl(context, result, eb, true).exp.value {
HE::Move {
annotation: MoveOpAnnotation::InferredLastUsage,
var,
} => var,
_ => panic!("ICE invalid bind_exp for single value"),
};
HE::BorrowLocal(mut_, tmp)
}
TE::Cast(te, rhs_ty) => {
use N::BuiltinTypeName_ as BT;
let e = exp(context, result, None, *te);
let bt = match rhs_ty.value.builtin_name() {
Some(bt @ sp!(_, BT::U8))
| Some(bt @ sp!(_, BT::U64))
| Some(bt @ sp!(_, BT::U128)) => bt.clone(),
_ => panic!("ICE typing failed for cast"),
};
HE::Cast(e, bt)
}
TE::Annotate(te, rhs_ty) => {
let expected_ty = type_(context, *rhs_ty);
return exp_(context, result, Some(&expected_ty), *te);
}
TE::Spec(u, tused_locals) => {
let used_locals = tused_locals
.into_iter()
.map(|(var, ty)| {
let v = context.remapped_local(var);
let st = single_type(context, ty);
(v, st)
})
.collect();
HE::Spec(u, used_locals)
}
TE::UnresolvedError => {
assert!(context.env.has_diags());
HE::UnresolvedError
}
TE::IfElse(..) | TE::BinopExp(..) => unreachable!(),
};
H::exp(ty, sp(eloc, res))
}
fn exp_evaluation_order(
context: &mut Context,
result: &mut Block,
tes: Vec<(T::Exp, Option<H::Type>)>,
) -> Vec<H::Exp> {
let mut needs_binding = false;
let mut e_results = vec![];
for (te, expected_type) in tes.into_iter().rev() {
let mut tmp_result = Block::new();
let e = *exp(context, &mut tmp_result, expected_type.as_ref(), te);
// If evaluating this expression introduces statements, all previous exps need to be bound
// to preserve left-to-right evaluation order
let adds_to_result = !tmp_result.is_empty();
let e = if needs_binding {
bind_exp(context, &mut tmp_result, e)
} else {
e
};
e_results.push((tmp_result, e));
needs_binding = needs_binding || adds_to_result;
}
let mut es = vec![];
for (mut tmp_result, e) in e_results.into_iter().rev() {
result.append(&mut tmp_result);
es.push(e)
}
es
}
fn make_temps(context: &mut Context, loc: Loc, ty: H::Type) -> Vec<(Var, H::SingleType)> {
use H::Type_ as T;
match ty.value {
T::Unit => vec![],
T::Single(s) => vec![(context.new_temp(loc, s.clone()), s)],
T::Multiple(ss) => ss
.into_iter()
.map(|s| (context.new_temp(loc, s.clone()), s))
.collect(),
}
}
fn bind_exp(context: &mut Context, result: &mut Block, e: H::Exp) -> H::Exp {
bind_exp_impl(context, result, e, false)
}
fn bind_exp_(
result: &mut Block,
loc: Loc,
tmps: Vec<(Var, H::SingleType)>,
e: H::Exp,
) -> H::UnannotatedExp_ {
bind_exp_impl_(result, loc, tmps, e, false)
}
fn bind_exp_impl(
context: &mut Context,
result: &mut Block,
e: H::Exp,
bind_unreachable: bool,
) -> H::Exp {
if matches!(&e.exp.value, H::UnannotatedExp_::Unreachable) && !bind_unreachable {
return e;
}
let loc = e.exp.loc;
let ty = e.ty.clone();
let tmps = make_temps(context, loc, ty.clone());
H::exp(
ty,
sp(loc, bind_exp_impl_(result, loc, tmps, e, bind_unreachable)),
)
}
fn bind_exp_impl_(
result: &mut Block,
loc: Loc,
tmps: Vec<(Var, H::SingleType)>,
e: H::Exp,
bind_unreachable: bool,
) -> H::UnannotatedExp_ {
use H::{Command_ as C, Statement_ as S, UnannotatedExp_ as E};
if matches!(&e.exp.value, H::UnannotatedExp_::Unreachable) && !bind_unreachable {
return H::UnannotatedExp_::Unreachable;
}
if tmps.is_empty() {
let cmd = sp(loc, C::IgnoreAndPop { pop_num: 0, exp: e });
result.push_back(sp(loc, S::Command(cmd)));
return E::Unit {
case: H::UnitCase::Implicit,
};
}
let lvalues = tmps
.iter()
.map(|(v, st)| sp(v.loc(), H::LValue_::Var(*v, Box::new(st.clone()))))
.collect();
let asgn = sp(loc, C::Assign(lvalues, Box::new(e)));
result.push_back(sp(loc, S::Command(asgn)));
let mut etemps = tmps
.into_iter()
.map(|(var, st)| {
let evar_ = sp(var.loc(), use_tmp(var));
let ty = sp(st.loc, H::Type_::Single(st.clone()));
let evar = H::exp(ty, evar_);
H::ExpListItem::Single(evar, Box::new(st))
})
.collect::<Vec<_>>();
match etemps.len() {
0 => unreachable!(),
1 => match etemps.pop().unwrap() {
H::ExpListItem::Single(e, _) => e.exp.value,
H::ExpListItem::Splat(_, _, _) => unreachable!(),
},
_ => E::ExpList(etemps),
}
}
fn use_tmp(var: Var) -> H::UnannotatedExp_ {
use H::UnannotatedExp_ as E;
E::Move {
annotation: MoveOpAnnotation::InferredLastUsage,
var,
}
}
fn builtin(
context: &mut Context,
result: &mut Block,
_eloc: Loc,
sp!(loc, tb_): T::BuiltinFunction,
targ: Box<T::Exp>,
) -> H::UnannotatedExp_ {
use H::{BuiltinFunction_ as HB, UnannotatedExp_ as E};
use T::BuiltinFunction_ as TB;
match tb_ {
TB::MoveTo(bt) => {
let texpected_tys = vec![
sp(loc, N::Type_::Ref(false, Box::new(N::Type_::signer(loc)))),
bt.clone(),
];
let texpected_ty_ = N::Type_::Apply(
Some(AbilitySet::empty()), // Should be unused
sp(loc, N::TypeName_::Multiple(texpected_tys.len())),
texpected_tys,
);
let expected_ty = type_(context, sp(loc, texpected_ty_));
let arg = exp(context, result, Some(&expected_ty), *targ);
let ty = base_type(context, bt);
E::Builtin(Box::new(sp(loc, HB::MoveTo(ty))), arg)
}
TB::MoveFrom(bt) => {
let ty = base_type(context, bt);
let arg = exp(context, result, None, *targ);
E::Builtin(Box::new(sp(loc, HB::MoveFrom(ty))), arg)
}
TB::BorrowGlobal(mut_, bt) => {
let ty = base_type(context, bt);
let arg = exp(context, result, None, *targ);
E::Builtin(Box::new(sp(loc, HB::BorrowGlobal(mut_, ty))), arg)
}
TB::Exists(bt) => {
let ty = base_type(context, bt);
let arg = exp(context, result, None, *targ);
E::Builtin(Box::new(sp(loc, HB::Exists(ty))), arg)
}
TB::Freeze(_bt) => {
let arg = exp(context, result, None, *targ);
E::Freeze(arg)
}
TB::Assert(_) => unreachable!(),
}
}
fn value(_context: &mut Context, sp!(loc, ev_): E::Value) -> H::Value {
use E::Value_ as EV;
use H::Value_ as HV;
let v_ = match ev_ {
EV::InferredNum(_) => panic!("ICE should have been expanded"),
EV::Address(a) => HV::Address(a.into_addr_bytes()),
EV::U8(u) => HV::U8(u),
EV::U64(u) => HV::U64(u),
EV::U128(u) => HV::U128(u),
EV::Bool(u) => HV::Bool(u),
EV::Bytearray(bytes) => HV::Vector(
Box::new(H::BaseType_::u8(loc)),
bytes.into_iter().map(|b| sp(loc, HV::U8(b))).collect(),
),
};
sp(loc, v_)
}
//**************************************************************************************************
// Freezing
//**************************************************************************************************
#[derive(PartialEq, Eq)]
enum Freeze {
NotNeeded,
Point,
Sub(Vec<bool>),
}
fn needs_freeze(context: &Context, sp!(_, actual): &H::Type, sp!(_, expected): &H::Type) -> Freeze {
use H::Type_ as T;
match (actual, expected) {
(T::Unit, T::Unit) => Freeze::NotNeeded,
(T::Single(actaul_s), T::Single(actual_e)) => {
let needs = needs_freeze_single(actaul_s, actual_e);
if needs {
Freeze::Point
} else {
Freeze::NotNeeded
}
}
(T::Multiple(actaul_ss), T::Multiple(actual_es)) => {
assert!(actaul_ss.len() == actual_es.len());
let points = actaul_ss
.iter()
.zip(actual_es)
.map(|(a, e)| needs_freeze_single(a, e))
.collect::<Vec<_>>();
if points.iter().any(|needs| *needs) {
Freeze::Sub(points)
} else {
Freeze::NotNeeded
}
}
(_actual, _expected) => {
assert!(context.env.has_diags());
Freeze::NotNeeded
}
}
}
fn needs_freeze_single(sp!(_, actual): &H::SingleType, sp!(_, expected): &H::SingleType) -> bool {
use H::SingleType_ as T;
matches!((actual, expected), (T::Ref(true, _), T::Ref(false, _)))
}
fn freeze(context: &mut Context, result: &mut Block, expected_type: &H::Type, e: H::Exp) -> H::Exp {
use H::{Type_ as T, UnannotatedExp_ as E};
match needs_freeze(context, &e.ty, expected_type) {
Freeze::NotNeeded => e,
Freeze::Point => freeze_point(e),
Freeze::Sub(points) => {
let loc = e.exp.loc;
let actual_tys = match &e.ty.value {
T::Multiple(v) => v.clone(),
_ => unreachable!("ICE needs_freeze failed"),
};
assert!(actual_tys.len() == points.len());
let new_temps = actual_tys
.into_iter()
.map(|ty| (context.new_temp(loc, ty.clone()), ty))
.collect::<Vec<_>>();
let lvalues = new_temps
.iter()
.cloned()
.map(|(v, ty)| sp(loc, H::LValue_::Var(v, Box::new(ty))))
.collect::<Vec<_>>();
let assign = sp(loc, H::Command_::Assign(lvalues, Box::new(e)));
result.push_back(sp(loc, H::Statement_::Command(assign)));
let exps = new_temps
.into_iter()
.zip(points)
.map(|((var, ty), needs_freeze)| {
let e_ = sp(loc, use_tmp(var));
let e = H::exp(T::single(ty), e_);
if needs_freeze {
freeze_point(e)
} else {
e
}
})
.collect::<Vec<_>>();
let ss = exps
.iter()
.map(|e| match &e.ty.value {
T::Single(s) => s.clone(),
_ => panic!("ICE list item has Multple type"),
})
.collect::<Vec<_>>();
let tys = sp(loc, T::Multiple(ss.clone()));
let items = exps
.into_iter()
.zip(ss)
.map(|(e, s)| H::ExpListItem::Single(e, Box::new(s)))
.collect();
H::exp(tys, sp(loc, E::ExpList(items)))
}
}
}
fn freeze_point(e: H::Exp) -> H::Exp {
let frozen_ty = freeze_ty(e.ty.clone());
let eloc = e.exp.loc;
let e_ = H::UnannotatedExp_::Freeze(Box::new(e));
H::exp(frozen_ty, sp(eloc, e_))
}
fn freeze_ty(sp!(tloc, t): H::Type) -> H::Type {
use H::Type_ as T;
match t {
T::Single(s) => sp(tloc, T::Single(freeze_single(s))),
t => sp(tloc, t),
}
}
fn freeze_single(sp!(sloc, s): H::SingleType) -> H::SingleType {
use H::SingleType_ as S;
match s {
S::Ref(true, inner) => sp(sloc, S::Ref(false, inner)),
s => sp(sloc, s),
}
}
fn bind_for_short_circuit(e: &T::Exp) -> bool {
use T::UnannotatedExp_ as TE;
match &e.exp.value {
TE::Use(_) => panic!("ICE should have been expanded"),
TE::Value(_)
| TE::Constant(_, _)
| TE::Move { .. }
| TE::Copy { .. }
| TE::UnresolvedError => false,
// TODO might want to case ModuleCall for fake natives
TE::ModuleCall(_) => true,
TE::Block(seq) => bind_for_short_circuit_sequence(seq),
TE::Annotate(el, _) => bind_for_short_circuit(el),
TE::Break
| TE::Continue
| TE::IfElse(_, _, _)
| TE::While(_, _)
| TE::Loop { .. }
| TE::Return(_)
| TE::Abort(_)
| TE::Builtin(_, _)
| TE::Dereference(_)
| TE::UnaryExp(_, _)
| TE::Borrow(_, _, _)
| TE::TempBorrow(_, _)
| TE::BinopExp(_, _, _, _) => true,
TE::Unit { .. }
| TE::Spec(_, _)
| TE::Assign(_, _, _)
| TE::Mutate(_, _)
| TE::Pack(_, _, _, _)
| TE::Vector(_, _, _, _)
| TE::BorrowLocal(_, _)
| TE::ExpList(_)
| TE::Cast(_, _) => panic!("ICE unexpected exp in short circuit check: {:?}", e),
}
}
fn bind_for_short_circuit_sequence(seq: &T::Sequence) -> bool {
use T::SequenceItem_ as TItem;
seq.len() != 1
|| match &seq[0].value {
TItem::Seq(e) => bind_for_short_circuit(e),
item @ TItem::Declare(_) | item @ TItem::Bind(_, _, _) => {
panic!("ICE unexpected item in short circuit check: {:?}", item)
}
}
}
//**************************************************************************************************
// Trailing semicolon
//**************************************************************************************************
fn check_trailing_unit(context: &mut Context, block: &mut Block) {
use H::{Command_ as C, Statement_ as S, UnannotatedExp_ as E};
macro_rules! hcmd {
($loc:pat, $cmd:pat) => {
sp!(_, S::Command(sp!($loc, $cmd)))
};
}
macro_rules! hignored {
($loc:pat, $e:pat) => {
hcmd!(
_,
C::IgnoreAndPop {
exp: H::Exp {
exp: sp!($loc, $e),
..
},
..
}
)
};
}
macro_rules! trailing {
($uloc: pat) => {
hcmd!(
_,
C::IgnoreAndPop {
exp: H::Exp {
exp: sp!(
$uloc,
E::Unit {
case: H::UnitCase::Trailing
}
),
..
},
..
}
)
};
}
macro_rules! trailing_returned {
($uloc:pat) => {
hcmd!(
_,
C::Return {
exp: H::Exp {
exp: sp!(
$uloc,
E::Unit {
case: H::UnitCase::Trailing
}
),
..
},
..
}
)
};
}
fn divergent_block(block: &Block) -> bool {
matches!(
block.back(),
Some(hcmd!(_, C::Break))
| Some(hcmd!(_, C::Continue))
| Some(hcmd!(_, C::Abort(_)))
| Some(hcmd!(_, C::Return { .. }))
| Some(hignored!(_, E::Unreachable))
)
}
macro_rules! invalid_trailing_unit {
($context:ident, $loc:expr, $uloc:expr) => {{
let semi_msg = "Invalid trailing ';'";
let unreachable_msg = "Any code after this expression will not be reached";
let info_msg = "A trailing ';' in an expression block implicitly adds a '()' value \
after the semicolon. That '()' value will not be reachable";
$context.env.add_diag(diag!(
UnusedItem::TrailingSemi,
($uloc, semi_msg),
($loc, unreachable_msg),
($uloc, info_msg),
));
block.pop_back();
}};
}
block
.iter_mut()
.for_each(|s| check_trailing_unit_statement(context, s));
let len = block.len();
if len < 2 {
return;
}
match (&block[len - 2], &block[len - 1]) {
(
sp!(
loc,
S::IfElse {
if_block,
else_block,
..
}
),
trailing!(uloc),
)
| (
sp!(
loc,
S::IfElse {
if_block,
else_block,
..
}
),
trailing_returned!(uloc),
) if divergent_block(if_block) && divergent_block(else_block) => {
invalid_trailing_unit!(context, *loc, *uloc)
}
(sp!(loc, S::Loop { has_break, .. }), trailing!(uloc))
| (sp!(loc, S::Loop { has_break, .. }), trailing_returned!(uloc))
if !has_break =>
{
invalid_trailing_unit!(context, *loc, *uloc)
}
(hcmd!(loc, C::Break), trailing!(uloc))
| (hcmd!(loc, C::Break), trailing_returned!(uloc))
| (hcmd!(loc, C::Continue), trailing!(uloc))
| (hcmd!(loc, C::Continue), trailing_returned!(uloc))
| (hcmd!(loc, C::Abort(_)), trailing!(uloc))
| (hcmd!(loc, C::Abort(_)), trailing_returned!(uloc))
| (hcmd!(loc, C::Return { .. }), trailing!(uloc))
| (hcmd!(loc, C::Return { .. }), trailing_returned!(uloc))
| (hignored!(loc, E::Unreachable), trailing!(uloc))
| (hignored!(loc, E::Unreachable), trailing_returned!(uloc)) => {
invalid_trailing_unit!(context, *loc, *uloc)
}
_ => (),
};
}
fn check_trailing_unit_statement(context: &mut Context, sp!(_, s_): &mut H::Statement) {
use H::Statement_ as S;
match s_ {
S::Command(_) => (),
S::IfElse {
if_block,
else_block,
..
} => {
check_trailing_unit(context, if_block);
check_trailing_unit(context, else_block)
}
S::While {
cond: (cond_block, _),
block,
} => {
check_trailing_unit(context, cond_block);
check_trailing_unit(context, block)
}
S::Loop { block, .. } => check_trailing_unit(context, block),
}
}
//**************************************************************************************************
// Unused locals
//**************************************************************************************************
fn check_unused_locals(
context: &mut Context,
locals: &mut UniqueMap<Var, H::SingleType>,
used: BTreeSet<Var>,
) -> BTreeSet<Var> {
let signature = context
.signature
.as_ref()
.expect("ICE Signature should always be defined when checking a function body");
let mut unused = BTreeSet::new();
// report unused locals
for (v, _) in locals
.key_cloned_iter()
.filter(|(v, _)| !used.contains(v) && !v.starts_with_underscore())
{
let vstr = match display_var(v.value()) {
DisplayVar::Tmp => panic!("ICE unused tmp"),
DisplayVar::Orig(vstr) => vstr,
};
let loc = v.loc();
let msg = if signature.is_parameter(&v) {
format!(
"Unused parameter '{0}'. Consider removing or prefixing with an underscore: '_{0}'",
vstr
)
} else {
// unused local variable; mark for removal
unused.insert(v);
format!(
"Unused local variable '{0}'. Consider removing or prefixing with an underscore: \
'_{0}'",
vstr
)
};
context
.env
.add_diag(diag!(UnusedItem::Variable, (loc, msg)));
}
for v in &unused {
locals.remove(v);
}
unused
}
fn remove_unused_bindings(unused: &BTreeSet<Var>, block: &mut Block) {
block
.iter_mut()
.for_each(|s| remove_unused_bindings_statement(unused, s))
}
fn remove_unused_bindings_statement(unused: &BTreeSet<Var>, sp!(_, s_): &mut H::Statement) {
use H::Statement_ as S;
match s_ {
S::Command(c) => remove_unused_bindings_command(unused, c),
S::IfElse {
if_block,
else_block,
..
} => {
remove_unused_bindings(unused, if_block);
remove_unused_bindings(unused, else_block)
}
S::While {
cond: (cond_block, _),
block,
} => {
remove_unused_bindings(unused, cond_block);
remove_unused_bindings(unused, block)
}
S::Loop { block, .. } => remove_unused_bindings(unused, block),
}
}
fn remove_unused_bindings_command(unused: &BTreeSet<Var>, sp!(_, c_): &mut H::Command) {
use H::Command_ as HC;
if let HC::Assign(ls, _) = c_ {
remove_unused_bindings_lvalues(unused, ls)
}
}
fn remove_unused_bindings_lvalues(unused: &BTreeSet<Var>, ls: &mut [H::LValue]) {
ls.iter_mut()
.for_each(|l| remove_unused_bindings_lvalue(unused, l))
}
fn remove_unused_bindings_lvalue(unused: &BTreeSet<Var>, sp!(_, l_): &mut H::LValue) {
use H::LValue_ as HL;
match l_ {
HL::Var(v, _) if unused.contains(v) => *l_ = HL::Ignore,
HL::Var(_, _) | HL::Ignore => (),
HL::Unpack(_, _, fields) => fields
.iter_mut()
.for_each(|(_, l)| remove_unused_bindings_lvalue(unused, l)),
}
}
| 34.091276 | 100 | 0.470186 |
29947687ee4ee037dd7fec81e1c67c38a2bb7cce | 1,580 | use bb::BB;
use castle::Castle;
use square::Square;
mod mv_counter;
mod mv_vec;
mod piece_square_table;
mod sorted_move_adder;
pub use self::mv_counter::MoveCounter;
pub use self::mv_vec::MoveVec;
pub use self::piece_square_table::PieceSquareTable;
pub use self::sorted_move_adder::{SortedMoveAdder, SortedMoveHeap, SortedMoveHeapItem};
/// MoveAdder represents a way to collect moves from move generation functions
/// Implementations:
/// MoveCounter (count moves only)
/// MoveVec (adds move to Vec)
/// SortedMoveAdder (adds moves along with piece-square-scores to a sorted binary heap)
pub trait MoveAdder {
fn add_captures(&mut self, from: Square, targets: BB);
fn add_non_captures(&mut self, from: Square, targets: BB);
/// Adds the castle to the move list
fn add_castle(&mut self, castle: Castle);
/// Adds pawn non-captures to the list. Targets is a bitboard of valid to-squares. Shift is the distance the pawn moved to get to the target square, mod 64. For example, for a white piece moving forward one row this is '8'. For a black piece moving forward one row this is 56 (-8 % 64).
fn add_pawn_pushes(&mut self, shift: usize, targets: BB);
/// Adds pawn captures to list. Targets and shift are same as for `add_pawn_pushes`. Do not use this for en-passant captures (use `add_pawn_ep_capture`)
fn add_pawn_captures(&mut self, shift: usize, targets: BB);
/// Adds pawn en-passant capture to list. From and to are the squares the moving pieces moves from and to, respectively
fn add_pawn_ep_capture(&mut self, from: Square, to: Square);
}
| 43.888889 | 288 | 0.747468 |
18424da4418db82344271e5d43de868a467a75db | 589,266 | // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
use std::fmt::Write;
/// See [`AcceptSharedDirectoryInput`](crate::input::AcceptSharedDirectoryInput)
pub mod accept_shared_directory_input {
/// A builder for [`AcceptSharedDirectoryInput`](crate::input::AcceptSharedDirectoryInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) shared_directory_id: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>Identifier of the shared directory in the directory consumer account. This identifier is different for each directory owner account. </p>
pub fn shared_directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.shared_directory_id = Some(input.into());
self
}
/// <p>Identifier of the shared directory in the directory consumer account. This identifier is different for each directory owner account. </p>
pub fn set_shared_directory_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.shared_directory_id = input;
self
}
/// Consumes the builder and constructs a [`AcceptSharedDirectoryInput`](crate::input::AcceptSharedDirectoryInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::AcceptSharedDirectoryInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::AcceptSharedDirectoryInput {
shared_directory_id: self.shared_directory_id,
})
}
}
}
#[doc(hidden)]
pub type AcceptSharedDirectoryInputOperationOutputAlias = crate::operation::AcceptSharedDirectory;
#[doc(hidden)]
pub type AcceptSharedDirectoryInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl AcceptSharedDirectoryInput {
/// Consumes the builder and constructs an Operation<[`AcceptSharedDirectory`](crate::operation::AcceptSharedDirectory)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::AcceptSharedDirectory,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::AcceptSharedDirectoryInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::AcceptSharedDirectoryInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.AcceptSharedDirectory",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_accept_shared_directory(
&self,
)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::AcceptSharedDirectory::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"AcceptSharedDirectory",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`AcceptSharedDirectoryInput`](crate::input::AcceptSharedDirectoryInput)
pub fn builder() -> crate::input::accept_shared_directory_input::Builder {
crate::input::accept_shared_directory_input::Builder::default()
}
}
/// See [`AddIpRoutesInput`](crate::input::AddIpRoutesInput)
pub mod add_ip_routes_input {
/// A builder for [`AddIpRoutesInput`](crate::input::AddIpRoutesInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) ip_routes: std::option::Option<std::vec::Vec<crate::model::IpRoute>>,
pub(crate) update_security_group_for_directory_controllers: std::option::Option<bool>,
}
impl Builder {
/// <p>Identifier (ID) of the directory to which to add the address block.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>Identifier (ID) of the directory to which to add the address block.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// Appends an item to `ip_routes`.
///
/// To override the contents of this collection use [`set_ip_routes`](Self::set_ip_routes).
///
/// <p>IP address blocks, using CIDR format, of the traffic to route. This is often the IP address block of the DNS server used for your self-managed domain.</p>
pub fn ip_routes(mut self, input: crate::model::IpRoute) -> Self {
let mut v = self.ip_routes.unwrap_or_default();
v.push(input);
self.ip_routes = Some(v);
self
}
/// <p>IP address blocks, using CIDR format, of the traffic to route. This is often the IP address block of the DNS server used for your self-managed domain.</p>
pub fn set_ip_routes(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::IpRoute>>,
) -> Self {
self.ip_routes = input;
self
}
/// <p>If set to true, updates the inbound and outbound rules of the security group that has the description: "Amazon Web Services created security group for <i>directory ID</i> directory controllers." Following are the new rules: </p>
/// <p>Inbound:</p>
/// <ul>
/// <li> <p>Type: Custom UDP Rule, Protocol: UDP, Range: 88, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom UDP Rule, Protocol: UDP, Range: 123, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom UDP Rule, Protocol: UDP, Range: 138, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom UDP Rule, Protocol: UDP, Range: 389, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom UDP Rule, Protocol: UDP, Range: 464, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom UDP Rule, Protocol: UDP, Range: 445, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 88, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 135, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 445, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 464, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 636, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 1024-65535, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 3268-33269, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: DNS (UDP), Protocol: UDP, Range: 53, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: DNS (TCP), Protocol: TCP, Range: 53, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: LDAP, Protocol: TCP, Range: 389, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: All ICMP, Protocol: All, Range: N/A, Source: 0.0.0.0/0</p> </li>
/// </ul>
/// <p></p>
/// <p>Outbound:</p>
/// <ul>
/// <li> <p>Type: All traffic, Protocol: All, Range: All, Destination: 0.0.0.0/0</p> </li>
/// </ul>
/// <p>These security rules impact an internal network interface that is not exposed publicly.</p>
pub fn update_security_group_for_directory_controllers(mut self, input: bool) -> Self {
self.update_security_group_for_directory_controllers = Some(input);
self
}
/// <p>If set to true, updates the inbound and outbound rules of the security group that has the description: "Amazon Web Services created security group for <i>directory ID</i> directory controllers." Following are the new rules: </p>
/// <p>Inbound:</p>
/// <ul>
/// <li> <p>Type: Custom UDP Rule, Protocol: UDP, Range: 88, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom UDP Rule, Protocol: UDP, Range: 123, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom UDP Rule, Protocol: UDP, Range: 138, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom UDP Rule, Protocol: UDP, Range: 389, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom UDP Rule, Protocol: UDP, Range: 464, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom UDP Rule, Protocol: UDP, Range: 445, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 88, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 135, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 445, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 464, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 636, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 1024-65535, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 3268-33269, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: DNS (UDP), Protocol: UDP, Range: 53, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: DNS (TCP), Protocol: TCP, Range: 53, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: LDAP, Protocol: TCP, Range: 389, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: All ICMP, Protocol: All, Range: N/A, Source: 0.0.0.0/0</p> </li>
/// </ul>
/// <p></p>
/// <p>Outbound:</p>
/// <ul>
/// <li> <p>Type: All traffic, Protocol: All, Range: All, Destination: 0.0.0.0/0</p> </li>
/// </ul>
/// <p>These security rules impact an internal network interface that is not exposed publicly.</p>
pub fn set_update_security_group_for_directory_controllers(
mut self,
input: std::option::Option<bool>,
) -> Self {
self.update_security_group_for_directory_controllers = input;
self
}
/// Consumes the builder and constructs a [`AddIpRoutesInput`](crate::input::AddIpRoutesInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::AddIpRoutesInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::AddIpRoutesInput {
directory_id: self.directory_id,
ip_routes: self.ip_routes,
update_security_group_for_directory_controllers: self
.update_security_group_for_directory_controllers
.unwrap_or_default(),
})
}
}
}
#[doc(hidden)]
pub type AddIpRoutesInputOperationOutputAlias = crate::operation::AddIpRoutes;
#[doc(hidden)]
pub type AddIpRoutesInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl AddIpRoutesInput {
/// Consumes the builder and constructs an Operation<[`AddIpRoutes`](crate::operation::AddIpRoutes)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::AddIpRoutes,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::AddIpRoutesInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::AddIpRoutesInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.AddIpRoutes",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_add_ip_routes(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::AddIpRoutes::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"AddIpRoutes",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`AddIpRoutesInput`](crate::input::AddIpRoutesInput)
pub fn builder() -> crate::input::add_ip_routes_input::Builder {
crate::input::add_ip_routes_input::Builder::default()
}
}
/// See [`AddRegionInput`](crate::input::AddRegionInput)
pub mod add_region_input {
/// A builder for [`AddRegionInput`](crate::input::AddRegionInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) region_name: std::option::Option<std::string::String>,
pub(crate) vpc_settings: std::option::Option<crate::model::DirectoryVpcSettings>,
}
impl Builder {
/// <p>The identifier of the directory to which you want to add Region replication.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory to which you want to add Region replication.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The name of the Region where you want to add domain controllers for replication. For example, <code>us-east-1</code>.</p>
pub fn region_name(mut self, input: impl Into<std::string::String>) -> Self {
self.region_name = Some(input.into());
self
}
/// <p>The name of the Region where you want to add domain controllers for replication. For example, <code>us-east-1</code>.</p>
pub fn set_region_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.region_name = input;
self
}
/// <p>Contains VPC information for the <code>CreateDirectory</code> or <code>CreateMicrosoftAD</code> operation.</p>
pub fn vpc_settings(mut self, input: crate::model::DirectoryVpcSettings) -> Self {
self.vpc_settings = Some(input);
self
}
/// <p>Contains VPC information for the <code>CreateDirectory</code> or <code>CreateMicrosoftAD</code> operation.</p>
pub fn set_vpc_settings(
mut self,
input: std::option::Option<crate::model::DirectoryVpcSettings>,
) -> Self {
self.vpc_settings = input;
self
}
/// Consumes the builder and constructs a [`AddRegionInput`](crate::input::AddRegionInput)
pub fn build(
self,
) -> std::result::Result<crate::input::AddRegionInput, aws_smithy_http::operation::BuildError>
{
Ok(crate::input::AddRegionInput {
directory_id: self.directory_id,
region_name: self.region_name,
vpc_settings: self.vpc_settings,
})
}
}
}
#[doc(hidden)]
pub type AddRegionInputOperationOutputAlias = crate::operation::AddRegion;
#[doc(hidden)]
pub type AddRegionInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl AddRegionInput {
/// Consumes the builder and constructs an Operation<[`AddRegion`](crate::operation::AddRegion)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::AddRegion,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::AddRegionInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::AddRegionInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.AddRegion",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_add_region(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op =
aws_smithy_http::operation::Operation::new(request, crate::operation::AddRegion::new())
.with_metadata(aws_smithy_http::operation::Metadata::new(
"AddRegion",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`AddRegionInput`](crate::input::AddRegionInput)
pub fn builder() -> crate::input::add_region_input::Builder {
crate::input::add_region_input::Builder::default()
}
}
/// See [`AddTagsToResourceInput`](crate::input::AddTagsToResourceInput)
pub mod add_tags_to_resource_input {
/// A builder for [`AddTagsToResourceInput`](crate::input::AddTagsToResourceInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) resource_id: std::option::Option<std::string::String>,
pub(crate) tags: std::option::Option<std::vec::Vec<crate::model::Tag>>,
}
impl Builder {
/// <p>Identifier (ID) for the directory to which to add the tag.</p>
pub fn resource_id(mut self, input: impl Into<std::string::String>) -> Self {
self.resource_id = Some(input.into());
self
}
/// <p>Identifier (ID) for the directory to which to add the tag.</p>
pub fn set_resource_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.resource_id = input;
self
}
/// Appends an item to `tags`.
///
/// To override the contents of this collection use [`set_tags`](Self::set_tags).
///
/// <p>The tags to be assigned to the directory.</p>
pub fn tags(mut self, input: crate::model::Tag) -> Self {
let mut v = self.tags.unwrap_or_default();
v.push(input);
self.tags = Some(v);
self
}
/// <p>The tags to be assigned to the directory.</p>
pub fn set_tags(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Tag>>,
) -> Self {
self.tags = input;
self
}
/// Consumes the builder and constructs a [`AddTagsToResourceInput`](crate::input::AddTagsToResourceInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::AddTagsToResourceInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::AddTagsToResourceInput {
resource_id: self.resource_id,
tags: self.tags,
})
}
}
}
#[doc(hidden)]
pub type AddTagsToResourceInputOperationOutputAlias = crate::operation::AddTagsToResource;
#[doc(hidden)]
pub type AddTagsToResourceInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl AddTagsToResourceInput {
/// Consumes the builder and constructs an Operation<[`AddTagsToResource`](crate::operation::AddTagsToResource)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::AddTagsToResource,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::AddTagsToResourceInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::AddTagsToResourceInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.AddTagsToResource",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_add_tags_to_resource(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::AddTagsToResource::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"AddTagsToResource",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`AddTagsToResourceInput`](crate::input::AddTagsToResourceInput)
pub fn builder() -> crate::input::add_tags_to_resource_input::Builder {
crate::input::add_tags_to_resource_input::Builder::default()
}
}
/// See [`CancelSchemaExtensionInput`](crate::input::CancelSchemaExtensionInput)
pub mod cancel_schema_extension_input {
/// A builder for [`CancelSchemaExtensionInput`](crate::input::CancelSchemaExtensionInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) schema_extension_id: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The identifier of the directory whose schema extension will be canceled.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory whose schema extension will be canceled.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The identifier of the schema extension that will be canceled.</p>
pub fn schema_extension_id(mut self, input: impl Into<std::string::String>) -> Self {
self.schema_extension_id = Some(input.into());
self
}
/// <p>The identifier of the schema extension that will be canceled.</p>
pub fn set_schema_extension_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.schema_extension_id = input;
self
}
/// Consumes the builder and constructs a [`CancelSchemaExtensionInput`](crate::input::CancelSchemaExtensionInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::CancelSchemaExtensionInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::CancelSchemaExtensionInput {
directory_id: self.directory_id,
schema_extension_id: self.schema_extension_id,
})
}
}
}
#[doc(hidden)]
pub type CancelSchemaExtensionInputOperationOutputAlias = crate::operation::CancelSchemaExtension;
#[doc(hidden)]
pub type CancelSchemaExtensionInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl CancelSchemaExtensionInput {
/// Consumes the builder and constructs an Operation<[`CancelSchemaExtension`](crate::operation::CancelSchemaExtension)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::CancelSchemaExtension,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::CancelSchemaExtensionInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::CancelSchemaExtensionInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.CancelSchemaExtension",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_cancel_schema_extension(
&self,
)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::CancelSchemaExtension::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"CancelSchemaExtension",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`CancelSchemaExtensionInput`](crate::input::CancelSchemaExtensionInput)
pub fn builder() -> crate::input::cancel_schema_extension_input::Builder {
crate::input::cancel_schema_extension_input::Builder::default()
}
}
/// See [`ConnectDirectoryInput`](crate::input::ConnectDirectoryInput)
pub mod connect_directory_input {
/// A builder for [`ConnectDirectoryInput`](crate::input::ConnectDirectoryInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) name: std::option::Option<std::string::String>,
pub(crate) short_name: std::option::Option<std::string::String>,
pub(crate) password: std::option::Option<std::string::String>,
pub(crate) description: std::option::Option<std::string::String>,
pub(crate) size: std::option::Option<crate::model::DirectorySize>,
pub(crate) connect_settings: std::option::Option<crate::model::DirectoryConnectSettings>,
pub(crate) tags: std::option::Option<std::vec::Vec<crate::model::Tag>>,
}
impl Builder {
/// <p>The fully qualified name of your self-managed directory, such as <code>corp.example.com</code>.</p>
pub fn name(mut self, input: impl Into<std::string::String>) -> Self {
self.name = Some(input.into());
self
}
/// <p>The fully qualified name of your self-managed directory, such as <code>corp.example.com</code>.</p>
pub fn set_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.name = input;
self
}
/// <p>The NetBIOS name of your self-managed directory, such as <code>CORP</code>.</p>
pub fn short_name(mut self, input: impl Into<std::string::String>) -> Self {
self.short_name = Some(input.into());
self
}
/// <p>The NetBIOS name of your self-managed directory, such as <code>CORP</code>.</p>
pub fn set_short_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.short_name = input;
self
}
/// <p>The password for your self-managed user account.</p>
pub fn password(mut self, input: impl Into<std::string::String>) -> Self {
self.password = Some(input.into());
self
}
/// <p>The password for your self-managed user account.</p>
pub fn set_password(mut self, input: std::option::Option<std::string::String>) -> Self {
self.password = input;
self
}
/// <p>A description for the directory.</p>
pub fn description(mut self, input: impl Into<std::string::String>) -> Self {
self.description = Some(input.into());
self
}
/// <p>A description for the directory.</p>
pub fn set_description(mut self, input: std::option::Option<std::string::String>) -> Self {
self.description = input;
self
}
/// <p>The size of the directory.</p>
pub fn size(mut self, input: crate::model::DirectorySize) -> Self {
self.size = Some(input);
self
}
/// <p>The size of the directory.</p>
pub fn set_size(mut self, input: std::option::Option<crate::model::DirectorySize>) -> Self {
self.size = input;
self
}
/// <p>A <code>DirectoryConnectSettings</code> object that contains additional information for the operation.</p>
pub fn connect_settings(mut self, input: crate::model::DirectoryConnectSettings) -> Self {
self.connect_settings = Some(input);
self
}
/// <p>A <code>DirectoryConnectSettings</code> object that contains additional information for the operation.</p>
pub fn set_connect_settings(
mut self,
input: std::option::Option<crate::model::DirectoryConnectSettings>,
) -> Self {
self.connect_settings = input;
self
}
/// Appends an item to `tags`.
///
/// To override the contents of this collection use [`set_tags`](Self::set_tags).
///
/// <p>The tags to be assigned to AD Connector.</p>
pub fn tags(mut self, input: crate::model::Tag) -> Self {
let mut v = self.tags.unwrap_or_default();
v.push(input);
self.tags = Some(v);
self
}
/// <p>The tags to be assigned to AD Connector.</p>
pub fn set_tags(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Tag>>,
) -> Self {
self.tags = input;
self
}
/// Consumes the builder and constructs a [`ConnectDirectoryInput`](crate::input::ConnectDirectoryInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::ConnectDirectoryInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::ConnectDirectoryInput {
name: self.name,
short_name: self.short_name,
password: self.password,
description: self.description,
size: self.size,
connect_settings: self.connect_settings,
tags: self.tags,
})
}
}
}
#[doc(hidden)]
pub type ConnectDirectoryInputOperationOutputAlias = crate::operation::ConnectDirectory;
#[doc(hidden)]
pub type ConnectDirectoryInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl ConnectDirectoryInput {
/// Consumes the builder and constructs an Operation<[`ConnectDirectory`](crate::operation::ConnectDirectory)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::ConnectDirectory,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::ConnectDirectoryInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::ConnectDirectoryInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.ConnectDirectory",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_connect_directory(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::ConnectDirectory::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"ConnectDirectory",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`ConnectDirectoryInput`](crate::input::ConnectDirectoryInput)
pub fn builder() -> crate::input::connect_directory_input::Builder {
crate::input::connect_directory_input::Builder::default()
}
}
/// See [`CreateAliasInput`](crate::input::CreateAliasInput)
pub mod create_alias_input {
/// A builder for [`CreateAliasInput`](crate::input::CreateAliasInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) alias: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The identifier of the directory for which to create the alias.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory for which to create the alias.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The requested alias.</p>
/// <p>The alias must be unique amongst all aliases in Amazon Web Services. This operation throws an <code>EntityAlreadyExistsException</code> error if the alias already exists.</p>
pub fn alias(mut self, input: impl Into<std::string::String>) -> Self {
self.alias = Some(input.into());
self
}
/// <p>The requested alias.</p>
/// <p>The alias must be unique amongst all aliases in Amazon Web Services. This operation throws an <code>EntityAlreadyExistsException</code> error if the alias already exists.</p>
pub fn set_alias(mut self, input: std::option::Option<std::string::String>) -> Self {
self.alias = input;
self
}
/// Consumes the builder and constructs a [`CreateAliasInput`](crate::input::CreateAliasInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::CreateAliasInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::CreateAliasInput {
directory_id: self.directory_id,
alias: self.alias,
})
}
}
}
#[doc(hidden)]
pub type CreateAliasInputOperationOutputAlias = crate::operation::CreateAlias;
#[doc(hidden)]
pub type CreateAliasInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl CreateAliasInput {
/// Consumes the builder and constructs an Operation<[`CreateAlias`](crate::operation::CreateAlias)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::CreateAlias,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::CreateAliasInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::CreateAliasInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.CreateAlias",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_create_alias(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::CreateAlias::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"CreateAlias",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`CreateAliasInput`](crate::input::CreateAliasInput)
pub fn builder() -> crate::input::create_alias_input::Builder {
crate::input::create_alias_input::Builder::default()
}
}
/// See [`CreateComputerInput`](crate::input::CreateComputerInput)
pub mod create_computer_input {
/// A builder for [`CreateComputerInput`](crate::input::CreateComputerInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) computer_name: std::option::Option<std::string::String>,
pub(crate) password: std::option::Option<std::string::String>,
pub(crate) organizational_unit_distinguished_name: std::option::Option<std::string::String>,
pub(crate) computer_attributes: std::option::Option<std::vec::Vec<crate::model::Attribute>>,
}
impl Builder {
/// <p>The identifier of the directory in which to create the computer account.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory in which to create the computer account.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The name of the computer account.</p>
pub fn computer_name(mut self, input: impl Into<std::string::String>) -> Self {
self.computer_name = Some(input.into());
self
}
/// <p>The name of the computer account.</p>
pub fn set_computer_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.computer_name = input;
self
}
/// <p>A one-time password that is used to join the computer to the directory. You should generate a random, strong password to use for this parameter.</p>
pub fn password(mut self, input: impl Into<std::string::String>) -> Self {
self.password = Some(input.into());
self
}
/// <p>A one-time password that is used to join the computer to the directory. You should generate a random, strong password to use for this parameter.</p>
pub fn set_password(mut self, input: std::option::Option<std::string::String>) -> Self {
self.password = input;
self
}
/// <p>The fully-qualified distinguished name of the organizational unit to place the computer account in.</p>
pub fn organizational_unit_distinguished_name(
mut self,
input: impl Into<std::string::String>,
) -> Self {
self.organizational_unit_distinguished_name = Some(input.into());
self
}
/// <p>The fully-qualified distinguished name of the organizational unit to place the computer account in.</p>
pub fn set_organizational_unit_distinguished_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.organizational_unit_distinguished_name = input;
self
}
/// Appends an item to `computer_attributes`.
///
/// To override the contents of this collection use [`set_computer_attributes`](Self::set_computer_attributes).
///
/// <p>An array of <code>Attribute</code> objects that contain any LDAP attributes to apply to the computer account.</p>
pub fn computer_attributes(mut self, input: crate::model::Attribute) -> Self {
let mut v = self.computer_attributes.unwrap_or_default();
v.push(input);
self.computer_attributes = Some(v);
self
}
/// <p>An array of <code>Attribute</code> objects that contain any LDAP attributes to apply to the computer account.</p>
pub fn set_computer_attributes(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Attribute>>,
) -> Self {
self.computer_attributes = input;
self
}
/// Consumes the builder and constructs a [`CreateComputerInput`](crate::input::CreateComputerInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::CreateComputerInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::CreateComputerInput {
directory_id: self.directory_id,
computer_name: self.computer_name,
password: self.password,
organizational_unit_distinguished_name: self.organizational_unit_distinguished_name,
computer_attributes: self.computer_attributes,
})
}
}
}
#[doc(hidden)]
pub type CreateComputerInputOperationOutputAlias = crate::operation::CreateComputer;
#[doc(hidden)]
pub type CreateComputerInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl CreateComputerInput {
/// Consumes the builder and constructs an Operation<[`CreateComputer`](crate::operation::CreateComputer)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::CreateComputer,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::CreateComputerInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::CreateComputerInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.CreateComputer",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_create_computer(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::CreateComputer::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"CreateComputer",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`CreateComputerInput`](crate::input::CreateComputerInput)
pub fn builder() -> crate::input::create_computer_input::Builder {
crate::input::create_computer_input::Builder::default()
}
}
/// See [`CreateConditionalForwarderInput`](crate::input::CreateConditionalForwarderInput)
pub mod create_conditional_forwarder_input {
/// A builder for [`CreateConditionalForwarderInput`](crate::input::CreateConditionalForwarderInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) remote_domain_name: std::option::Option<std::string::String>,
pub(crate) dns_ip_addrs: std::option::Option<std::vec::Vec<std::string::String>>,
}
impl Builder {
/// <p>The directory ID of the Amazon Web Services directory for which you are creating the conditional forwarder.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The directory ID of the Amazon Web Services directory for which you are creating the conditional forwarder.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The fully qualified domain name (FQDN) of the remote domain with which you will set up a trust relationship.</p>
pub fn remote_domain_name(mut self, input: impl Into<std::string::String>) -> Self {
self.remote_domain_name = Some(input.into());
self
}
/// <p>The fully qualified domain name (FQDN) of the remote domain with which you will set up a trust relationship.</p>
pub fn set_remote_domain_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.remote_domain_name = input;
self
}
/// Appends an item to `dns_ip_addrs`.
///
/// To override the contents of this collection use [`set_dns_ip_addrs`](Self::set_dns_ip_addrs).
///
/// <p>The IP addresses of the remote DNS server associated with RemoteDomainName.</p>
pub fn dns_ip_addrs(mut self, input: impl Into<std::string::String>) -> Self {
let mut v = self.dns_ip_addrs.unwrap_or_default();
v.push(input.into());
self.dns_ip_addrs = Some(v);
self
}
/// <p>The IP addresses of the remote DNS server associated with RemoteDomainName.</p>
pub fn set_dns_ip_addrs(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.dns_ip_addrs = input;
self
}
/// Consumes the builder and constructs a [`CreateConditionalForwarderInput`](crate::input::CreateConditionalForwarderInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::CreateConditionalForwarderInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::CreateConditionalForwarderInput {
directory_id: self.directory_id,
remote_domain_name: self.remote_domain_name,
dns_ip_addrs: self.dns_ip_addrs,
})
}
}
}
#[doc(hidden)]
pub type CreateConditionalForwarderInputOperationOutputAlias =
crate::operation::CreateConditionalForwarder;
#[doc(hidden)]
pub type CreateConditionalForwarderInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl CreateConditionalForwarderInput {
/// Consumes the builder and constructs an Operation<[`CreateConditionalForwarder`](crate::operation::CreateConditionalForwarder)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::CreateConditionalForwarder,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::CreateConditionalForwarderInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::CreateConditionalForwarderInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.CreateConditionalForwarder",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_create_conditional_forwarder(
&self,
)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::CreateConditionalForwarder::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"CreateConditionalForwarder",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`CreateConditionalForwarderInput`](crate::input::CreateConditionalForwarderInput)
pub fn builder() -> crate::input::create_conditional_forwarder_input::Builder {
crate::input::create_conditional_forwarder_input::Builder::default()
}
}
/// See [`CreateDirectoryInput`](crate::input::CreateDirectoryInput)
pub mod create_directory_input {
/// A builder for [`CreateDirectoryInput`](crate::input::CreateDirectoryInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) name: std::option::Option<std::string::String>,
pub(crate) short_name: std::option::Option<std::string::String>,
pub(crate) password: std::option::Option<std::string::String>,
pub(crate) description: std::option::Option<std::string::String>,
pub(crate) size: std::option::Option<crate::model::DirectorySize>,
pub(crate) vpc_settings: std::option::Option<crate::model::DirectoryVpcSettings>,
pub(crate) tags: std::option::Option<std::vec::Vec<crate::model::Tag>>,
}
impl Builder {
/// <p>The fully qualified name for the directory, such as <code>corp.example.com</code>.</p>
pub fn name(mut self, input: impl Into<std::string::String>) -> Self {
self.name = Some(input.into());
self
}
/// <p>The fully qualified name for the directory, such as <code>corp.example.com</code>.</p>
pub fn set_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.name = input;
self
}
/// <p>The NetBIOS name of the directory, such as <code>CORP</code>.</p>
pub fn short_name(mut self, input: impl Into<std::string::String>) -> Self {
self.short_name = Some(input.into());
self
}
/// <p>The NetBIOS name of the directory, such as <code>CORP</code>.</p>
pub fn set_short_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.short_name = input;
self
}
/// <p>The password for the directory administrator. The directory creation process creates a directory administrator account with the user name <code>Administrator</code> and this password.</p>
/// <p>If you need to change the password for the administrator account, you can use the <code>ResetUserPassword</code> API call.</p>
/// <p>The regex pattern for this string is made up of the following conditions:</p>
/// <ul>
/// <li> <p>Length (?=^.{8,64}$) – Must be between 8 and 64 characters</p> </li>
/// </ul>
/// <p>AND any 3 of the following password complexity rules required by Active Directory:</p>
/// <ul>
/// <li> <p>Numbers and upper case and lowercase (?=.*\d)(?=.*[A-Z])(?=.*[a-z])</p> </li>
/// <li> <p>Numbers and special characters and lower case (?=.*\d)(?=.*[^A-Za-z0-9\s])(?=.*[a-z])</p> </li>
/// <li> <p>Special characters and upper case and lower case (?=.*[^A-Za-z0-9\s])(?=.*[A-Z])(?=.*[a-z])</p> </li>
/// <li> <p>Numbers and upper case and special characters (?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9\s])</p> </li>
/// </ul>
/// <p>For additional information about how Active Directory passwords are enforced, see <a href="https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/password-must-meet-complexity-requirements">Password must meet complexity requirements</a> on the Microsoft website.</p>
pub fn password(mut self, input: impl Into<std::string::String>) -> Self {
self.password = Some(input.into());
self
}
/// <p>The password for the directory administrator. The directory creation process creates a directory administrator account with the user name <code>Administrator</code> and this password.</p>
/// <p>If you need to change the password for the administrator account, you can use the <code>ResetUserPassword</code> API call.</p>
/// <p>The regex pattern for this string is made up of the following conditions:</p>
/// <ul>
/// <li> <p>Length (?=^.{8,64}$) – Must be between 8 and 64 characters</p> </li>
/// </ul>
/// <p>AND any 3 of the following password complexity rules required by Active Directory:</p>
/// <ul>
/// <li> <p>Numbers and upper case and lowercase (?=.*\d)(?=.*[A-Z])(?=.*[a-z])</p> </li>
/// <li> <p>Numbers and special characters and lower case (?=.*\d)(?=.*[^A-Za-z0-9\s])(?=.*[a-z])</p> </li>
/// <li> <p>Special characters and upper case and lower case (?=.*[^A-Za-z0-9\s])(?=.*[A-Z])(?=.*[a-z])</p> </li>
/// <li> <p>Numbers and upper case and special characters (?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9\s])</p> </li>
/// </ul>
/// <p>For additional information about how Active Directory passwords are enforced, see <a href="https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/password-must-meet-complexity-requirements">Password must meet complexity requirements</a> on the Microsoft website.</p>
pub fn set_password(mut self, input: std::option::Option<std::string::String>) -> Self {
self.password = input;
self
}
/// <p>A description for the directory.</p>
pub fn description(mut self, input: impl Into<std::string::String>) -> Self {
self.description = Some(input.into());
self
}
/// <p>A description for the directory.</p>
pub fn set_description(mut self, input: std::option::Option<std::string::String>) -> Self {
self.description = input;
self
}
/// <p>The size of the directory.</p>
pub fn size(mut self, input: crate::model::DirectorySize) -> Self {
self.size = Some(input);
self
}
/// <p>The size of the directory.</p>
pub fn set_size(mut self, input: std::option::Option<crate::model::DirectorySize>) -> Self {
self.size = input;
self
}
/// <p>A <code>DirectoryVpcSettings</code> object that contains additional information for the operation.</p>
pub fn vpc_settings(mut self, input: crate::model::DirectoryVpcSettings) -> Self {
self.vpc_settings = Some(input);
self
}
/// <p>A <code>DirectoryVpcSettings</code> object that contains additional information for the operation.</p>
pub fn set_vpc_settings(
mut self,
input: std::option::Option<crate::model::DirectoryVpcSettings>,
) -> Self {
self.vpc_settings = input;
self
}
/// Appends an item to `tags`.
///
/// To override the contents of this collection use [`set_tags`](Self::set_tags).
///
/// <p>The tags to be assigned to the Simple AD directory.</p>
pub fn tags(mut self, input: crate::model::Tag) -> Self {
let mut v = self.tags.unwrap_or_default();
v.push(input);
self.tags = Some(v);
self
}
/// <p>The tags to be assigned to the Simple AD directory.</p>
pub fn set_tags(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Tag>>,
) -> Self {
self.tags = input;
self
}
/// Consumes the builder and constructs a [`CreateDirectoryInput`](crate::input::CreateDirectoryInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::CreateDirectoryInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::CreateDirectoryInput {
name: self.name,
short_name: self.short_name,
password: self.password,
description: self.description,
size: self.size,
vpc_settings: self.vpc_settings,
tags: self.tags,
})
}
}
}
#[doc(hidden)]
pub type CreateDirectoryInputOperationOutputAlias = crate::operation::CreateDirectory;
#[doc(hidden)]
pub type CreateDirectoryInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl CreateDirectoryInput {
/// Consumes the builder and constructs an Operation<[`CreateDirectory`](crate::operation::CreateDirectory)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::CreateDirectory,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::CreateDirectoryInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::CreateDirectoryInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.CreateDirectory",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_create_directory(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::CreateDirectory::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"CreateDirectory",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`CreateDirectoryInput`](crate::input::CreateDirectoryInput)
pub fn builder() -> crate::input::create_directory_input::Builder {
crate::input::create_directory_input::Builder::default()
}
}
/// See [`CreateLogSubscriptionInput`](crate::input::CreateLogSubscriptionInput)
pub mod create_log_subscription_input {
/// A builder for [`CreateLogSubscriptionInput`](crate::input::CreateLogSubscriptionInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) log_group_name: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>Identifier of the directory to which you want to subscribe and receive real-time logs to your specified CloudWatch log group.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>Identifier of the directory to which you want to subscribe and receive real-time logs to your specified CloudWatch log group.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The name of the CloudWatch log group where the real-time domain controller logs are forwarded.</p>
pub fn log_group_name(mut self, input: impl Into<std::string::String>) -> Self {
self.log_group_name = Some(input.into());
self
}
/// <p>The name of the CloudWatch log group where the real-time domain controller logs are forwarded.</p>
pub fn set_log_group_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.log_group_name = input;
self
}
/// Consumes the builder and constructs a [`CreateLogSubscriptionInput`](crate::input::CreateLogSubscriptionInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::CreateLogSubscriptionInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::CreateLogSubscriptionInput {
directory_id: self.directory_id,
log_group_name: self.log_group_name,
})
}
}
}
#[doc(hidden)]
pub type CreateLogSubscriptionInputOperationOutputAlias = crate::operation::CreateLogSubscription;
#[doc(hidden)]
pub type CreateLogSubscriptionInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl CreateLogSubscriptionInput {
/// Consumes the builder and constructs an Operation<[`CreateLogSubscription`](crate::operation::CreateLogSubscription)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::CreateLogSubscription,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::CreateLogSubscriptionInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::CreateLogSubscriptionInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.CreateLogSubscription",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_create_log_subscription(
&self,
)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::CreateLogSubscription::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"CreateLogSubscription",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`CreateLogSubscriptionInput`](crate::input::CreateLogSubscriptionInput)
pub fn builder() -> crate::input::create_log_subscription_input::Builder {
crate::input::create_log_subscription_input::Builder::default()
}
}
/// See [`CreateMicrosoftAdInput`](crate::input::CreateMicrosoftAdInput)
pub mod create_microsoft_ad_input {
/// A builder for [`CreateMicrosoftAdInput`](crate::input::CreateMicrosoftAdInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) name: std::option::Option<std::string::String>,
pub(crate) short_name: std::option::Option<std::string::String>,
pub(crate) password: std::option::Option<std::string::String>,
pub(crate) description: std::option::Option<std::string::String>,
pub(crate) vpc_settings: std::option::Option<crate::model::DirectoryVpcSettings>,
pub(crate) edition: std::option::Option<crate::model::DirectoryEdition>,
pub(crate) tags: std::option::Option<std::vec::Vec<crate::model::Tag>>,
}
impl Builder {
/// <p>The fully qualified domain name for the Managed Microsoft AD directory, such as <code>corp.example.com</code>. This name will resolve inside your VPC only. It does not need to be publicly resolvable.</p>
pub fn name(mut self, input: impl Into<std::string::String>) -> Self {
self.name = Some(input.into());
self
}
/// <p>The fully qualified domain name for the Managed Microsoft AD directory, such as <code>corp.example.com</code>. This name will resolve inside your VPC only. It does not need to be publicly resolvable.</p>
pub fn set_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.name = input;
self
}
/// <p>The NetBIOS name for your domain, such as <code>CORP</code>. If you don't specify a NetBIOS name, it will default to the first part of your directory DNS. For example, <code>CORP</code> for the directory DNS <code>corp.example.com</code>. </p>
pub fn short_name(mut self, input: impl Into<std::string::String>) -> Self {
self.short_name = Some(input.into());
self
}
/// <p>The NetBIOS name for your domain, such as <code>CORP</code>. If you don't specify a NetBIOS name, it will default to the first part of your directory DNS. For example, <code>CORP</code> for the directory DNS <code>corp.example.com</code>. </p>
pub fn set_short_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.short_name = input;
self
}
/// <p>The password for the default administrative user named <code>Admin</code>.</p>
/// <p>If you need to change the password for the administrator account, you can use the <code>ResetUserPassword</code> API call.</p>
pub fn password(mut self, input: impl Into<std::string::String>) -> Self {
self.password = Some(input.into());
self
}
/// <p>The password for the default administrative user named <code>Admin</code>.</p>
/// <p>If you need to change the password for the administrator account, you can use the <code>ResetUserPassword</code> API call.</p>
pub fn set_password(mut self, input: std::option::Option<std::string::String>) -> Self {
self.password = input;
self
}
/// <p>A description for the directory. This label will appear on the Amazon Web Services console <code>Directory Details</code> page after the directory is created.</p>
pub fn description(mut self, input: impl Into<std::string::String>) -> Self {
self.description = Some(input.into());
self
}
/// <p>A description for the directory. This label will appear on the Amazon Web Services console <code>Directory Details</code> page after the directory is created.</p>
pub fn set_description(mut self, input: std::option::Option<std::string::String>) -> Self {
self.description = input;
self
}
/// <p>Contains VPC information for the <code>CreateDirectory</code> or <code>CreateMicrosoftAD</code> operation.</p>
pub fn vpc_settings(mut self, input: crate::model::DirectoryVpcSettings) -> Self {
self.vpc_settings = Some(input);
self
}
/// <p>Contains VPC information for the <code>CreateDirectory</code> or <code>CreateMicrosoftAD</code> operation.</p>
pub fn set_vpc_settings(
mut self,
input: std::option::Option<crate::model::DirectoryVpcSettings>,
) -> Self {
self.vpc_settings = input;
self
}
/// <p>Managed Microsoft AD is available in two editions: <code>Standard</code> and <code>Enterprise</code>. <code>Enterprise</code> is the default.</p>
pub fn edition(mut self, input: crate::model::DirectoryEdition) -> Self {
self.edition = Some(input);
self
}
/// <p>Managed Microsoft AD is available in two editions: <code>Standard</code> and <code>Enterprise</code>. <code>Enterprise</code> is the default.</p>
pub fn set_edition(
mut self,
input: std::option::Option<crate::model::DirectoryEdition>,
) -> Self {
self.edition = input;
self
}
/// Appends an item to `tags`.
///
/// To override the contents of this collection use [`set_tags`](Self::set_tags).
///
/// <p>The tags to be assigned to the Managed Microsoft AD directory.</p>
pub fn tags(mut self, input: crate::model::Tag) -> Self {
let mut v = self.tags.unwrap_or_default();
v.push(input);
self.tags = Some(v);
self
}
/// <p>The tags to be assigned to the Managed Microsoft AD directory.</p>
pub fn set_tags(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Tag>>,
) -> Self {
self.tags = input;
self
}
/// Consumes the builder and constructs a [`CreateMicrosoftAdInput`](crate::input::CreateMicrosoftAdInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::CreateMicrosoftAdInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::CreateMicrosoftAdInput {
name: self.name,
short_name: self.short_name,
password: self.password,
description: self.description,
vpc_settings: self.vpc_settings,
edition: self.edition,
tags: self.tags,
})
}
}
}
#[doc(hidden)]
pub type CreateMicrosoftAdInputOperationOutputAlias = crate::operation::CreateMicrosoftAD;
#[doc(hidden)]
pub type CreateMicrosoftAdInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl CreateMicrosoftAdInput {
/// Consumes the builder and constructs an Operation<[`CreateMicrosoftAD`](crate::operation::CreateMicrosoftAD)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::CreateMicrosoftAD,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::CreateMicrosoftAdInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::CreateMicrosoftAdInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.CreateMicrosoftAD",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_create_microsoft_ad(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::CreateMicrosoftAD::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"CreateMicrosoftAD",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`CreateMicrosoftAdInput`](crate::input::CreateMicrosoftAdInput)
pub fn builder() -> crate::input::create_microsoft_ad_input::Builder {
crate::input::create_microsoft_ad_input::Builder::default()
}
}
/// See [`CreateSnapshotInput`](crate::input::CreateSnapshotInput)
pub mod create_snapshot_input {
/// A builder for [`CreateSnapshotInput`](crate::input::CreateSnapshotInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) name: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The identifier of the directory of which to take a snapshot.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory of which to take a snapshot.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The descriptive name to apply to the snapshot.</p>
pub fn name(mut self, input: impl Into<std::string::String>) -> Self {
self.name = Some(input.into());
self
}
/// <p>The descriptive name to apply to the snapshot.</p>
pub fn set_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.name = input;
self
}
/// Consumes the builder and constructs a [`CreateSnapshotInput`](crate::input::CreateSnapshotInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::CreateSnapshotInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::CreateSnapshotInput {
directory_id: self.directory_id,
name: self.name,
})
}
}
}
#[doc(hidden)]
pub type CreateSnapshotInputOperationOutputAlias = crate::operation::CreateSnapshot;
#[doc(hidden)]
pub type CreateSnapshotInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl CreateSnapshotInput {
/// Consumes the builder and constructs an Operation<[`CreateSnapshot`](crate::operation::CreateSnapshot)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::CreateSnapshot,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::CreateSnapshotInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::CreateSnapshotInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.CreateSnapshot",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_create_snapshot(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::CreateSnapshot::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"CreateSnapshot",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`CreateSnapshotInput`](crate::input::CreateSnapshotInput)
pub fn builder() -> crate::input::create_snapshot_input::Builder {
crate::input::create_snapshot_input::Builder::default()
}
}
/// See [`CreateTrustInput`](crate::input::CreateTrustInput)
pub mod create_trust_input {
/// A builder for [`CreateTrustInput`](crate::input::CreateTrustInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) remote_domain_name: std::option::Option<std::string::String>,
pub(crate) trust_password: std::option::Option<std::string::String>,
pub(crate) trust_direction: std::option::Option<crate::model::TrustDirection>,
pub(crate) trust_type: std::option::Option<crate::model::TrustType>,
pub(crate) conditional_forwarder_ip_addrs:
std::option::Option<std::vec::Vec<std::string::String>>,
pub(crate) selective_auth: std::option::Option<crate::model::SelectiveAuth>,
}
impl Builder {
/// <p>The Directory ID of the Managed Microsoft AD directory for which to establish the trust relationship.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The Directory ID of the Managed Microsoft AD directory for which to establish the trust relationship.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The Fully Qualified Domain Name (FQDN) of the external domain for which to create the trust relationship.</p>
pub fn remote_domain_name(mut self, input: impl Into<std::string::String>) -> Self {
self.remote_domain_name = Some(input.into());
self
}
/// <p>The Fully Qualified Domain Name (FQDN) of the external domain for which to create the trust relationship.</p>
pub fn set_remote_domain_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.remote_domain_name = input;
self
}
/// <p>The trust password. The must be the same password that was used when creating the trust relationship on the external domain.</p>
pub fn trust_password(mut self, input: impl Into<std::string::String>) -> Self {
self.trust_password = Some(input.into());
self
}
/// <p>The trust password. The must be the same password that was used when creating the trust relationship on the external domain.</p>
pub fn set_trust_password(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.trust_password = input;
self
}
/// <p>The direction of the trust relationship.</p>
pub fn trust_direction(mut self, input: crate::model::TrustDirection) -> Self {
self.trust_direction = Some(input);
self
}
/// <p>The direction of the trust relationship.</p>
pub fn set_trust_direction(
mut self,
input: std::option::Option<crate::model::TrustDirection>,
) -> Self {
self.trust_direction = input;
self
}
/// <p>The trust relationship type. <code>Forest</code> is the default.</p>
pub fn trust_type(mut self, input: crate::model::TrustType) -> Self {
self.trust_type = Some(input);
self
}
/// <p>The trust relationship type. <code>Forest</code> is the default.</p>
pub fn set_trust_type(
mut self,
input: std::option::Option<crate::model::TrustType>,
) -> Self {
self.trust_type = input;
self
}
/// Appends an item to `conditional_forwarder_ip_addrs`.
///
/// To override the contents of this collection use [`set_conditional_forwarder_ip_addrs`](Self::set_conditional_forwarder_ip_addrs).
///
/// <p>The IP addresses of the remote DNS server associated with RemoteDomainName.</p>
pub fn conditional_forwarder_ip_addrs(
mut self,
input: impl Into<std::string::String>,
) -> Self {
let mut v = self.conditional_forwarder_ip_addrs.unwrap_or_default();
v.push(input.into());
self.conditional_forwarder_ip_addrs = Some(v);
self
}
/// <p>The IP addresses of the remote DNS server associated with RemoteDomainName.</p>
pub fn set_conditional_forwarder_ip_addrs(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.conditional_forwarder_ip_addrs = input;
self
}
/// <p>Optional parameter to enable selective authentication for the trust.</p>
pub fn selective_auth(mut self, input: crate::model::SelectiveAuth) -> Self {
self.selective_auth = Some(input);
self
}
/// <p>Optional parameter to enable selective authentication for the trust.</p>
pub fn set_selective_auth(
mut self,
input: std::option::Option<crate::model::SelectiveAuth>,
) -> Self {
self.selective_auth = input;
self
}
/// Consumes the builder and constructs a [`CreateTrustInput`](crate::input::CreateTrustInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::CreateTrustInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::CreateTrustInput {
directory_id: self.directory_id,
remote_domain_name: self.remote_domain_name,
trust_password: self.trust_password,
trust_direction: self.trust_direction,
trust_type: self.trust_type,
conditional_forwarder_ip_addrs: self.conditional_forwarder_ip_addrs,
selective_auth: self.selective_auth,
})
}
}
}
#[doc(hidden)]
pub type CreateTrustInputOperationOutputAlias = crate::operation::CreateTrust;
#[doc(hidden)]
pub type CreateTrustInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl CreateTrustInput {
/// Consumes the builder and constructs an Operation<[`CreateTrust`](crate::operation::CreateTrust)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::CreateTrust,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::CreateTrustInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::CreateTrustInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.CreateTrust",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_create_trust(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::CreateTrust::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"CreateTrust",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`CreateTrustInput`](crate::input::CreateTrustInput)
pub fn builder() -> crate::input::create_trust_input::Builder {
crate::input::create_trust_input::Builder::default()
}
}
/// See [`DeleteConditionalForwarderInput`](crate::input::DeleteConditionalForwarderInput)
pub mod delete_conditional_forwarder_input {
/// A builder for [`DeleteConditionalForwarderInput`](crate::input::DeleteConditionalForwarderInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) remote_domain_name: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The directory ID for which you are deleting the conditional forwarder.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The directory ID for which you are deleting the conditional forwarder.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The fully qualified domain name (FQDN) of the remote domain with which you are deleting the conditional forwarder.</p>
pub fn remote_domain_name(mut self, input: impl Into<std::string::String>) -> Self {
self.remote_domain_name = Some(input.into());
self
}
/// <p>The fully qualified domain name (FQDN) of the remote domain with which you are deleting the conditional forwarder.</p>
pub fn set_remote_domain_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.remote_domain_name = input;
self
}
/// Consumes the builder and constructs a [`DeleteConditionalForwarderInput`](crate::input::DeleteConditionalForwarderInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::DeleteConditionalForwarderInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::DeleteConditionalForwarderInput {
directory_id: self.directory_id,
remote_domain_name: self.remote_domain_name,
})
}
}
}
#[doc(hidden)]
pub type DeleteConditionalForwarderInputOperationOutputAlias =
crate::operation::DeleteConditionalForwarder;
#[doc(hidden)]
pub type DeleteConditionalForwarderInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl DeleteConditionalForwarderInput {
/// Consumes the builder and constructs an Operation<[`DeleteConditionalForwarder`](crate::operation::DeleteConditionalForwarder)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::DeleteConditionalForwarder,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::DeleteConditionalForwarderInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::DeleteConditionalForwarderInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.DeleteConditionalForwarder",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_delete_conditional_forwarder(
&self,
)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::DeleteConditionalForwarder::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"DeleteConditionalForwarder",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`DeleteConditionalForwarderInput`](crate::input::DeleteConditionalForwarderInput)
pub fn builder() -> crate::input::delete_conditional_forwarder_input::Builder {
crate::input::delete_conditional_forwarder_input::Builder::default()
}
}
/// See [`DeleteDirectoryInput`](crate::input::DeleteDirectoryInput)
pub mod delete_directory_input {
/// A builder for [`DeleteDirectoryInput`](crate::input::DeleteDirectoryInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The identifier of the directory to delete.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory to delete.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// Consumes the builder and constructs a [`DeleteDirectoryInput`](crate::input::DeleteDirectoryInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::DeleteDirectoryInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::DeleteDirectoryInput {
directory_id: self.directory_id,
})
}
}
}
#[doc(hidden)]
pub type DeleteDirectoryInputOperationOutputAlias = crate::operation::DeleteDirectory;
#[doc(hidden)]
pub type DeleteDirectoryInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl DeleteDirectoryInput {
/// Consumes the builder and constructs an Operation<[`DeleteDirectory`](crate::operation::DeleteDirectory)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::DeleteDirectory,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::DeleteDirectoryInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::DeleteDirectoryInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.DeleteDirectory",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_delete_directory(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::DeleteDirectory::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"DeleteDirectory",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`DeleteDirectoryInput`](crate::input::DeleteDirectoryInput)
pub fn builder() -> crate::input::delete_directory_input::Builder {
crate::input::delete_directory_input::Builder::default()
}
}
/// See [`DeleteLogSubscriptionInput`](crate::input::DeleteLogSubscriptionInput)
pub mod delete_log_subscription_input {
/// A builder for [`DeleteLogSubscriptionInput`](crate::input::DeleteLogSubscriptionInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>Identifier of the directory whose log subscription you want to delete.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>Identifier of the directory whose log subscription you want to delete.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// Consumes the builder and constructs a [`DeleteLogSubscriptionInput`](crate::input::DeleteLogSubscriptionInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::DeleteLogSubscriptionInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::DeleteLogSubscriptionInput {
directory_id: self.directory_id,
})
}
}
}
#[doc(hidden)]
pub type DeleteLogSubscriptionInputOperationOutputAlias = crate::operation::DeleteLogSubscription;
#[doc(hidden)]
pub type DeleteLogSubscriptionInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl DeleteLogSubscriptionInput {
/// Consumes the builder and constructs an Operation<[`DeleteLogSubscription`](crate::operation::DeleteLogSubscription)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::DeleteLogSubscription,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::DeleteLogSubscriptionInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::DeleteLogSubscriptionInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.DeleteLogSubscription",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_delete_log_subscription(
&self,
)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::DeleteLogSubscription::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"DeleteLogSubscription",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`DeleteLogSubscriptionInput`](crate::input::DeleteLogSubscriptionInput)
pub fn builder() -> crate::input::delete_log_subscription_input::Builder {
crate::input::delete_log_subscription_input::Builder::default()
}
}
/// See [`DeleteSnapshotInput`](crate::input::DeleteSnapshotInput)
pub mod delete_snapshot_input {
/// A builder for [`DeleteSnapshotInput`](crate::input::DeleteSnapshotInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) snapshot_id: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The identifier of the directory snapshot to be deleted.</p>
pub fn snapshot_id(mut self, input: impl Into<std::string::String>) -> Self {
self.snapshot_id = Some(input.into());
self
}
/// <p>The identifier of the directory snapshot to be deleted.</p>
pub fn set_snapshot_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.snapshot_id = input;
self
}
/// Consumes the builder and constructs a [`DeleteSnapshotInput`](crate::input::DeleteSnapshotInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::DeleteSnapshotInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::DeleteSnapshotInput {
snapshot_id: self.snapshot_id,
})
}
}
}
#[doc(hidden)]
pub type DeleteSnapshotInputOperationOutputAlias = crate::operation::DeleteSnapshot;
#[doc(hidden)]
pub type DeleteSnapshotInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl DeleteSnapshotInput {
/// Consumes the builder and constructs an Operation<[`DeleteSnapshot`](crate::operation::DeleteSnapshot)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::DeleteSnapshot,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::DeleteSnapshotInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::DeleteSnapshotInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.DeleteSnapshot",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_delete_snapshot(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::DeleteSnapshot::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"DeleteSnapshot",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`DeleteSnapshotInput`](crate::input::DeleteSnapshotInput)
pub fn builder() -> crate::input::delete_snapshot_input::Builder {
crate::input::delete_snapshot_input::Builder::default()
}
}
/// See [`DeleteTrustInput`](crate::input::DeleteTrustInput)
pub mod delete_trust_input {
/// A builder for [`DeleteTrustInput`](crate::input::DeleteTrustInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) trust_id: std::option::Option<std::string::String>,
pub(crate) delete_associated_conditional_forwarder: std::option::Option<bool>,
}
impl Builder {
/// <p>The Trust ID of the trust relationship to be deleted.</p>
pub fn trust_id(mut self, input: impl Into<std::string::String>) -> Self {
self.trust_id = Some(input.into());
self
}
/// <p>The Trust ID of the trust relationship to be deleted.</p>
pub fn set_trust_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.trust_id = input;
self
}
/// <p>Delete a conditional forwarder as part of a DeleteTrustRequest.</p>
pub fn delete_associated_conditional_forwarder(mut self, input: bool) -> Self {
self.delete_associated_conditional_forwarder = Some(input);
self
}
/// <p>Delete a conditional forwarder as part of a DeleteTrustRequest.</p>
pub fn set_delete_associated_conditional_forwarder(
mut self,
input: std::option::Option<bool>,
) -> Self {
self.delete_associated_conditional_forwarder = input;
self
}
/// Consumes the builder and constructs a [`DeleteTrustInput`](crate::input::DeleteTrustInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::DeleteTrustInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::DeleteTrustInput {
trust_id: self.trust_id,
delete_associated_conditional_forwarder: self
.delete_associated_conditional_forwarder
.unwrap_or_default(),
})
}
}
}
#[doc(hidden)]
pub type DeleteTrustInputOperationOutputAlias = crate::operation::DeleteTrust;
#[doc(hidden)]
pub type DeleteTrustInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl DeleteTrustInput {
/// Consumes the builder and constructs an Operation<[`DeleteTrust`](crate::operation::DeleteTrust)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::DeleteTrust,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::DeleteTrustInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::DeleteTrustInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.DeleteTrust",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_delete_trust(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::DeleteTrust::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"DeleteTrust",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`DeleteTrustInput`](crate::input::DeleteTrustInput)
pub fn builder() -> crate::input::delete_trust_input::Builder {
crate::input::delete_trust_input::Builder::default()
}
}
/// See [`DeregisterCertificateInput`](crate::input::DeregisterCertificateInput)
pub mod deregister_certificate_input {
/// A builder for [`DeregisterCertificateInput`](crate::input::DeregisterCertificateInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) certificate_id: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The identifier of the directory.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The identifier of the certificate.</p>
pub fn certificate_id(mut self, input: impl Into<std::string::String>) -> Self {
self.certificate_id = Some(input.into());
self
}
/// <p>The identifier of the certificate.</p>
pub fn set_certificate_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.certificate_id = input;
self
}
/// Consumes the builder and constructs a [`DeregisterCertificateInput`](crate::input::DeregisterCertificateInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::DeregisterCertificateInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::DeregisterCertificateInput {
directory_id: self.directory_id,
certificate_id: self.certificate_id,
})
}
}
}
#[doc(hidden)]
pub type DeregisterCertificateInputOperationOutputAlias = crate::operation::DeregisterCertificate;
#[doc(hidden)]
pub type DeregisterCertificateInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl DeregisterCertificateInput {
/// Consumes the builder and constructs an Operation<[`DeregisterCertificate`](crate::operation::DeregisterCertificate)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::DeregisterCertificate,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::DeregisterCertificateInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::DeregisterCertificateInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.DeregisterCertificate",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_deregister_certificate(
&self,
)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::DeregisterCertificate::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"DeregisterCertificate",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`DeregisterCertificateInput`](crate::input::DeregisterCertificateInput)
pub fn builder() -> crate::input::deregister_certificate_input::Builder {
crate::input::deregister_certificate_input::Builder::default()
}
}
/// See [`DeregisterEventTopicInput`](crate::input::DeregisterEventTopicInput)
pub mod deregister_event_topic_input {
/// A builder for [`DeregisterEventTopicInput`](crate::input::DeregisterEventTopicInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) topic_name: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The Directory ID to remove as a publisher. This directory will no longer send messages to the specified Amazon SNS topic.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The Directory ID to remove as a publisher. This directory will no longer send messages to the specified Amazon SNS topic.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The name of the Amazon SNS topic from which to remove the directory as a publisher.</p>
pub fn topic_name(mut self, input: impl Into<std::string::String>) -> Self {
self.topic_name = Some(input.into());
self
}
/// <p>The name of the Amazon SNS topic from which to remove the directory as a publisher.</p>
pub fn set_topic_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.topic_name = input;
self
}
/// Consumes the builder and constructs a [`DeregisterEventTopicInput`](crate::input::DeregisterEventTopicInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::DeregisterEventTopicInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::DeregisterEventTopicInput {
directory_id: self.directory_id,
topic_name: self.topic_name,
})
}
}
}
#[doc(hidden)]
pub type DeregisterEventTopicInputOperationOutputAlias = crate::operation::DeregisterEventTopic;
#[doc(hidden)]
pub type DeregisterEventTopicInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl DeregisterEventTopicInput {
/// Consumes the builder and constructs an Operation<[`DeregisterEventTopic`](crate::operation::DeregisterEventTopic)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::DeregisterEventTopic,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::DeregisterEventTopicInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::DeregisterEventTopicInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.DeregisterEventTopic",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_deregister_event_topic(
&self,
)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::DeregisterEventTopic::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"DeregisterEventTopic",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`DeregisterEventTopicInput`](crate::input::DeregisterEventTopicInput)
pub fn builder() -> crate::input::deregister_event_topic_input::Builder {
crate::input::deregister_event_topic_input::Builder::default()
}
}
/// See [`DescribeCertificateInput`](crate::input::DescribeCertificateInput)
pub mod describe_certificate_input {
/// A builder for [`DescribeCertificateInput`](crate::input::DescribeCertificateInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) certificate_id: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The identifier of the directory.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The identifier of the certificate.</p>
pub fn certificate_id(mut self, input: impl Into<std::string::String>) -> Self {
self.certificate_id = Some(input.into());
self
}
/// <p>The identifier of the certificate.</p>
pub fn set_certificate_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.certificate_id = input;
self
}
/// Consumes the builder and constructs a [`DescribeCertificateInput`](crate::input::DescribeCertificateInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::DescribeCertificateInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::DescribeCertificateInput {
directory_id: self.directory_id,
certificate_id: self.certificate_id,
})
}
}
}
#[doc(hidden)]
pub type DescribeCertificateInputOperationOutputAlias = crate::operation::DescribeCertificate;
#[doc(hidden)]
pub type DescribeCertificateInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl DescribeCertificateInput {
/// Consumes the builder and constructs an Operation<[`DescribeCertificate`](crate::operation::DescribeCertificate)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::DescribeCertificate,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::DescribeCertificateInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::DescribeCertificateInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.DescribeCertificate",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_describe_certificate(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::DescribeCertificate::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"DescribeCertificate",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`DescribeCertificateInput`](crate::input::DescribeCertificateInput)
pub fn builder() -> crate::input::describe_certificate_input::Builder {
crate::input::describe_certificate_input::Builder::default()
}
}
/// See [`DescribeClientAuthenticationSettingsInput`](crate::input::DescribeClientAuthenticationSettingsInput)
pub mod describe_client_authentication_settings_input {
/// A builder for [`DescribeClientAuthenticationSettingsInput`](crate::input::DescribeClientAuthenticationSettingsInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) r#type: std::option::Option<crate::model::ClientAuthenticationType>,
pub(crate) next_token: std::option::Option<std::string::String>,
pub(crate) limit: std::option::Option<i32>,
}
impl Builder {
/// <p>The identifier of the directory for which to retrieve information.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory for which to retrieve information.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The type of client authentication for which to retrieve information. If no type is specified, a list of all client authentication types that are supported for the specified directory is retrieved.</p>
pub fn r#type(mut self, input: crate::model::ClientAuthenticationType) -> Self {
self.r#type = Some(input);
self
}
/// <p>The type of client authentication for which to retrieve information. If no type is specified, a list of all client authentication types that are supported for the specified directory is retrieved.</p>
pub fn set_type(
mut self,
input: std::option::Option<crate::model::ClientAuthenticationType>,
) -> Self {
self.r#type = input;
self
}
/// <p>The <i>DescribeClientAuthenticationSettingsResult.NextToken</i> value from a previous call to <code>DescribeClientAuthenticationSettings</code>. Pass null if this is the first call.</p>
pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self {
self.next_token = Some(input.into());
self
}
/// <p>The <i>DescribeClientAuthenticationSettingsResult.NextToken</i> value from a previous call to <code>DescribeClientAuthenticationSettings</code>. Pass null if this is the first call.</p>
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.next_token = input;
self
}
/// <p>The maximum number of items to return. If this value is zero, the maximum number of items is specified by the limitations of the operation. </p>
pub fn limit(mut self, input: i32) -> Self {
self.limit = Some(input);
self
}
/// <p>The maximum number of items to return. If this value is zero, the maximum number of items is specified by the limitations of the operation. </p>
pub fn set_limit(mut self, input: std::option::Option<i32>) -> Self {
self.limit = input;
self
}
/// Consumes the builder and constructs a [`DescribeClientAuthenticationSettingsInput`](crate::input::DescribeClientAuthenticationSettingsInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::DescribeClientAuthenticationSettingsInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::DescribeClientAuthenticationSettingsInput {
directory_id: self.directory_id,
r#type: self.r#type,
next_token: self.next_token,
limit: self.limit,
})
}
}
}
#[doc(hidden)]
pub type DescribeClientAuthenticationSettingsInputOperationOutputAlias =
crate::operation::DescribeClientAuthenticationSettings;
#[doc(hidden)]
pub type DescribeClientAuthenticationSettingsInputOperationRetryAlias =
aws_http::retry::AwsErrorRetryPolicy;
impl DescribeClientAuthenticationSettingsInput {
/// Consumes the builder and constructs an Operation<[`DescribeClientAuthenticationSettings`](crate::operation::DescribeClientAuthenticationSettings)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::DescribeClientAuthenticationSettings,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::DescribeClientAuthenticationSettingsInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::DescribeClientAuthenticationSettingsInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.DescribeClientAuthenticationSettings",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_describe_client_authentication_settings(&self)?
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::DescribeClientAuthenticationSettings::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"DescribeClientAuthenticationSettings",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`DescribeClientAuthenticationSettingsInput`](crate::input::DescribeClientAuthenticationSettingsInput)
pub fn builder() -> crate::input::describe_client_authentication_settings_input::Builder {
crate::input::describe_client_authentication_settings_input::Builder::default()
}
}
/// See [`DescribeConditionalForwardersInput`](crate::input::DescribeConditionalForwardersInput)
pub mod describe_conditional_forwarders_input {
/// A builder for [`DescribeConditionalForwardersInput`](crate::input::DescribeConditionalForwardersInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) remote_domain_names: std::option::Option<std::vec::Vec<std::string::String>>,
}
impl Builder {
/// <p>The directory ID for which to get the list of associated conditional forwarders.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The directory ID for which to get the list of associated conditional forwarders.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// Appends an item to `remote_domain_names`.
///
/// To override the contents of this collection use [`set_remote_domain_names`](Self::set_remote_domain_names).
///
/// <p>The fully qualified domain names (FQDN) of the remote domains for which to get the list of associated conditional forwarders. If this member is null, all conditional forwarders are returned.</p>
pub fn remote_domain_names(mut self, input: impl Into<std::string::String>) -> Self {
let mut v = self.remote_domain_names.unwrap_or_default();
v.push(input.into());
self.remote_domain_names = Some(v);
self
}
/// <p>The fully qualified domain names (FQDN) of the remote domains for which to get the list of associated conditional forwarders. If this member is null, all conditional forwarders are returned.</p>
pub fn set_remote_domain_names(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.remote_domain_names = input;
self
}
/// Consumes the builder and constructs a [`DescribeConditionalForwardersInput`](crate::input::DescribeConditionalForwardersInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::DescribeConditionalForwardersInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::DescribeConditionalForwardersInput {
directory_id: self.directory_id,
remote_domain_names: self.remote_domain_names,
})
}
}
}
#[doc(hidden)]
pub type DescribeConditionalForwardersInputOperationOutputAlias =
crate::operation::DescribeConditionalForwarders;
#[doc(hidden)]
pub type DescribeConditionalForwardersInputOperationRetryAlias =
aws_http::retry::AwsErrorRetryPolicy;
impl DescribeConditionalForwardersInput {
/// Consumes the builder and constructs an Operation<[`DescribeConditionalForwarders`](crate::operation::DescribeConditionalForwarders)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::DescribeConditionalForwarders,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::DescribeConditionalForwardersInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::DescribeConditionalForwardersInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.DescribeConditionalForwarders",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_describe_conditional_forwarders(&self)?
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::DescribeConditionalForwarders::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"DescribeConditionalForwarders",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`DescribeConditionalForwardersInput`](crate::input::DescribeConditionalForwardersInput)
pub fn builder() -> crate::input::describe_conditional_forwarders_input::Builder {
crate::input::describe_conditional_forwarders_input::Builder::default()
}
}
/// See [`DescribeDirectoriesInput`](crate::input::DescribeDirectoriesInput)
pub mod describe_directories_input {
/// A builder for [`DescribeDirectoriesInput`](crate::input::DescribeDirectoriesInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_ids: std::option::Option<std::vec::Vec<std::string::String>>,
pub(crate) next_token: std::option::Option<std::string::String>,
pub(crate) limit: std::option::Option<i32>,
}
impl Builder {
/// Appends an item to `directory_ids`.
///
/// To override the contents of this collection use [`set_directory_ids`](Self::set_directory_ids).
///
/// <p>A list of identifiers of the directories for which to obtain the information. If this member is null, all directories that belong to the current account are returned.</p>
/// <p>An empty list results in an <code>InvalidParameterException</code> being thrown.</p>
pub fn directory_ids(mut self, input: impl Into<std::string::String>) -> Self {
let mut v = self.directory_ids.unwrap_or_default();
v.push(input.into());
self.directory_ids = Some(v);
self
}
/// <p>A list of identifiers of the directories for which to obtain the information. If this member is null, all directories that belong to the current account are returned.</p>
/// <p>An empty list results in an <code>InvalidParameterException</code> being thrown.</p>
pub fn set_directory_ids(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.directory_ids = input;
self
}
/// <p>The <code>DescribeDirectoriesResult.NextToken</code> value from a previous call to <code>DescribeDirectories</code>. Pass null if this is the first call.</p>
pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self {
self.next_token = Some(input.into());
self
}
/// <p>The <code>DescribeDirectoriesResult.NextToken</code> value from a previous call to <code>DescribeDirectories</code>. Pass null if this is the first call.</p>
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.next_token = input;
self
}
/// <p>The maximum number of items to return. If this value is zero, the maximum number of items is specified by the limitations of the operation.</p>
pub fn limit(mut self, input: i32) -> Self {
self.limit = Some(input);
self
}
/// <p>The maximum number of items to return. If this value is zero, the maximum number of items is specified by the limitations of the operation.</p>
pub fn set_limit(mut self, input: std::option::Option<i32>) -> Self {
self.limit = input;
self
}
/// Consumes the builder and constructs a [`DescribeDirectoriesInput`](crate::input::DescribeDirectoriesInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::DescribeDirectoriesInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::DescribeDirectoriesInput {
directory_ids: self.directory_ids,
next_token: self.next_token,
limit: self.limit,
})
}
}
}
#[doc(hidden)]
pub type DescribeDirectoriesInputOperationOutputAlias = crate::operation::DescribeDirectories;
#[doc(hidden)]
pub type DescribeDirectoriesInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl DescribeDirectoriesInput {
/// Consumes the builder and constructs an Operation<[`DescribeDirectories`](crate::operation::DescribeDirectories)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::DescribeDirectories,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::DescribeDirectoriesInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::DescribeDirectoriesInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.DescribeDirectories",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_describe_directories(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::DescribeDirectories::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"DescribeDirectories",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`DescribeDirectoriesInput`](crate::input::DescribeDirectoriesInput)
pub fn builder() -> crate::input::describe_directories_input::Builder {
crate::input::describe_directories_input::Builder::default()
}
}
/// See [`DescribeDomainControllersInput`](crate::input::DescribeDomainControllersInput)
pub mod describe_domain_controllers_input {
/// A builder for [`DescribeDomainControllersInput`](crate::input::DescribeDomainControllersInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) domain_controller_ids: std::option::Option<std::vec::Vec<std::string::String>>,
pub(crate) next_token: std::option::Option<std::string::String>,
pub(crate) limit: std::option::Option<i32>,
}
impl Builder {
/// <p>Identifier of the directory for which to retrieve the domain controller information.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>Identifier of the directory for which to retrieve the domain controller information.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// Appends an item to `domain_controller_ids`.
///
/// To override the contents of this collection use [`set_domain_controller_ids`](Self::set_domain_controller_ids).
///
/// <p>A list of identifiers for the domain controllers whose information will be provided.</p>
pub fn domain_controller_ids(mut self, input: impl Into<std::string::String>) -> Self {
let mut v = self.domain_controller_ids.unwrap_or_default();
v.push(input.into());
self.domain_controller_ids = Some(v);
self
}
/// <p>A list of identifiers for the domain controllers whose information will be provided.</p>
pub fn set_domain_controller_ids(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.domain_controller_ids = input;
self
}
/// <p>The <i>DescribeDomainControllers.NextToken</i> value from a previous call to <code>DescribeDomainControllers</code>. Pass null if this is the first call. </p>
pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self {
self.next_token = Some(input.into());
self
}
/// <p>The <i>DescribeDomainControllers.NextToken</i> value from a previous call to <code>DescribeDomainControllers</code>. Pass null if this is the first call. </p>
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.next_token = input;
self
}
/// <p>The maximum number of items to return.</p>
pub fn limit(mut self, input: i32) -> Self {
self.limit = Some(input);
self
}
/// <p>The maximum number of items to return.</p>
pub fn set_limit(mut self, input: std::option::Option<i32>) -> Self {
self.limit = input;
self
}
/// Consumes the builder and constructs a [`DescribeDomainControllersInput`](crate::input::DescribeDomainControllersInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::DescribeDomainControllersInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::DescribeDomainControllersInput {
directory_id: self.directory_id,
domain_controller_ids: self.domain_controller_ids,
next_token: self.next_token,
limit: self.limit,
})
}
}
}
#[doc(hidden)]
pub type DescribeDomainControllersInputOperationOutputAlias =
crate::operation::DescribeDomainControllers;
#[doc(hidden)]
pub type DescribeDomainControllersInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl DescribeDomainControllersInput {
/// Consumes the builder and constructs an Operation<[`DescribeDomainControllers`](crate::operation::DescribeDomainControllers)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::DescribeDomainControllers,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::DescribeDomainControllersInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::DescribeDomainControllersInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.DescribeDomainControllers",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_describe_domain_controllers(
&self,
)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::DescribeDomainControllers::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"DescribeDomainControllers",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`DescribeDomainControllersInput`](crate::input::DescribeDomainControllersInput)
pub fn builder() -> crate::input::describe_domain_controllers_input::Builder {
crate::input::describe_domain_controllers_input::Builder::default()
}
}
/// See [`DescribeEventTopicsInput`](crate::input::DescribeEventTopicsInput)
pub mod describe_event_topics_input {
/// A builder for [`DescribeEventTopicsInput`](crate::input::DescribeEventTopicsInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) topic_names: std::option::Option<std::vec::Vec<std::string::String>>,
}
impl Builder {
/// <p>The Directory ID for which to get the list of associated Amazon SNS topics. If this member is null, associations for all Directory IDs are returned.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The Directory ID for which to get the list of associated Amazon SNS topics. If this member is null, associations for all Directory IDs are returned.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// Appends an item to `topic_names`.
///
/// To override the contents of this collection use [`set_topic_names`](Self::set_topic_names).
///
/// <p>A list of Amazon SNS topic names for which to obtain the information. If this member is null, all associations for the specified Directory ID are returned.</p>
/// <p>An empty list results in an <code>InvalidParameterException</code> being thrown.</p>
pub fn topic_names(mut self, input: impl Into<std::string::String>) -> Self {
let mut v = self.topic_names.unwrap_or_default();
v.push(input.into());
self.topic_names = Some(v);
self
}
/// <p>A list of Amazon SNS topic names for which to obtain the information. If this member is null, all associations for the specified Directory ID are returned.</p>
/// <p>An empty list results in an <code>InvalidParameterException</code> being thrown.</p>
pub fn set_topic_names(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.topic_names = input;
self
}
/// Consumes the builder and constructs a [`DescribeEventTopicsInput`](crate::input::DescribeEventTopicsInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::DescribeEventTopicsInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::DescribeEventTopicsInput {
directory_id: self.directory_id,
topic_names: self.topic_names,
})
}
}
}
#[doc(hidden)]
pub type DescribeEventTopicsInputOperationOutputAlias = crate::operation::DescribeEventTopics;
#[doc(hidden)]
pub type DescribeEventTopicsInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl DescribeEventTopicsInput {
/// Consumes the builder and constructs an Operation<[`DescribeEventTopics`](crate::operation::DescribeEventTopics)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::DescribeEventTopics,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::DescribeEventTopicsInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::DescribeEventTopicsInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.DescribeEventTopics",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_describe_event_topics(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::DescribeEventTopics::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"DescribeEventTopics",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`DescribeEventTopicsInput`](crate::input::DescribeEventTopicsInput)
pub fn builder() -> crate::input::describe_event_topics_input::Builder {
crate::input::describe_event_topics_input::Builder::default()
}
}
/// See [`DescribeLdapsSettingsInput`](crate::input::DescribeLdapsSettingsInput)
pub mod describe_ldaps_settings_input {
/// A builder for [`DescribeLdapsSettingsInput`](crate::input::DescribeLdapsSettingsInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) r#type: std::option::Option<crate::model::LdapsType>,
pub(crate) next_token: std::option::Option<std::string::String>,
pub(crate) limit: std::option::Option<i32>,
}
impl Builder {
/// <p>The identifier of the directory.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The type of LDAP security to enable. Currently only the value <code>Client</code> is supported.</p>
pub fn r#type(mut self, input: crate::model::LdapsType) -> Self {
self.r#type = Some(input);
self
}
/// <p>The type of LDAP security to enable. Currently only the value <code>Client</code> is supported.</p>
pub fn set_type(mut self, input: std::option::Option<crate::model::LdapsType>) -> Self {
self.r#type = input;
self
}
/// <p>The type of next token used for pagination.</p>
pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self {
self.next_token = Some(input.into());
self
}
/// <p>The type of next token used for pagination.</p>
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.next_token = input;
self
}
/// <p>Specifies the number of items that should be displayed on one page.</p>
pub fn limit(mut self, input: i32) -> Self {
self.limit = Some(input);
self
}
/// <p>Specifies the number of items that should be displayed on one page.</p>
pub fn set_limit(mut self, input: std::option::Option<i32>) -> Self {
self.limit = input;
self
}
/// Consumes the builder and constructs a [`DescribeLdapsSettingsInput`](crate::input::DescribeLdapsSettingsInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::DescribeLdapsSettingsInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::DescribeLdapsSettingsInput {
directory_id: self.directory_id,
r#type: self.r#type,
next_token: self.next_token,
limit: self.limit,
})
}
}
}
#[doc(hidden)]
pub type DescribeLdapsSettingsInputOperationOutputAlias = crate::operation::DescribeLDAPSSettings;
#[doc(hidden)]
pub type DescribeLdapsSettingsInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl DescribeLdapsSettingsInput {
/// Consumes the builder and constructs an Operation<[`DescribeLDAPSSettings`](crate::operation::DescribeLDAPSSettings)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::DescribeLDAPSSettings,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::DescribeLdapsSettingsInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::DescribeLdapsSettingsInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.DescribeLDAPSSettings",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_describe_ldaps_settings(
&self,
)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::DescribeLDAPSSettings::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"DescribeLDAPSSettings",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`DescribeLdapsSettingsInput`](crate::input::DescribeLdapsSettingsInput)
pub fn builder() -> crate::input::describe_ldaps_settings_input::Builder {
crate::input::describe_ldaps_settings_input::Builder::default()
}
}
/// See [`DescribeRegionsInput`](crate::input::DescribeRegionsInput)
pub mod describe_regions_input {
/// A builder for [`DescribeRegionsInput`](crate::input::DescribeRegionsInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) region_name: std::option::Option<std::string::String>,
pub(crate) next_token: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The identifier of the directory.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The name of the Region. For example, <code>us-east-1</code>.</p>
pub fn region_name(mut self, input: impl Into<std::string::String>) -> Self {
self.region_name = Some(input.into());
self
}
/// <p>The name of the Region. For example, <code>us-east-1</code>.</p>
pub fn set_region_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.region_name = input;
self
}
/// <p>The <code>DescribeRegionsResult.NextToken</code> value from a previous call to <code>DescribeRegions</code>. Pass null if this is the first call.</p>
pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self {
self.next_token = Some(input.into());
self
}
/// <p>The <code>DescribeRegionsResult.NextToken</code> value from a previous call to <code>DescribeRegions</code>. Pass null if this is the first call.</p>
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.next_token = input;
self
}
/// Consumes the builder and constructs a [`DescribeRegionsInput`](crate::input::DescribeRegionsInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::DescribeRegionsInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::DescribeRegionsInput {
directory_id: self.directory_id,
region_name: self.region_name,
next_token: self.next_token,
})
}
}
}
#[doc(hidden)]
pub type DescribeRegionsInputOperationOutputAlias = crate::operation::DescribeRegions;
#[doc(hidden)]
pub type DescribeRegionsInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl DescribeRegionsInput {
/// Consumes the builder and constructs an Operation<[`DescribeRegions`](crate::operation::DescribeRegions)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::DescribeRegions,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::DescribeRegionsInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::DescribeRegionsInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.DescribeRegions",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_describe_regions(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::DescribeRegions::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"DescribeRegions",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`DescribeRegionsInput`](crate::input::DescribeRegionsInput)
pub fn builder() -> crate::input::describe_regions_input::Builder {
crate::input::describe_regions_input::Builder::default()
}
}
/// See [`DescribeSharedDirectoriesInput`](crate::input::DescribeSharedDirectoriesInput)
pub mod describe_shared_directories_input {
/// A builder for [`DescribeSharedDirectoriesInput`](crate::input::DescribeSharedDirectoriesInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) owner_directory_id: std::option::Option<std::string::String>,
pub(crate) shared_directory_ids: std::option::Option<std::vec::Vec<std::string::String>>,
pub(crate) next_token: std::option::Option<std::string::String>,
pub(crate) limit: std::option::Option<i32>,
}
impl Builder {
/// <p>Returns the identifier of the directory in the directory owner account. </p>
pub fn owner_directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.owner_directory_id = Some(input.into());
self
}
/// <p>Returns the identifier of the directory in the directory owner account. </p>
pub fn set_owner_directory_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.owner_directory_id = input;
self
}
/// Appends an item to `shared_directory_ids`.
///
/// To override the contents of this collection use [`set_shared_directory_ids`](Self::set_shared_directory_ids).
///
/// <p>A list of identifiers of all shared directories in your account. </p>
pub fn shared_directory_ids(mut self, input: impl Into<std::string::String>) -> Self {
let mut v = self.shared_directory_ids.unwrap_or_default();
v.push(input.into());
self.shared_directory_ids = Some(v);
self
}
/// <p>A list of identifiers of all shared directories in your account. </p>
pub fn set_shared_directory_ids(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.shared_directory_ids = input;
self
}
/// <p>The <code>DescribeSharedDirectoriesResult.NextToken</code> value from a previous call to <code>DescribeSharedDirectories</code>. Pass null if this is the first call. </p>
pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self {
self.next_token = Some(input.into());
self
}
/// <p>The <code>DescribeSharedDirectoriesResult.NextToken</code> value from a previous call to <code>DescribeSharedDirectories</code>. Pass null if this is the first call. </p>
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.next_token = input;
self
}
/// <p>The number of shared directories to return in the response object.</p>
pub fn limit(mut self, input: i32) -> Self {
self.limit = Some(input);
self
}
/// <p>The number of shared directories to return in the response object.</p>
pub fn set_limit(mut self, input: std::option::Option<i32>) -> Self {
self.limit = input;
self
}
/// Consumes the builder and constructs a [`DescribeSharedDirectoriesInput`](crate::input::DescribeSharedDirectoriesInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::DescribeSharedDirectoriesInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::DescribeSharedDirectoriesInput {
owner_directory_id: self.owner_directory_id,
shared_directory_ids: self.shared_directory_ids,
next_token: self.next_token,
limit: self.limit,
})
}
}
}
#[doc(hidden)]
pub type DescribeSharedDirectoriesInputOperationOutputAlias =
crate::operation::DescribeSharedDirectories;
#[doc(hidden)]
pub type DescribeSharedDirectoriesInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl DescribeSharedDirectoriesInput {
/// Consumes the builder and constructs an Operation<[`DescribeSharedDirectories`](crate::operation::DescribeSharedDirectories)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::DescribeSharedDirectories,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::DescribeSharedDirectoriesInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::DescribeSharedDirectoriesInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.DescribeSharedDirectories",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_describe_shared_directories(
&self,
)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::DescribeSharedDirectories::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"DescribeSharedDirectories",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`DescribeSharedDirectoriesInput`](crate::input::DescribeSharedDirectoriesInput)
pub fn builder() -> crate::input::describe_shared_directories_input::Builder {
crate::input::describe_shared_directories_input::Builder::default()
}
}
/// See [`DescribeSnapshotsInput`](crate::input::DescribeSnapshotsInput)
pub mod describe_snapshots_input {
/// A builder for [`DescribeSnapshotsInput`](crate::input::DescribeSnapshotsInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) snapshot_ids: std::option::Option<std::vec::Vec<std::string::String>>,
pub(crate) next_token: std::option::Option<std::string::String>,
pub(crate) limit: std::option::Option<i32>,
}
impl Builder {
/// <p>The identifier of the directory for which to retrieve snapshot information.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory for which to retrieve snapshot information.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// Appends an item to `snapshot_ids`.
///
/// To override the contents of this collection use [`set_snapshot_ids`](Self::set_snapshot_ids).
///
/// <p>A list of identifiers of the snapshots to obtain the information for. If this member is null or empty, all snapshots are returned using the <i>Limit</i> and <i>NextToken</i> members.</p>
pub fn snapshot_ids(mut self, input: impl Into<std::string::String>) -> Self {
let mut v = self.snapshot_ids.unwrap_or_default();
v.push(input.into());
self.snapshot_ids = Some(v);
self
}
/// <p>A list of identifiers of the snapshots to obtain the information for. If this member is null or empty, all snapshots are returned using the <i>Limit</i> and <i>NextToken</i> members.</p>
pub fn set_snapshot_ids(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.snapshot_ids = input;
self
}
/// <p>The <i>DescribeSnapshotsResult.NextToken</i> value from a previous call to <code>DescribeSnapshots</code>. Pass null if this is the first call.</p>
pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self {
self.next_token = Some(input.into());
self
}
/// <p>The <i>DescribeSnapshotsResult.NextToken</i> value from a previous call to <code>DescribeSnapshots</code>. Pass null if this is the first call.</p>
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.next_token = input;
self
}
/// <p>The maximum number of objects to return.</p>
pub fn limit(mut self, input: i32) -> Self {
self.limit = Some(input);
self
}
/// <p>The maximum number of objects to return.</p>
pub fn set_limit(mut self, input: std::option::Option<i32>) -> Self {
self.limit = input;
self
}
/// Consumes the builder and constructs a [`DescribeSnapshotsInput`](crate::input::DescribeSnapshotsInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::DescribeSnapshotsInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::DescribeSnapshotsInput {
directory_id: self.directory_id,
snapshot_ids: self.snapshot_ids,
next_token: self.next_token,
limit: self.limit,
})
}
}
}
#[doc(hidden)]
pub type DescribeSnapshotsInputOperationOutputAlias = crate::operation::DescribeSnapshots;
#[doc(hidden)]
pub type DescribeSnapshotsInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl DescribeSnapshotsInput {
/// Consumes the builder and constructs an Operation<[`DescribeSnapshots`](crate::operation::DescribeSnapshots)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::DescribeSnapshots,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::DescribeSnapshotsInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::DescribeSnapshotsInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.DescribeSnapshots",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_describe_snapshots(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::DescribeSnapshots::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"DescribeSnapshots",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`DescribeSnapshotsInput`](crate::input::DescribeSnapshotsInput)
pub fn builder() -> crate::input::describe_snapshots_input::Builder {
crate::input::describe_snapshots_input::Builder::default()
}
}
/// See [`DescribeTrustsInput`](crate::input::DescribeTrustsInput)
pub mod describe_trusts_input {
/// A builder for [`DescribeTrustsInput`](crate::input::DescribeTrustsInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) trust_ids: std::option::Option<std::vec::Vec<std::string::String>>,
pub(crate) next_token: std::option::Option<std::string::String>,
pub(crate) limit: std::option::Option<i32>,
}
impl Builder {
/// <p>The Directory ID of the Amazon Web Services directory that is a part of the requested trust relationship.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The Directory ID of the Amazon Web Services directory that is a part of the requested trust relationship.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// Appends an item to `trust_ids`.
///
/// To override the contents of this collection use [`set_trust_ids`](Self::set_trust_ids).
///
/// <p>A list of identifiers of the trust relationships for which to obtain the information. If this member is null, all trust relationships that belong to the current account are returned.</p>
/// <p>An empty list results in an <code>InvalidParameterException</code> being thrown.</p>
pub fn trust_ids(mut self, input: impl Into<std::string::String>) -> Self {
let mut v = self.trust_ids.unwrap_or_default();
v.push(input.into());
self.trust_ids = Some(v);
self
}
/// <p>A list of identifiers of the trust relationships for which to obtain the information. If this member is null, all trust relationships that belong to the current account are returned.</p>
/// <p>An empty list results in an <code>InvalidParameterException</code> being thrown.</p>
pub fn set_trust_ids(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.trust_ids = input;
self
}
/// <p>The <i>DescribeTrustsResult.NextToken</i> value from a previous call to <code>DescribeTrusts</code>. Pass null if this is the first call.</p>
pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self {
self.next_token = Some(input.into());
self
}
/// <p>The <i>DescribeTrustsResult.NextToken</i> value from a previous call to <code>DescribeTrusts</code>. Pass null if this is the first call.</p>
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.next_token = input;
self
}
/// <p>The maximum number of objects to return.</p>
pub fn limit(mut self, input: i32) -> Self {
self.limit = Some(input);
self
}
/// <p>The maximum number of objects to return.</p>
pub fn set_limit(mut self, input: std::option::Option<i32>) -> Self {
self.limit = input;
self
}
/// Consumes the builder and constructs a [`DescribeTrustsInput`](crate::input::DescribeTrustsInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::DescribeTrustsInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::DescribeTrustsInput {
directory_id: self.directory_id,
trust_ids: self.trust_ids,
next_token: self.next_token,
limit: self.limit,
})
}
}
}
#[doc(hidden)]
pub type DescribeTrustsInputOperationOutputAlias = crate::operation::DescribeTrusts;
#[doc(hidden)]
pub type DescribeTrustsInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl DescribeTrustsInput {
/// Consumes the builder and constructs an Operation<[`DescribeTrusts`](crate::operation::DescribeTrusts)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::DescribeTrusts,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::DescribeTrustsInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::DescribeTrustsInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.DescribeTrusts",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_describe_trusts(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::DescribeTrusts::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"DescribeTrusts",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`DescribeTrustsInput`](crate::input::DescribeTrustsInput)
pub fn builder() -> crate::input::describe_trusts_input::Builder {
crate::input::describe_trusts_input::Builder::default()
}
}
/// See [`DisableClientAuthenticationInput`](crate::input::DisableClientAuthenticationInput)
pub mod disable_client_authentication_input {
/// A builder for [`DisableClientAuthenticationInput`](crate::input::DisableClientAuthenticationInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) r#type: std::option::Option<crate::model::ClientAuthenticationType>,
}
impl Builder {
/// <p>The identifier of the directory </p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory </p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The type of client authentication to disable. Currently, only the parameter, <code>SmartCard</code> is supported.</p>
pub fn r#type(mut self, input: crate::model::ClientAuthenticationType) -> Self {
self.r#type = Some(input);
self
}
/// <p>The type of client authentication to disable. Currently, only the parameter, <code>SmartCard</code> is supported.</p>
pub fn set_type(
mut self,
input: std::option::Option<crate::model::ClientAuthenticationType>,
) -> Self {
self.r#type = input;
self
}
/// Consumes the builder and constructs a [`DisableClientAuthenticationInput`](crate::input::DisableClientAuthenticationInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::DisableClientAuthenticationInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::DisableClientAuthenticationInput {
directory_id: self.directory_id,
r#type: self.r#type,
})
}
}
}
#[doc(hidden)]
pub type DisableClientAuthenticationInputOperationOutputAlias =
crate::operation::DisableClientAuthentication;
#[doc(hidden)]
pub type DisableClientAuthenticationInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl DisableClientAuthenticationInput {
/// Consumes the builder and constructs an Operation<[`DisableClientAuthentication`](crate::operation::DisableClientAuthentication)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::DisableClientAuthentication,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::DisableClientAuthenticationInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::DisableClientAuthenticationInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.DisableClientAuthentication",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_disable_client_authentication(&self)?
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::DisableClientAuthentication::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"DisableClientAuthentication",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`DisableClientAuthenticationInput`](crate::input::DisableClientAuthenticationInput)
pub fn builder() -> crate::input::disable_client_authentication_input::Builder {
crate::input::disable_client_authentication_input::Builder::default()
}
}
/// See [`DisableLdapsInput`](crate::input::DisableLdapsInput)
pub mod disable_ldaps_input {
/// A builder for [`DisableLdapsInput`](crate::input::DisableLdapsInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) r#type: std::option::Option<crate::model::LdapsType>,
}
impl Builder {
/// <p>The identifier of the directory.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The type of LDAP security to enable. Currently only the value <code>Client</code> is supported.</p>
pub fn r#type(mut self, input: crate::model::LdapsType) -> Self {
self.r#type = Some(input);
self
}
/// <p>The type of LDAP security to enable. Currently only the value <code>Client</code> is supported.</p>
pub fn set_type(mut self, input: std::option::Option<crate::model::LdapsType>) -> Self {
self.r#type = input;
self
}
/// Consumes the builder and constructs a [`DisableLdapsInput`](crate::input::DisableLdapsInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::DisableLdapsInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::DisableLdapsInput {
directory_id: self.directory_id,
r#type: self.r#type,
})
}
}
}
#[doc(hidden)]
pub type DisableLdapsInputOperationOutputAlias = crate::operation::DisableLDAPS;
#[doc(hidden)]
pub type DisableLdapsInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl DisableLdapsInput {
/// Consumes the builder and constructs an Operation<[`DisableLDAPS`](crate::operation::DisableLDAPS)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::DisableLDAPS,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::DisableLdapsInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::DisableLdapsInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.DisableLDAPS",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_disable_ldaps(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::DisableLDAPS::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"DisableLDAPS",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`DisableLdapsInput`](crate::input::DisableLdapsInput)
pub fn builder() -> crate::input::disable_ldaps_input::Builder {
crate::input::disable_ldaps_input::Builder::default()
}
}
/// See [`DisableRadiusInput`](crate::input::DisableRadiusInput)
pub mod disable_radius_input {
/// A builder for [`DisableRadiusInput`](crate::input::DisableRadiusInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The identifier of the directory for which to disable MFA.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory for which to disable MFA.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// Consumes the builder and constructs a [`DisableRadiusInput`](crate::input::DisableRadiusInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::DisableRadiusInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::DisableRadiusInput {
directory_id: self.directory_id,
})
}
}
}
#[doc(hidden)]
pub type DisableRadiusInputOperationOutputAlias = crate::operation::DisableRadius;
#[doc(hidden)]
pub type DisableRadiusInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl DisableRadiusInput {
/// Consumes the builder and constructs an Operation<[`DisableRadius`](crate::operation::DisableRadius)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::DisableRadius,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::DisableRadiusInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::DisableRadiusInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.DisableRadius",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_disable_radius(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::DisableRadius::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"DisableRadius",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`DisableRadiusInput`](crate::input::DisableRadiusInput)
pub fn builder() -> crate::input::disable_radius_input::Builder {
crate::input::disable_radius_input::Builder::default()
}
}
/// See [`DisableSsoInput`](crate::input::DisableSsoInput)
pub mod disable_sso_input {
/// A builder for [`DisableSsoInput`](crate::input::DisableSsoInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) user_name: std::option::Option<std::string::String>,
pub(crate) password: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The identifier of the directory for which to disable single-sign on.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory for which to disable single-sign on.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The username of an alternate account to use to disable single-sign on. This is only used for AD Connector directories. This account must have privileges to remove a service principal name.</p>
/// <p>If the AD Connector service account does not have privileges to remove a service principal name, you can specify an alternate account with the <i>UserName</i> and <i>Password</i> parameters. These credentials are only used to disable single sign-on and are not stored by the service. The AD Connector service account is not changed.</p>
pub fn user_name(mut self, input: impl Into<std::string::String>) -> Self {
self.user_name = Some(input.into());
self
}
/// <p>The username of an alternate account to use to disable single-sign on. This is only used for AD Connector directories. This account must have privileges to remove a service principal name.</p>
/// <p>If the AD Connector service account does not have privileges to remove a service principal name, you can specify an alternate account with the <i>UserName</i> and <i>Password</i> parameters. These credentials are only used to disable single sign-on and are not stored by the service. The AD Connector service account is not changed.</p>
pub fn set_user_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.user_name = input;
self
}
/// <p>The password of an alternate account to use to disable single-sign on. This is only used for AD Connector directories. For more information, see the <i>UserName</i> parameter.</p>
pub fn password(mut self, input: impl Into<std::string::String>) -> Self {
self.password = Some(input.into());
self
}
/// <p>The password of an alternate account to use to disable single-sign on. This is only used for AD Connector directories. For more information, see the <i>UserName</i> parameter.</p>
pub fn set_password(mut self, input: std::option::Option<std::string::String>) -> Self {
self.password = input;
self
}
/// Consumes the builder and constructs a [`DisableSsoInput`](crate::input::DisableSsoInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::DisableSsoInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::DisableSsoInput {
directory_id: self.directory_id,
user_name: self.user_name,
password: self.password,
})
}
}
}
#[doc(hidden)]
pub type DisableSsoInputOperationOutputAlias = crate::operation::DisableSso;
#[doc(hidden)]
pub type DisableSsoInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl DisableSsoInput {
/// Consumes the builder and constructs an Operation<[`DisableSso`](crate::operation::DisableSso)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::DisableSso,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::DisableSsoInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::DisableSsoInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.DisableSso",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_disable_sso(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::DisableSso::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"DisableSso",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`DisableSsoInput`](crate::input::DisableSsoInput)
pub fn builder() -> crate::input::disable_sso_input::Builder {
crate::input::disable_sso_input::Builder::default()
}
}
/// See [`EnableClientAuthenticationInput`](crate::input::EnableClientAuthenticationInput)
pub mod enable_client_authentication_input {
/// A builder for [`EnableClientAuthenticationInput`](crate::input::EnableClientAuthenticationInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) r#type: std::option::Option<crate::model::ClientAuthenticationType>,
}
impl Builder {
/// <p>The identifier of the specified directory. </p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the specified directory. </p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The type of client authentication to enable. Currently only the value <code>SmartCard</code> is supported. Smart card authentication in AD Connector requires that you enable Kerberos Constrained Delegation for the Service User to the LDAP service in your self-managed AD. </p>
pub fn r#type(mut self, input: crate::model::ClientAuthenticationType) -> Self {
self.r#type = Some(input);
self
}
/// <p>The type of client authentication to enable. Currently only the value <code>SmartCard</code> is supported. Smart card authentication in AD Connector requires that you enable Kerberos Constrained Delegation for the Service User to the LDAP service in your self-managed AD. </p>
pub fn set_type(
mut self,
input: std::option::Option<crate::model::ClientAuthenticationType>,
) -> Self {
self.r#type = input;
self
}
/// Consumes the builder and constructs a [`EnableClientAuthenticationInput`](crate::input::EnableClientAuthenticationInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::EnableClientAuthenticationInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::EnableClientAuthenticationInput {
directory_id: self.directory_id,
r#type: self.r#type,
})
}
}
}
#[doc(hidden)]
pub type EnableClientAuthenticationInputOperationOutputAlias =
crate::operation::EnableClientAuthentication;
#[doc(hidden)]
pub type EnableClientAuthenticationInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl EnableClientAuthenticationInput {
/// Consumes the builder and constructs an Operation<[`EnableClientAuthentication`](crate::operation::EnableClientAuthentication)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::EnableClientAuthentication,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::EnableClientAuthenticationInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::EnableClientAuthenticationInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.EnableClientAuthentication",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_enable_client_authentication(
&self,
)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::EnableClientAuthentication::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"EnableClientAuthentication",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`EnableClientAuthenticationInput`](crate::input::EnableClientAuthenticationInput)
pub fn builder() -> crate::input::enable_client_authentication_input::Builder {
crate::input::enable_client_authentication_input::Builder::default()
}
}
/// See [`EnableLdapsInput`](crate::input::EnableLdapsInput)
pub mod enable_ldaps_input {
/// A builder for [`EnableLdapsInput`](crate::input::EnableLdapsInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) r#type: std::option::Option<crate::model::LdapsType>,
}
impl Builder {
/// <p>The identifier of the directory.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The type of LDAP security to enable. Currently only the value <code>Client</code> is supported.</p>
pub fn r#type(mut self, input: crate::model::LdapsType) -> Self {
self.r#type = Some(input);
self
}
/// <p>The type of LDAP security to enable. Currently only the value <code>Client</code> is supported.</p>
pub fn set_type(mut self, input: std::option::Option<crate::model::LdapsType>) -> Self {
self.r#type = input;
self
}
/// Consumes the builder and constructs a [`EnableLdapsInput`](crate::input::EnableLdapsInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::EnableLdapsInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::EnableLdapsInput {
directory_id: self.directory_id,
r#type: self.r#type,
})
}
}
}
#[doc(hidden)]
pub type EnableLdapsInputOperationOutputAlias = crate::operation::EnableLDAPS;
#[doc(hidden)]
pub type EnableLdapsInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl EnableLdapsInput {
/// Consumes the builder and constructs an Operation<[`EnableLDAPS`](crate::operation::EnableLDAPS)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::EnableLDAPS,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::EnableLdapsInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::EnableLdapsInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.EnableLDAPS",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_enable_ldaps(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::EnableLDAPS::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"EnableLDAPS",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`EnableLdapsInput`](crate::input::EnableLdapsInput)
pub fn builder() -> crate::input::enable_ldaps_input::Builder {
crate::input::enable_ldaps_input::Builder::default()
}
}
/// See [`EnableRadiusInput`](crate::input::EnableRadiusInput)
pub mod enable_radius_input {
/// A builder for [`EnableRadiusInput`](crate::input::EnableRadiusInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) radius_settings: std::option::Option<crate::model::RadiusSettings>,
}
impl Builder {
/// <p>The identifier of the directory for which to enable MFA.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory for which to enable MFA.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>A <code>RadiusSettings</code> object that contains information about the RADIUS server.</p>
pub fn radius_settings(mut self, input: crate::model::RadiusSettings) -> Self {
self.radius_settings = Some(input);
self
}
/// <p>A <code>RadiusSettings</code> object that contains information about the RADIUS server.</p>
pub fn set_radius_settings(
mut self,
input: std::option::Option<crate::model::RadiusSettings>,
) -> Self {
self.radius_settings = input;
self
}
/// Consumes the builder and constructs a [`EnableRadiusInput`](crate::input::EnableRadiusInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::EnableRadiusInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::EnableRadiusInput {
directory_id: self.directory_id,
radius_settings: self.radius_settings,
})
}
}
}
#[doc(hidden)]
pub type EnableRadiusInputOperationOutputAlias = crate::operation::EnableRadius;
#[doc(hidden)]
pub type EnableRadiusInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl EnableRadiusInput {
/// Consumes the builder and constructs an Operation<[`EnableRadius`](crate::operation::EnableRadius)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::EnableRadius,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::EnableRadiusInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::EnableRadiusInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.EnableRadius",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_enable_radius(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::EnableRadius::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"EnableRadius",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`EnableRadiusInput`](crate::input::EnableRadiusInput)
pub fn builder() -> crate::input::enable_radius_input::Builder {
crate::input::enable_radius_input::Builder::default()
}
}
/// See [`EnableSsoInput`](crate::input::EnableSsoInput)
pub mod enable_sso_input {
/// A builder for [`EnableSsoInput`](crate::input::EnableSsoInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) user_name: std::option::Option<std::string::String>,
pub(crate) password: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The identifier of the directory for which to enable single-sign on.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory for which to enable single-sign on.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The username of an alternate account to use to enable single-sign on. This is only used for AD Connector directories. This account must have privileges to add a service principal name.</p>
/// <p>If the AD Connector service account does not have privileges to add a service principal name, you can specify an alternate account with the <i>UserName</i> and <i>Password</i> parameters. These credentials are only used to enable single sign-on and are not stored by the service. The AD Connector service account is not changed.</p>
pub fn user_name(mut self, input: impl Into<std::string::String>) -> Self {
self.user_name = Some(input.into());
self
}
/// <p>The username of an alternate account to use to enable single-sign on. This is only used for AD Connector directories. This account must have privileges to add a service principal name.</p>
/// <p>If the AD Connector service account does not have privileges to add a service principal name, you can specify an alternate account with the <i>UserName</i> and <i>Password</i> parameters. These credentials are only used to enable single sign-on and are not stored by the service. The AD Connector service account is not changed.</p>
pub fn set_user_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.user_name = input;
self
}
/// <p>The password of an alternate account to use to enable single-sign on. This is only used for AD Connector directories. For more information, see the <i>UserName</i> parameter.</p>
pub fn password(mut self, input: impl Into<std::string::String>) -> Self {
self.password = Some(input.into());
self
}
/// <p>The password of an alternate account to use to enable single-sign on. This is only used for AD Connector directories. For more information, see the <i>UserName</i> parameter.</p>
pub fn set_password(mut self, input: std::option::Option<std::string::String>) -> Self {
self.password = input;
self
}
/// Consumes the builder and constructs a [`EnableSsoInput`](crate::input::EnableSsoInput)
pub fn build(
self,
) -> std::result::Result<crate::input::EnableSsoInput, aws_smithy_http::operation::BuildError>
{
Ok(crate::input::EnableSsoInput {
directory_id: self.directory_id,
user_name: self.user_name,
password: self.password,
})
}
}
}
#[doc(hidden)]
pub type EnableSsoInputOperationOutputAlias = crate::operation::EnableSso;
#[doc(hidden)]
pub type EnableSsoInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl EnableSsoInput {
/// Consumes the builder and constructs an Operation<[`EnableSso`](crate::operation::EnableSso)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::EnableSso,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::EnableSsoInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::EnableSsoInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.EnableSso",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_enable_sso(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op =
aws_smithy_http::operation::Operation::new(request, crate::operation::EnableSso::new())
.with_metadata(aws_smithy_http::operation::Metadata::new(
"EnableSso",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`EnableSsoInput`](crate::input::EnableSsoInput)
pub fn builder() -> crate::input::enable_sso_input::Builder {
crate::input::enable_sso_input::Builder::default()
}
}
/// See [`GetDirectoryLimitsInput`](crate::input::GetDirectoryLimitsInput)
pub mod get_directory_limits_input {
/// A builder for [`GetDirectoryLimitsInput`](crate::input::GetDirectoryLimitsInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {}
impl Builder {
/// Consumes the builder and constructs a [`GetDirectoryLimitsInput`](crate::input::GetDirectoryLimitsInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::GetDirectoryLimitsInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::GetDirectoryLimitsInput {})
}
}
}
#[doc(hidden)]
pub type GetDirectoryLimitsInputOperationOutputAlias = crate::operation::GetDirectoryLimits;
#[doc(hidden)]
pub type GetDirectoryLimitsInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl GetDirectoryLimitsInput {
/// Consumes the builder and constructs an Operation<[`GetDirectoryLimits`](crate::operation::GetDirectoryLimits)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::GetDirectoryLimits,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::GetDirectoryLimitsInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::GetDirectoryLimitsInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.GetDirectoryLimits",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_get_directory_limits(&self)?,
);
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::GetDirectoryLimits::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"GetDirectoryLimits",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`GetDirectoryLimitsInput`](crate::input::GetDirectoryLimitsInput)
pub fn builder() -> crate::input::get_directory_limits_input::Builder {
crate::input::get_directory_limits_input::Builder::default()
}
}
/// See [`GetSnapshotLimitsInput`](crate::input::GetSnapshotLimitsInput)
pub mod get_snapshot_limits_input {
/// A builder for [`GetSnapshotLimitsInput`](crate::input::GetSnapshotLimitsInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>Contains the identifier of the directory to obtain the limits for.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>Contains the identifier of the directory to obtain the limits for.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// Consumes the builder and constructs a [`GetSnapshotLimitsInput`](crate::input::GetSnapshotLimitsInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::GetSnapshotLimitsInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::GetSnapshotLimitsInput {
directory_id: self.directory_id,
})
}
}
}
#[doc(hidden)]
pub type GetSnapshotLimitsInputOperationOutputAlias = crate::operation::GetSnapshotLimits;
#[doc(hidden)]
pub type GetSnapshotLimitsInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl GetSnapshotLimitsInput {
/// Consumes the builder and constructs an Operation<[`GetSnapshotLimits`](crate::operation::GetSnapshotLimits)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::GetSnapshotLimits,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::GetSnapshotLimitsInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::GetSnapshotLimitsInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.GetSnapshotLimits",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_get_snapshot_limits(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::GetSnapshotLimits::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"GetSnapshotLimits",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`GetSnapshotLimitsInput`](crate::input::GetSnapshotLimitsInput)
pub fn builder() -> crate::input::get_snapshot_limits_input::Builder {
crate::input::get_snapshot_limits_input::Builder::default()
}
}
/// See [`ListCertificatesInput`](crate::input::ListCertificatesInput)
pub mod list_certificates_input {
/// A builder for [`ListCertificatesInput`](crate::input::ListCertificatesInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) next_token: std::option::Option<std::string::String>,
pub(crate) limit: std::option::Option<i32>,
}
impl Builder {
/// <p>The identifier of the directory.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>A token for requesting another page of certificates if the <code>NextToken</code> response element indicates that more certificates are available. Use the value of the returned <code>NextToken</code> element in your request until the token comes back as <code>null</code>. Pass <code>null</code> if this is the first call.</p>
pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self {
self.next_token = Some(input.into());
self
}
/// <p>A token for requesting another page of certificates if the <code>NextToken</code> response element indicates that more certificates are available. Use the value of the returned <code>NextToken</code> element in your request until the token comes back as <code>null</code>. Pass <code>null</code> if this is the first call.</p>
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.next_token = input;
self
}
/// <p>The number of items that should show up on one page</p>
pub fn limit(mut self, input: i32) -> Self {
self.limit = Some(input);
self
}
/// <p>The number of items that should show up on one page</p>
pub fn set_limit(mut self, input: std::option::Option<i32>) -> Self {
self.limit = input;
self
}
/// Consumes the builder and constructs a [`ListCertificatesInput`](crate::input::ListCertificatesInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::ListCertificatesInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::ListCertificatesInput {
directory_id: self.directory_id,
next_token: self.next_token,
limit: self.limit,
})
}
}
}
#[doc(hidden)]
pub type ListCertificatesInputOperationOutputAlias = crate::operation::ListCertificates;
#[doc(hidden)]
pub type ListCertificatesInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl ListCertificatesInput {
/// Consumes the builder and constructs an Operation<[`ListCertificates`](crate::operation::ListCertificates)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::ListCertificates,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::ListCertificatesInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::ListCertificatesInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.ListCertificates",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_list_certificates(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::ListCertificates::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"ListCertificates",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`ListCertificatesInput`](crate::input::ListCertificatesInput)
pub fn builder() -> crate::input::list_certificates_input::Builder {
crate::input::list_certificates_input::Builder::default()
}
}
/// See [`ListIpRoutesInput`](crate::input::ListIpRoutesInput)
pub mod list_ip_routes_input {
/// A builder for [`ListIpRoutesInput`](crate::input::ListIpRoutesInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) next_token: std::option::Option<std::string::String>,
pub(crate) limit: std::option::Option<i32>,
}
impl Builder {
/// <p>Identifier (ID) of the directory for which you want to retrieve the IP addresses.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>Identifier (ID) of the directory for which you want to retrieve the IP addresses.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The <i>ListIpRoutes.NextToken</i> value from a previous call to <code>ListIpRoutes</code>. Pass null if this is the first call.</p>
pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self {
self.next_token = Some(input.into());
self
}
/// <p>The <i>ListIpRoutes.NextToken</i> value from a previous call to <code>ListIpRoutes</code>. Pass null if this is the first call.</p>
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.next_token = input;
self
}
/// <p>Maximum number of items to return. If this value is zero, the maximum number of items is specified by the limitations of the operation.</p>
pub fn limit(mut self, input: i32) -> Self {
self.limit = Some(input);
self
}
/// <p>Maximum number of items to return. If this value is zero, the maximum number of items is specified by the limitations of the operation.</p>
pub fn set_limit(mut self, input: std::option::Option<i32>) -> Self {
self.limit = input;
self
}
/// Consumes the builder and constructs a [`ListIpRoutesInput`](crate::input::ListIpRoutesInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::ListIpRoutesInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::ListIpRoutesInput {
directory_id: self.directory_id,
next_token: self.next_token,
limit: self.limit,
})
}
}
}
#[doc(hidden)]
pub type ListIpRoutesInputOperationOutputAlias = crate::operation::ListIpRoutes;
#[doc(hidden)]
pub type ListIpRoutesInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl ListIpRoutesInput {
/// Consumes the builder and constructs an Operation<[`ListIpRoutes`](crate::operation::ListIpRoutes)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::ListIpRoutes,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::ListIpRoutesInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::ListIpRoutesInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.ListIpRoutes",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_list_ip_routes(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::ListIpRoutes::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"ListIpRoutes",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`ListIpRoutesInput`](crate::input::ListIpRoutesInput)
pub fn builder() -> crate::input::list_ip_routes_input::Builder {
crate::input::list_ip_routes_input::Builder::default()
}
}
/// See [`ListLogSubscriptionsInput`](crate::input::ListLogSubscriptionsInput)
pub mod list_log_subscriptions_input {
/// A builder for [`ListLogSubscriptionsInput`](crate::input::ListLogSubscriptionsInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) next_token: std::option::Option<std::string::String>,
pub(crate) limit: std::option::Option<i32>,
}
impl Builder {
/// <p>If a <i>DirectoryID</i> is provided, lists only the log subscription associated with that directory. If no <i>DirectoryId</i> is provided, lists all log subscriptions associated with your Amazon Web Services account. If there are no log subscriptions for the Amazon Web Services account or the directory, an empty list will be returned.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>If a <i>DirectoryID</i> is provided, lists only the log subscription associated with that directory. If no <i>DirectoryId</i> is provided, lists all log subscriptions associated with your Amazon Web Services account. If there are no log subscriptions for the Amazon Web Services account or the directory, an empty list will be returned.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The token for the next set of items to return.</p>
pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self {
self.next_token = Some(input.into());
self
}
/// <p>The token for the next set of items to return.</p>
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.next_token = input;
self
}
/// <p>The maximum number of items returned.</p>
pub fn limit(mut self, input: i32) -> Self {
self.limit = Some(input);
self
}
/// <p>The maximum number of items returned.</p>
pub fn set_limit(mut self, input: std::option::Option<i32>) -> Self {
self.limit = input;
self
}
/// Consumes the builder and constructs a [`ListLogSubscriptionsInput`](crate::input::ListLogSubscriptionsInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::ListLogSubscriptionsInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::ListLogSubscriptionsInput {
directory_id: self.directory_id,
next_token: self.next_token,
limit: self.limit,
})
}
}
}
#[doc(hidden)]
pub type ListLogSubscriptionsInputOperationOutputAlias = crate::operation::ListLogSubscriptions;
#[doc(hidden)]
pub type ListLogSubscriptionsInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl ListLogSubscriptionsInput {
/// Consumes the builder and constructs an Operation<[`ListLogSubscriptions`](crate::operation::ListLogSubscriptions)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::ListLogSubscriptions,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::ListLogSubscriptionsInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::ListLogSubscriptionsInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.ListLogSubscriptions",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_list_log_subscriptions(
&self,
)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::ListLogSubscriptions::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"ListLogSubscriptions",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`ListLogSubscriptionsInput`](crate::input::ListLogSubscriptionsInput)
pub fn builder() -> crate::input::list_log_subscriptions_input::Builder {
crate::input::list_log_subscriptions_input::Builder::default()
}
}
/// See [`ListSchemaExtensionsInput`](crate::input::ListSchemaExtensionsInput)
pub mod list_schema_extensions_input {
/// A builder for [`ListSchemaExtensionsInput`](crate::input::ListSchemaExtensionsInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) next_token: std::option::Option<std::string::String>,
pub(crate) limit: std::option::Option<i32>,
}
impl Builder {
/// <p>The identifier of the directory from which to retrieve the schema extension information.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory from which to retrieve the schema extension information.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The <code>ListSchemaExtensions.NextToken</code> value from a previous call to <code>ListSchemaExtensions</code>. Pass null if this is the first call.</p>
pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self {
self.next_token = Some(input.into());
self
}
/// <p>The <code>ListSchemaExtensions.NextToken</code> value from a previous call to <code>ListSchemaExtensions</code>. Pass null if this is the first call.</p>
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.next_token = input;
self
}
/// <p>The maximum number of items to return.</p>
pub fn limit(mut self, input: i32) -> Self {
self.limit = Some(input);
self
}
/// <p>The maximum number of items to return.</p>
pub fn set_limit(mut self, input: std::option::Option<i32>) -> Self {
self.limit = input;
self
}
/// Consumes the builder and constructs a [`ListSchemaExtensionsInput`](crate::input::ListSchemaExtensionsInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::ListSchemaExtensionsInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::ListSchemaExtensionsInput {
directory_id: self.directory_id,
next_token: self.next_token,
limit: self.limit,
})
}
}
}
#[doc(hidden)]
pub type ListSchemaExtensionsInputOperationOutputAlias = crate::operation::ListSchemaExtensions;
#[doc(hidden)]
pub type ListSchemaExtensionsInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl ListSchemaExtensionsInput {
/// Consumes the builder and constructs an Operation<[`ListSchemaExtensions`](crate::operation::ListSchemaExtensions)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::ListSchemaExtensions,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::ListSchemaExtensionsInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::ListSchemaExtensionsInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.ListSchemaExtensions",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_list_schema_extensions(
&self,
)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::ListSchemaExtensions::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"ListSchemaExtensions",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`ListSchemaExtensionsInput`](crate::input::ListSchemaExtensionsInput)
pub fn builder() -> crate::input::list_schema_extensions_input::Builder {
crate::input::list_schema_extensions_input::Builder::default()
}
}
/// See [`ListTagsForResourceInput`](crate::input::ListTagsForResourceInput)
pub mod list_tags_for_resource_input {
/// A builder for [`ListTagsForResourceInput`](crate::input::ListTagsForResourceInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) resource_id: std::option::Option<std::string::String>,
pub(crate) next_token: std::option::Option<std::string::String>,
pub(crate) limit: std::option::Option<i32>,
}
impl Builder {
/// <p>Identifier (ID) of the directory for which you want to retrieve tags.</p>
pub fn resource_id(mut self, input: impl Into<std::string::String>) -> Self {
self.resource_id = Some(input.into());
self
}
/// <p>Identifier (ID) of the directory for which you want to retrieve tags.</p>
pub fn set_resource_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.resource_id = input;
self
}
/// <p>Reserved for future use.</p>
pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self {
self.next_token = Some(input.into());
self
}
/// <p>Reserved for future use.</p>
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.next_token = input;
self
}
/// <p>Reserved for future use.</p>
pub fn limit(mut self, input: i32) -> Self {
self.limit = Some(input);
self
}
/// <p>Reserved for future use.</p>
pub fn set_limit(mut self, input: std::option::Option<i32>) -> Self {
self.limit = input;
self
}
/// Consumes the builder and constructs a [`ListTagsForResourceInput`](crate::input::ListTagsForResourceInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::ListTagsForResourceInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::ListTagsForResourceInput {
resource_id: self.resource_id,
next_token: self.next_token,
limit: self.limit,
})
}
}
}
#[doc(hidden)]
pub type ListTagsForResourceInputOperationOutputAlias = crate::operation::ListTagsForResource;
#[doc(hidden)]
pub type ListTagsForResourceInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl ListTagsForResourceInput {
/// Consumes the builder and constructs an Operation<[`ListTagsForResource`](crate::operation::ListTagsForResource)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::ListTagsForResource,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::ListTagsForResourceInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::ListTagsForResourceInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.ListTagsForResource",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_list_tags_for_resource(
&self,
)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::ListTagsForResource::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"ListTagsForResource",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`ListTagsForResourceInput`](crate::input::ListTagsForResourceInput)
pub fn builder() -> crate::input::list_tags_for_resource_input::Builder {
crate::input::list_tags_for_resource_input::Builder::default()
}
}
/// See [`RegisterCertificateInput`](crate::input::RegisterCertificateInput)
pub mod register_certificate_input {
/// A builder for [`RegisterCertificateInput`](crate::input::RegisterCertificateInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) certificate_data: std::option::Option<std::string::String>,
pub(crate) r#type: std::option::Option<crate::model::CertificateType>,
pub(crate) client_cert_auth_settings:
std::option::Option<crate::model::ClientCertAuthSettings>,
}
impl Builder {
/// <p>The identifier of the directory.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The certificate PEM string that needs to be registered.</p>
pub fn certificate_data(mut self, input: impl Into<std::string::String>) -> Self {
self.certificate_data = Some(input.into());
self
}
/// <p>The certificate PEM string that needs to be registered.</p>
pub fn set_certificate_data(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.certificate_data = input;
self
}
/// <p>The function that the registered certificate performs. Valid values include <code>ClientLDAPS</code> or <code>ClientCertAuth</code>. The default value is <code>ClientLDAPS</code>.</p>
pub fn r#type(mut self, input: crate::model::CertificateType) -> Self {
self.r#type = Some(input);
self
}
/// <p>The function that the registered certificate performs. Valid values include <code>ClientLDAPS</code> or <code>ClientCertAuth</code>. The default value is <code>ClientLDAPS</code>.</p>
pub fn set_type(
mut self,
input: std::option::Option<crate::model::CertificateType>,
) -> Self {
self.r#type = input;
self
}
/// <p>A <code>ClientCertAuthSettings</code> object that contains client certificate authentication settings.</p>
pub fn client_cert_auth_settings(
mut self,
input: crate::model::ClientCertAuthSettings,
) -> Self {
self.client_cert_auth_settings = Some(input);
self
}
/// <p>A <code>ClientCertAuthSettings</code> object that contains client certificate authentication settings.</p>
pub fn set_client_cert_auth_settings(
mut self,
input: std::option::Option<crate::model::ClientCertAuthSettings>,
) -> Self {
self.client_cert_auth_settings = input;
self
}
/// Consumes the builder and constructs a [`RegisterCertificateInput`](crate::input::RegisterCertificateInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::RegisterCertificateInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::RegisterCertificateInput {
directory_id: self.directory_id,
certificate_data: self.certificate_data,
r#type: self.r#type,
client_cert_auth_settings: self.client_cert_auth_settings,
})
}
}
}
#[doc(hidden)]
pub type RegisterCertificateInputOperationOutputAlias = crate::operation::RegisterCertificate;
#[doc(hidden)]
pub type RegisterCertificateInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl RegisterCertificateInput {
/// Consumes the builder and constructs an Operation<[`RegisterCertificate`](crate::operation::RegisterCertificate)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::RegisterCertificate,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::RegisterCertificateInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::RegisterCertificateInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.RegisterCertificate",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_register_certificate(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::RegisterCertificate::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"RegisterCertificate",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`RegisterCertificateInput`](crate::input::RegisterCertificateInput)
pub fn builder() -> crate::input::register_certificate_input::Builder {
crate::input::register_certificate_input::Builder::default()
}
}
/// See [`RegisterEventTopicInput`](crate::input::RegisterEventTopicInput)
pub mod register_event_topic_input {
/// A builder for [`RegisterEventTopicInput`](crate::input::RegisterEventTopicInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) topic_name: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The Directory ID that will publish status messages to the Amazon SNS topic.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The Directory ID that will publish status messages to the Amazon SNS topic.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The Amazon SNS topic name to which the directory will publish status messages. This Amazon SNS topic must be in the same region as the specified Directory ID.</p>
pub fn topic_name(mut self, input: impl Into<std::string::String>) -> Self {
self.topic_name = Some(input.into());
self
}
/// <p>The Amazon SNS topic name to which the directory will publish status messages. This Amazon SNS topic must be in the same region as the specified Directory ID.</p>
pub fn set_topic_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.topic_name = input;
self
}
/// Consumes the builder and constructs a [`RegisterEventTopicInput`](crate::input::RegisterEventTopicInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::RegisterEventTopicInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::RegisterEventTopicInput {
directory_id: self.directory_id,
topic_name: self.topic_name,
})
}
}
}
#[doc(hidden)]
pub type RegisterEventTopicInputOperationOutputAlias = crate::operation::RegisterEventTopic;
#[doc(hidden)]
pub type RegisterEventTopicInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl RegisterEventTopicInput {
/// Consumes the builder and constructs an Operation<[`RegisterEventTopic`](crate::operation::RegisterEventTopic)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::RegisterEventTopic,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::RegisterEventTopicInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::RegisterEventTopicInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.RegisterEventTopic",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_register_event_topic(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::RegisterEventTopic::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"RegisterEventTopic",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`RegisterEventTopicInput`](crate::input::RegisterEventTopicInput)
pub fn builder() -> crate::input::register_event_topic_input::Builder {
crate::input::register_event_topic_input::Builder::default()
}
}
/// See [`RejectSharedDirectoryInput`](crate::input::RejectSharedDirectoryInput)
pub mod reject_shared_directory_input {
/// A builder for [`RejectSharedDirectoryInput`](crate::input::RejectSharedDirectoryInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) shared_directory_id: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>Identifier of the shared directory in the directory consumer account. This identifier is different for each directory owner account.</p>
pub fn shared_directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.shared_directory_id = Some(input.into());
self
}
/// <p>Identifier of the shared directory in the directory consumer account. This identifier is different for each directory owner account.</p>
pub fn set_shared_directory_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.shared_directory_id = input;
self
}
/// Consumes the builder and constructs a [`RejectSharedDirectoryInput`](crate::input::RejectSharedDirectoryInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::RejectSharedDirectoryInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::RejectSharedDirectoryInput {
shared_directory_id: self.shared_directory_id,
})
}
}
}
#[doc(hidden)]
pub type RejectSharedDirectoryInputOperationOutputAlias = crate::operation::RejectSharedDirectory;
#[doc(hidden)]
pub type RejectSharedDirectoryInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl RejectSharedDirectoryInput {
/// Consumes the builder and constructs an Operation<[`RejectSharedDirectory`](crate::operation::RejectSharedDirectory)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::RejectSharedDirectory,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::RejectSharedDirectoryInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::RejectSharedDirectoryInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.RejectSharedDirectory",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_reject_shared_directory(
&self,
)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::RejectSharedDirectory::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"RejectSharedDirectory",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`RejectSharedDirectoryInput`](crate::input::RejectSharedDirectoryInput)
pub fn builder() -> crate::input::reject_shared_directory_input::Builder {
crate::input::reject_shared_directory_input::Builder::default()
}
}
/// See [`RemoveIpRoutesInput`](crate::input::RemoveIpRoutesInput)
pub mod remove_ip_routes_input {
/// A builder for [`RemoveIpRoutesInput`](crate::input::RemoveIpRoutesInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) cidr_ips: std::option::Option<std::vec::Vec<std::string::String>>,
}
impl Builder {
/// <p>Identifier (ID) of the directory from which you want to remove the IP addresses.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>Identifier (ID) of the directory from which you want to remove the IP addresses.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// Appends an item to `cidr_ips`.
///
/// To override the contents of this collection use [`set_cidr_ips`](Self::set_cidr_ips).
///
/// <p>IP address blocks that you want to remove.</p>
pub fn cidr_ips(mut self, input: impl Into<std::string::String>) -> Self {
let mut v = self.cidr_ips.unwrap_or_default();
v.push(input.into());
self.cidr_ips = Some(v);
self
}
/// <p>IP address blocks that you want to remove.</p>
pub fn set_cidr_ips(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.cidr_ips = input;
self
}
/// Consumes the builder and constructs a [`RemoveIpRoutesInput`](crate::input::RemoveIpRoutesInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::RemoveIpRoutesInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::RemoveIpRoutesInput {
directory_id: self.directory_id,
cidr_ips: self.cidr_ips,
})
}
}
}
#[doc(hidden)]
pub type RemoveIpRoutesInputOperationOutputAlias = crate::operation::RemoveIpRoutes;
#[doc(hidden)]
pub type RemoveIpRoutesInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl RemoveIpRoutesInput {
/// Consumes the builder and constructs an Operation<[`RemoveIpRoutes`](crate::operation::RemoveIpRoutes)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::RemoveIpRoutes,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::RemoveIpRoutesInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::RemoveIpRoutesInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.RemoveIpRoutes",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_remove_ip_routes(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::RemoveIpRoutes::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"RemoveIpRoutes",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`RemoveIpRoutesInput`](crate::input::RemoveIpRoutesInput)
pub fn builder() -> crate::input::remove_ip_routes_input::Builder {
crate::input::remove_ip_routes_input::Builder::default()
}
}
/// See [`RemoveRegionInput`](crate::input::RemoveRegionInput)
pub mod remove_region_input {
/// A builder for [`RemoveRegionInput`](crate::input::RemoveRegionInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The identifier of the directory for which you want to remove Region replication.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory for which you want to remove Region replication.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// Consumes the builder and constructs a [`RemoveRegionInput`](crate::input::RemoveRegionInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::RemoveRegionInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::RemoveRegionInput {
directory_id: self.directory_id,
})
}
}
}
#[doc(hidden)]
pub type RemoveRegionInputOperationOutputAlias = crate::operation::RemoveRegion;
#[doc(hidden)]
pub type RemoveRegionInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl RemoveRegionInput {
/// Consumes the builder and constructs an Operation<[`RemoveRegion`](crate::operation::RemoveRegion)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::RemoveRegion,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::RemoveRegionInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::RemoveRegionInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.RemoveRegion",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_remove_region(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::RemoveRegion::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"RemoveRegion",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`RemoveRegionInput`](crate::input::RemoveRegionInput)
pub fn builder() -> crate::input::remove_region_input::Builder {
crate::input::remove_region_input::Builder::default()
}
}
/// See [`RemoveTagsFromResourceInput`](crate::input::RemoveTagsFromResourceInput)
pub mod remove_tags_from_resource_input {
/// A builder for [`RemoveTagsFromResourceInput`](crate::input::RemoveTagsFromResourceInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) resource_id: std::option::Option<std::string::String>,
pub(crate) tag_keys: std::option::Option<std::vec::Vec<std::string::String>>,
}
impl Builder {
/// <p>Identifier (ID) of the directory from which to remove the tag.</p>
pub fn resource_id(mut self, input: impl Into<std::string::String>) -> Self {
self.resource_id = Some(input.into());
self
}
/// <p>Identifier (ID) of the directory from which to remove the tag.</p>
pub fn set_resource_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.resource_id = input;
self
}
/// Appends an item to `tag_keys`.
///
/// To override the contents of this collection use [`set_tag_keys`](Self::set_tag_keys).
///
/// <p>The tag key (name) of the tag to be removed.</p>
pub fn tag_keys(mut self, input: impl Into<std::string::String>) -> Self {
let mut v = self.tag_keys.unwrap_or_default();
v.push(input.into());
self.tag_keys = Some(v);
self
}
/// <p>The tag key (name) of the tag to be removed.</p>
pub fn set_tag_keys(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.tag_keys = input;
self
}
/// Consumes the builder and constructs a [`RemoveTagsFromResourceInput`](crate::input::RemoveTagsFromResourceInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::RemoveTagsFromResourceInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::RemoveTagsFromResourceInput {
resource_id: self.resource_id,
tag_keys: self.tag_keys,
})
}
}
}
#[doc(hidden)]
pub type RemoveTagsFromResourceInputOperationOutputAlias = crate::operation::RemoveTagsFromResource;
#[doc(hidden)]
pub type RemoveTagsFromResourceInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl RemoveTagsFromResourceInput {
/// Consumes the builder and constructs an Operation<[`RemoveTagsFromResource`](crate::operation::RemoveTagsFromResource)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::RemoveTagsFromResource,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::RemoveTagsFromResourceInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::RemoveTagsFromResourceInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.RemoveTagsFromResource",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_remove_tags_from_resource(
&self,
)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::RemoveTagsFromResource::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"RemoveTagsFromResource",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`RemoveTagsFromResourceInput`](crate::input::RemoveTagsFromResourceInput)
pub fn builder() -> crate::input::remove_tags_from_resource_input::Builder {
crate::input::remove_tags_from_resource_input::Builder::default()
}
}
/// See [`ResetUserPasswordInput`](crate::input::ResetUserPasswordInput)
pub mod reset_user_password_input {
/// A builder for [`ResetUserPasswordInput`](crate::input::ResetUserPasswordInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) user_name: std::option::Option<std::string::String>,
pub(crate) new_password: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>Identifier of the Managed Microsoft AD or Simple AD directory in which the user resides.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>Identifier of the Managed Microsoft AD or Simple AD directory in which the user resides.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The user name of the user whose password will be reset.</p>
pub fn user_name(mut self, input: impl Into<std::string::String>) -> Self {
self.user_name = Some(input.into());
self
}
/// <p>The user name of the user whose password will be reset.</p>
pub fn set_user_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.user_name = input;
self
}
/// <p>The new password that will be reset.</p>
pub fn new_password(mut self, input: impl Into<std::string::String>) -> Self {
self.new_password = Some(input.into());
self
}
/// <p>The new password that will be reset.</p>
pub fn set_new_password(mut self, input: std::option::Option<std::string::String>) -> Self {
self.new_password = input;
self
}
/// Consumes the builder and constructs a [`ResetUserPasswordInput`](crate::input::ResetUserPasswordInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::ResetUserPasswordInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::ResetUserPasswordInput {
directory_id: self.directory_id,
user_name: self.user_name,
new_password: self.new_password,
})
}
}
}
#[doc(hidden)]
pub type ResetUserPasswordInputOperationOutputAlias = crate::operation::ResetUserPassword;
#[doc(hidden)]
pub type ResetUserPasswordInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl ResetUserPasswordInput {
/// Consumes the builder and constructs an Operation<[`ResetUserPassword`](crate::operation::ResetUserPassword)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::ResetUserPassword,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::ResetUserPasswordInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::ResetUserPasswordInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.ResetUserPassword",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_reset_user_password(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::ResetUserPassword::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"ResetUserPassword",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`ResetUserPasswordInput`](crate::input::ResetUserPasswordInput)
pub fn builder() -> crate::input::reset_user_password_input::Builder {
crate::input::reset_user_password_input::Builder::default()
}
}
/// See [`RestoreFromSnapshotInput`](crate::input::RestoreFromSnapshotInput)
pub mod restore_from_snapshot_input {
/// A builder for [`RestoreFromSnapshotInput`](crate::input::RestoreFromSnapshotInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) snapshot_id: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The identifier of the snapshot to restore from.</p>
pub fn snapshot_id(mut self, input: impl Into<std::string::String>) -> Self {
self.snapshot_id = Some(input.into());
self
}
/// <p>The identifier of the snapshot to restore from.</p>
pub fn set_snapshot_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.snapshot_id = input;
self
}
/// Consumes the builder and constructs a [`RestoreFromSnapshotInput`](crate::input::RestoreFromSnapshotInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::RestoreFromSnapshotInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::RestoreFromSnapshotInput {
snapshot_id: self.snapshot_id,
})
}
}
}
#[doc(hidden)]
pub type RestoreFromSnapshotInputOperationOutputAlias = crate::operation::RestoreFromSnapshot;
#[doc(hidden)]
pub type RestoreFromSnapshotInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl RestoreFromSnapshotInput {
/// Consumes the builder and constructs an Operation<[`RestoreFromSnapshot`](crate::operation::RestoreFromSnapshot)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::RestoreFromSnapshot,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::RestoreFromSnapshotInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::RestoreFromSnapshotInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.RestoreFromSnapshot",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_restore_from_snapshot(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::RestoreFromSnapshot::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"RestoreFromSnapshot",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`RestoreFromSnapshotInput`](crate::input::RestoreFromSnapshotInput)
pub fn builder() -> crate::input::restore_from_snapshot_input::Builder {
crate::input::restore_from_snapshot_input::Builder::default()
}
}
/// See [`ShareDirectoryInput`](crate::input::ShareDirectoryInput)
pub mod share_directory_input {
/// A builder for [`ShareDirectoryInput`](crate::input::ShareDirectoryInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) share_notes: std::option::Option<std::string::String>,
pub(crate) share_target: std::option::Option<crate::model::ShareTarget>,
pub(crate) share_method: std::option::Option<crate::model::ShareMethod>,
}
impl Builder {
/// <p>Identifier of the Managed Microsoft AD directory that you want to share with other Amazon Web Services accounts.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>Identifier of the Managed Microsoft AD directory that you want to share with other Amazon Web Services accounts.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>A directory share request that is sent by the directory owner to the directory consumer. The request includes a typed message to help the directory consumer administrator determine whether to approve or reject the share invitation.</p>
pub fn share_notes(mut self, input: impl Into<std::string::String>) -> Self {
self.share_notes = Some(input.into());
self
}
/// <p>A directory share request that is sent by the directory owner to the directory consumer. The request includes a typed message to help the directory consumer administrator determine whether to approve or reject the share invitation.</p>
pub fn set_share_notes(mut self, input: std::option::Option<std::string::String>) -> Self {
self.share_notes = input;
self
}
/// <p>Identifier for the directory consumer account with whom the directory is to be shared.</p>
pub fn share_target(mut self, input: crate::model::ShareTarget) -> Self {
self.share_target = Some(input);
self
}
/// <p>Identifier for the directory consumer account with whom the directory is to be shared.</p>
pub fn set_share_target(
mut self,
input: std::option::Option<crate::model::ShareTarget>,
) -> Self {
self.share_target = input;
self
}
/// <p>The method used when sharing a directory to determine whether the directory should be shared within your Amazon Web Services organization (<code>ORGANIZATIONS</code>) or with any Amazon Web Services account by sending a directory sharing request (<code>HANDSHAKE</code>).</p>
pub fn share_method(mut self, input: crate::model::ShareMethod) -> Self {
self.share_method = Some(input);
self
}
/// <p>The method used when sharing a directory to determine whether the directory should be shared within your Amazon Web Services organization (<code>ORGANIZATIONS</code>) or with any Amazon Web Services account by sending a directory sharing request (<code>HANDSHAKE</code>).</p>
pub fn set_share_method(
mut self,
input: std::option::Option<crate::model::ShareMethod>,
) -> Self {
self.share_method = input;
self
}
/// Consumes the builder and constructs a [`ShareDirectoryInput`](crate::input::ShareDirectoryInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::ShareDirectoryInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::ShareDirectoryInput {
directory_id: self.directory_id,
share_notes: self.share_notes,
share_target: self.share_target,
share_method: self.share_method,
})
}
}
}
#[doc(hidden)]
pub type ShareDirectoryInputOperationOutputAlias = crate::operation::ShareDirectory;
#[doc(hidden)]
pub type ShareDirectoryInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl ShareDirectoryInput {
/// Consumes the builder and constructs an Operation<[`ShareDirectory`](crate::operation::ShareDirectory)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::ShareDirectory,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::ShareDirectoryInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::ShareDirectoryInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.ShareDirectory",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_share_directory(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::ShareDirectory::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"ShareDirectory",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`ShareDirectoryInput`](crate::input::ShareDirectoryInput)
pub fn builder() -> crate::input::share_directory_input::Builder {
crate::input::share_directory_input::Builder::default()
}
}
/// See [`StartSchemaExtensionInput`](crate::input::StartSchemaExtensionInput)
pub mod start_schema_extension_input {
/// A builder for [`StartSchemaExtensionInput`](crate::input::StartSchemaExtensionInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) create_snapshot_before_schema_extension: std::option::Option<bool>,
pub(crate) ldif_content: std::option::Option<std::string::String>,
pub(crate) description: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The identifier of the directory for which the schema extension will be applied to.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory for which the schema extension will be applied to.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>If true, creates a snapshot of the directory before applying the schema extension.</p>
pub fn create_snapshot_before_schema_extension(mut self, input: bool) -> Self {
self.create_snapshot_before_schema_extension = Some(input);
self
}
/// <p>If true, creates a snapshot of the directory before applying the schema extension.</p>
pub fn set_create_snapshot_before_schema_extension(
mut self,
input: std::option::Option<bool>,
) -> Self {
self.create_snapshot_before_schema_extension = input;
self
}
/// <p>The LDIF file represented as a string. To construct the LdifContent string, precede each line as it would be formatted in an ldif file with \n. See the example request below for more details. The file size can be no larger than 1MB.</p>
pub fn ldif_content(mut self, input: impl Into<std::string::String>) -> Self {
self.ldif_content = Some(input.into());
self
}
/// <p>The LDIF file represented as a string. To construct the LdifContent string, precede each line as it would be formatted in an ldif file with \n. See the example request below for more details. The file size can be no larger than 1MB.</p>
pub fn set_ldif_content(mut self, input: std::option::Option<std::string::String>) -> Self {
self.ldif_content = input;
self
}
/// <p>A description of the schema extension.</p>
pub fn description(mut self, input: impl Into<std::string::String>) -> Self {
self.description = Some(input.into());
self
}
/// <p>A description of the schema extension.</p>
pub fn set_description(mut self, input: std::option::Option<std::string::String>) -> Self {
self.description = input;
self
}
/// Consumes the builder and constructs a [`StartSchemaExtensionInput`](crate::input::StartSchemaExtensionInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::StartSchemaExtensionInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::StartSchemaExtensionInput {
directory_id: self.directory_id,
create_snapshot_before_schema_extension: self
.create_snapshot_before_schema_extension
.unwrap_or_default(),
ldif_content: self.ldif_content,
description: self.description,
})
}
}
}
#[doc(hidden)]
pub type StartSchemaExtensionInputOperationOutputAlias = crate::operation::StartSchemaExtension;
#[doc(hidden)]
pub type StartSchemaExtensionInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl StartSchemaExtensionInput {
/// Consumes the builder and constructs an Operation<[`StartSchemaExtension`](crate::operation::StartSchemaExtension)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::StartSchemaExtension,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::StartSchemaExtensionInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::StartSchemaExtensionInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.StartSchemaExtension",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_start_schema_extension(
&self,
)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::StartSchemaExtension::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"StartSchemaExtension",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`StartSchemaExtensionInput`](crate::input::StartSchemaExtensionInput)
pub fn builder() -> crate::input::start_schema_extension_input::Builder {
crate::input::start_schema_extension_input::Builder::default()
}
}
/// See [`UnshareDirectoryInput`](crate::input::UnshareDirectoryInput)
pub mod unshare_directory_input {
/// A builder for [`UnshareDirectoryInput`](crate::input::UnshareDirectoryInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) unshare_target: std::option::Option<crate::model::UnshareTarget>,
}
impl Builder {
/// <p>The identifier of the Managed Microsoft AD directory that you want to stop sharing.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the Managed Microsoft AD directory that you want to stop sharing.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>Identifier for the directory consumer account with whom the directory has to be unshared.</p>
pub fn unshare_target(mut self, input: crate::model::UnshareTarget) -> Self {
self.unshare_target = Some(input);
self
}
/// <p>Identifier for the directory consumer account with whom the directory has to be unshared.</p>
pub fn set_unshare_target(
mut self,
input: std::option::Option<crate::model::UnshareTarget>,
) -> Self {
self.unshare_target = input;
self
}
/// Consumes the builder and constructs a [`UnshareDirectoryInput`](crate::input::UnshareDirectoryInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::UnshareDirectoryInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::UnshareDirectoryInput {
directory_id: self.directory_id,
unshare_target: self.unshare_target,
})
}
}
}
#[doc(hidden)]
pub type UnshareDirectoryInputOperationOutputAlias = crate::operation::UnshareDirectory;
#[doc(hidden)]
pub type UnshareDirectoryInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl UnshareDirectoryInput {
/// Consumes the builder and constructs an Operation<[`UnshareDirectory`](crate::operation::UnshareDirectory)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::UnshareDirectory,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::UnshareDirectoryInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::UnshareDirectoryInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.UnshareDirectory",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_unshare_directory(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::UnshareDirectory::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"UnshareDirectory",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`UnshareDirectoryInput`](crate::input::UnshareDirectoryInput)
pub fn builder() -> crate::input::unshare_directory_input::Builder {
crate::input::unshare_directory_input::Builder::default()
}
}
/// See [`UpdateConditionalForwarderInput`](crate::input::UpdateConditionalForwarderInput)
pub mod update_conditional_forwarder_input {
/// A builder for [`UpdateConditionalForwarderInput`](crate::input::UpdateConditionalForwarderInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) remote_domain_name: std::option::Option<std::string::String>,
pub(crate) dns_ip_addrs: std::option::Option<std::vec::Vec<std::string::String>>,
}
impl Builder {
/// <p>The directory ID of the Amazon Web Services directory for which to update the conditional forwarder.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The directory ID of the Amazon Web Services directory for which to update the conditional forwarder.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The fully qualified domain name (FQDN) of the remote domain with which you will set up a trust relationship.</p>
pub fn remote_domain_name(mut self, input: impl Into<std::string::String>) -> Self {
self.remote_domain_name = Some(input.into());
self
}
/// <p>The fully qualified domain name (FQDN) of the remote domain with which you will set up a trust relationship.</p>
pub fn set_remote_domain_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.remote_domain_name = input;
self
}
/// Appends an item to `dns_ip_addrs`.
///
/// To override the contents of this collection use [`set_dns_ip_addrs`](Self::set_dns_ip_addrs).
///
/// <p>The updated IP addresses of the remote DNS server associated with the conditional forwarder.</p>
pub fn dns_ip_addrs(mut self, input: impl Into<std::string::String>) -> Self {
let mut v = self.dns_ip_addrs.unwrap_or_default();
v.push(input.into());
self.dns_ip_addrs = Some(v);
self
}
/// <p>The updated IP addresses of the remote DNS server associated with the conditional forwarder.</p>
pub fn set_dns_ip_addrs(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.dns_ip_addrs = input;
self
}
/// Consumes the builder and constructs a [`UpdateConditionalForwarderInput`](crate::input::UpdateConditionalForwarderInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::UpdateConditionalForwarderInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::UpdateConditionalForwarderInput {
directory_id: self.directory_id,
remote_domain_name: self.remote_domain_name,
dns_ip_addrs: self.dns_ip_addrs,
})
}
}
}
#[doc(hidden)]
pub type UpdateConditionalForwarderInputOperationOutputAlias =
crate::operation::UpdateConditionalForwarder;
#[doc(hidden)]
pub type UpdateConditionalForwarderInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl UpdateConditionalForwarderInput {
/// Consumes the builder and constructs an Operation<[`UpdateConditionalForwarder`](crate::operation::UpdateConditionalForwarder)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::UpdateConditionalForwarder,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::UpdateConditionalForwarderInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::UpdateConditionalForwarderInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.UpdateConditionalForwarder",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_update_conditional_forwarder(
&self,
)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::UpdateConditionalForwarder::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"UpdateConditionalForwarder",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`UpdateConditionalForwarderInput`](crate::input::UpdateConditionalForwarderInput)
pub fn builder() -> crate::input::update_conditional_forwarder_input::Builder {
crate::input::update_conditional_forwarder_input::Builder::default()
}
}
/// See [`UpdateNumberOfDomainControllersInput`](crate::input::UpdateNumberOfDomainControllersInput)
pub mod update_number_of_domain_controllers_input {
/// A builder for [`UpdateNumberOfDomainControllersInput`](crate::input::UpdateNumberOfDomainControllersInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) desired_number: std::option::Option<i32>,
}
impl Builder {
/// <p>Identifier of the directory to which the domain controllers will be added or removed.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>Identifier of the directory to which the domain controllers will be added or removed.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>The number of domain controllers desired in the directory.</p>
pub fn desired_number(mut self, input: i32) -> Self {
self.desired_number = Some(input);
self
}
/// <p>The number of domain controllers desired in the directory.</p>
pub fn set_desired_number(mut self, input: std::option::Option<i32>) -> Self {
self.desired_number = input;
self
}
/// Consumes the builder and constructs a [`UpdateNumberOfDomainControllersInput`](crate::input::UpdateNumberOfDomainControllersInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::UpdateNumberOfDomainControllersInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::UpdateNumberOfDomainControllersInput {
directory_id: self.directory_id,
desired_number: self.desired_number.unwrap_or_default(),
})
}
}
}
#[doc(hidden)]
pub type UpdateNumberOfDomainControllersInputOperationOutputAlias =
crate::operation::UpdateNumberOfDomainControllers;
#[doc(hidden)]
pub type UpdateNumberOfDomainControllersInputOperationRetryAlias =
aws_http::retry::AwsErrorRetryPolicy;
impl UpdateNumberOfDomainControllersInput {
/// Consumes the builder and constructs an Operation<[`UpdateNumberOfDomainControllers`](crate::operation::UpdateNumberOfDomainControllers)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::UpdateNumberOfDomainControllers,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::UpdateNumberOfDomainControllersInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::UpdateNumberOfDomainControllersInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.UpdateNumberOfDomainControllers",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_update_number_of_domain_controllers(&self)?
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::UpdateNumberOfDomainControllers::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"UpdateNumberOfDomainControllers",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`UpdateNumberOfDomainControllersInput`](crate::input::UpdateNumberOfDomainControllersInput)
pub fn builder() -> crate::input::update_number_of_domain_controllers_input::Builder {
crate::input::update_number_of_domain_controllers_input::Builder::default()
}
}
/// See [`UpdateRadiusInput`](crate::input::UpdateRadiusInput)
pub mod update_radius_input {
/// A builder for [`UpdateRadiusInput`](crate::input::UpdateRadiusInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) directory_id: std::option::Option<std::string::String>,
pub(crate) radius_settings: std::option::Option<crate::model::RadiusSettings>,
}
impl Builder {
/// <p>The identifier of the directory for which to update the RADIUS server information.</p>
pub fn directory_id(mut self, input: impl Into<std::string::String>) -> Self {
self.directory_id = Some(input.into());
self
}
/// <p>The identifier of the directory for which to update the RADIUS server information.</p>
pub fn set_directory_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.directory_id = input;
self
}
/// <p>A <code>RadiusSettings</code> object that contains information about the RADIUS server.</p>
pub fn radius_settings(mut self, input: crate::model::RadiusSettings) -> Self {
self.radius_settings = Some(input);
self
}
/// <p>A <code>RadiusSettings</code> object that contains information about the RADIUS server.</p>
pub fn set_radius_settings(
mut self,
input: std::option::Option<crate::model::RadiusSettings>,
) -> Self {
self.radius_settings = input;
self
}
/// Consumes the builder and constructs a [`UpdateRadiusInput`](crate::input::UpdateRadiusInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::UpdateRadiusInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::UpdateRadiusInput {
directory_id: self.directory_id,
radius_settings: self.radius_settings,
})
}
}
}
#[doc(hidden)]
pub type UpdateRadiusInputOperationOutputAlias = crate::operation::UpdateRadius;
#[doc(hidden)]
pub type UpdateRadiusInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl UpdateRadiusInput {
/// Consumes the builder and constructs an Operation<[`UpdateRadius`](crate::operation::UpdateRadius)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::UpdateRadius,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::UpdateRadiusInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::UpdateRadiusInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.UpdateRadius",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_update_radius(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::UpdateRadius::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"UpdateRadius",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`UpdateRadiusInput`](crate::input::UpdateRadiusInput)
pub fn builder() -> crate::input::update_radius_input::Builder {
crate::input::update_radius_input::Builder::default()
}
}
/// See [`UpdateTrustInput`](crate::input::UpdateTrustInput)
pub mod update_trust_input {
/// A builder for [`UpdateTrustInput`](crate::input::UpdateTrustInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) trust_id: std::option::Option<std::string::String>,
pub(crate) selective_auth: std::option::Option<crate::model::SelectiveAuth>,
}
impl Builder {
/// <p>Identifier of the trust relationship.</p>
pub fn trust_id(mut self, input: impl Into<std::string::String>) -> Self {
self.trust_id = Some(input.into());
self
}
/// <p>Identifier of the trust relationship.</p>
pub fn set_trust_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.trust_id = input;
self
}
/// <p>Updates selective authentication for the trust.</p>
pub fn selective_auth(mut self, input: crate::model::SelectiveAuth) -> Self {
self.selective_auth = Some(input);
self
}
/// <p>Updates selective authentication for the trust.</p>
pub fn set_selective_auth(
mut self,
input: std::option::Option<crate::model::SelectiveAuth>,
) -> Self {
self.selective_auth = input;
self
}
/// Consumes the builder and constructs a [`UpdateTrustInput`](crate::input::UpdateTrustInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::UpdateTrustInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::UpdateTrustInput {
trust_id: self.trust_id,
selective_auth: self.selective_auth,
})
}
}
}
#[doc(hidden)]
pub type UpdateTrustInputOperationOutputAlias = crate::operation::UpdateTrust;
#[doc(hidden)]
pub type UpdateTrustInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl UpdateTrustInput {
/// Consumes the builder and constructs an Operation<[`UpdateTrust`](crate::operation::UpdateTrust)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::UpdateTrust,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::UpdateTrustInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::UpdateTrustInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.UpdateTrust",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_update_trust(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::UpdateTrust::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"UpdateTrust",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`UpdateTrustInput`](crate::input::UpdateTrustInput)
pub fn builder() -> crate::input::update_trust_input::Builder {
crate::input::update_trust_input::Builder::default()
}
}
/// See [`VerifyTrustInput`](crate::input::VerifyTrustInput)
pub mod verify_trust_input {
/// A builder for [`VerifyTrustInput`](crate::input::VerifyTrustInput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) trust_id: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The unique Trust ID of the trust relationship to verify.</p>
pub fn trust_id(mut self, input: impl Into<std::string::String>) -> Self {
self.trust_id = Some(input.into());
self
}
/// <p>The unique Trust ID of the trust relationship to verify.</p>
pub fn set_trust_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.trust_id = input;
self
}
/// Consumes the builder and constructs a [`VerifyTrustInput`](crate::input::VerifyTrustInput)
pub fn build(
self,
) -> std::result::Result<
crate::input::VerifyTrustInput,
aws_smithy_http::operation::BuildError,
> {
Ok(crate::input::VerifyTrustInput {
trust_id: self.trust_id,
})
}
}
}
#[doc(hidden)]
pub type VerifyTrustInputOperationOutputAlias = crate::operation::VerifyTrust;
#[doc(hidden)]
pub type VerifyTrustInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl VerifyTrustInput {
/// Consumes the builder and constructs an Operation<[`VerifyTrust`](crate::operation::VerifyTrust)>
#[allow(unused_mut)]
#[allow(clippy::let_and_return)]
#[allow(clippy::needless_borrow)]
pub async fn make_operation(
&self,
_config: &crate::config::Config,
) -> std::result::Result<
aws_smithy_http::operation::Operation<
crate::operation::VerifyTrust,
aws_http::retry::AwsErrorRetryPolicy,
>,
aws_smithy_http::operation::BuildError,
> {
let mut request = {
fn uri_base(
_input: &crate::input::VerifyTrustInput,
output: &mut String,
) -> Result<(), aws_smithy_http::operation::BuildError> {
write!(output, "/").expect("formatting should succeed");
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn update_http_builder(
input: &crate::input::VerifyTrustInput,
builder: http::request::Builder,
) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
{
let mut uri = String::new();
uri_base(input, &mut uri)?;
Ok(builder.method("POST").uri(uri))
}
let mut builder = update_http_builder(&self, http::request::Builder::new())?;
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::CONTENT_TYPE,
"application/x-amz-json-1.1",
);
builder = aws_smithy_http::header::set_request_header_if_absent(
builder,
http::header::HeaderName::from_static("x-amz-target"),
"DirectoryService_20150416.VerifyTrust",
);
builder
};
let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
#[allow(clippy::useless_conversion)]
let body = aws_smithy_http::body::SdkBody::from(
crate::operation_ser::serialize_operation_crate_operation_verify_trust(&self)?,
);
if let Some(content_length) = body.content_length() {
request = aws_smithy_http::header::set_request_header_if_absent(
request,
http::header::CONTENT_LENGTH,
content_length,
);
}
let request = request.body(body).expect("should be valid request");
let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
aws_types::os_shim_internal::Env::real(),
crate::API_METADATA.clone(),
);
if let Some(app_name) = _config.app_name() {
user_agent = user_agent.with_app_name(app_name.clone());
}
request.properties_mut().insert(user_agent);
let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
request.properties_mut().insert(signing_config);
request
.properties_mut()
.insert(aws_types::SigningService::from_static(
_config.signing_service(),
));
aws_endpoint::set_endpoint_resolver(
&mut request.properties_mut(),
_config.endpoint_resolver.clone(),
);
if let Some(region) = &_config.region {
request.properties_mut().insert(region.clone());
}
aws_http::auth::set_provider(
&mut request.properties_mut(),
_config.credentials_provider.clone(),
);
let op = aws_smithy_http::operation::Operation::new(
request,
crate::operation::VerifyTrust::new(),
)
.with_metadata(aws_smithy_http::operation::Metadata::new(
"VerifyTrust",
"directoryservice",
));
let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
Ok(op)
}
/// Creates a new builder-style object to manufacture [`VerifyTrustInput`](crate::input::VerifyTrustInput)
pub fn builder() -> crate::input::verify_trust_input::Builder {
crate::input::verify_trust_input::Builder::default()
}
}
/// <p>Initiates the verification of an existing trust relationship between an Managed Microsoft AD directory and an external domain.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct VerifyTrustInput {
/// <p>The unique Trust ID of the trust relationship to verify.</p>
pub trust_id: std::option::Option<std::string::String>,
}
impl VerifyTrustInput {
/// <p>The unique Trust ID of the trust relationship to verify.</p>
pub fn trust_id(&self) -> std::option::Option<&str> {
self.trust_id.as_deref()
}
}
impl std::fmt::Debug for VerifyTrustInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("VerifyTrustInput");
formatter.field("trust_id", &self.trust_id);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct UpdateTrustInput {
/// <p>Identifier of the trust relationship.</p>
pub trust_id: std::option::Option<std::string::String>,
/// <p>Updates selective authentication for the trust.</p>
pub selective_auth: std::option::Option<crate::model::SelectiveAuth>,
}
impl UpdateTrustInput {
/// <p>Identifier of the trust relationship.</p>
pub fn trust_id(&self) -> std::option::Option<&str> {
self.trust_id.as_deref()
}
/// <p>Updates selective authentication for the trust.</p>
pub fn selective_auth(&self) -> std::option::Option<&crate::model::SelectiveAuth> {
self.selective_auth.as_ref()
}
}
impl std::fmt::Debug for UpdateTrustInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("UpdateTrustInput");
formatter.field("trust_id", &self.trust_id);
formatter.field("selective_auth", &self.selective_auth);
formatter.finish()
}
}
/// <p>Contains the inputs for the <code>UpdateRadius</code> operation.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct UpdateRadiusInput {
/// <p>The identifier of the directory for which to update the RADIUS server information.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>A <code>RadiusSettings</code> object that contains information about the RADIUS server.</p>
pub radius_settings: std::option::Option<crate::model::RadiusSettings>,
}
impl UpdateRadiusInput {
/// <p>The identifier of the directory for which to update the RADIUS server information.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>A <code>RadiusSettings</code> object that contains information about the RADIUS server.</p>
pub fn radius_settings(&self) -> std::option::Option<&crate::model::RadiusSettings> {
self.radius_settings.as_ref()
}
}
impl std::fmt::Debug for UpdateRadiusInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("UpdateRadiusInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("radius_settings", &self.radius_settings);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct UpdateNumberOfDomainControllersInput {
/// <p>Identifier of the directory to which the domain controllers will be added or removed.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The number of domain controllers desired in the directory.</p>
pub desired_number: i32,
}
impl UpdateNumberOfDomainControllersInput {
/// <p>Identifier of the directory to which the domain controllers will be added or removed.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The number of domain controllers desired in the directory.</p>
pub fn desired_number(&self) -> i32 {
self.desired_number
}
}
impl std::fmt::Debug for UpdateNumberOfDomainControllersInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("UpdateNumberOfDomainControllersInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("desired_number", &self.desired_number);
formatter.finish()
}
}
/// <p>Updates a conditional forwarder.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct UpdateConditionalForwarderInput {
/// <p>The directory ID of the Amazon Web Services directory for which to update the conditional forwarder.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The fully qualified domain name (FQDN) of the remote domain with which you will set up a trust relationship.</p>
pub remote_domain_name: std::option::Option<std::string::String>,
/// <p>The updated IP addresses of the remote DNS server associated with the conditional forwarder.</p>
pub dns_ip_addrs: std::option::Option<std::vec::Vec<std::string::String>>,
}
impl UpdateConditionalForwarderInput {
/// <p>The directory ID of the Amazon Web Services directory for which to update the conditional forwarder.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The fully qualified domain name (FQDN) of the remote domain with which you will set up a trust relationship.</p>
pub fn remote_domain_name(&self) -> std::option::Option<&str> {
self.remote_domain_name.as_deref()
}
/// <p>The updated IP addresses of the remote DNS server associated with the conditional forwarder.</p>
pub fn dns_ip_addrs(&self) -> std::option::Option<&[std::string::String]> {
self.dns_ip_addrs.as_deref()
}
}
impl std::fmt::Debug for UpdateConditionalForwarderInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("UpdateConditionalForwarderInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("remote_domain_name", &self.remote_domain_name);
formatter.field("dns_ip_addrs", &self.dns_ip_addrs);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct UnshareDirectoryInput {
/// <p>The identifier of the Managed Microsoft AD directory that you want to stop sharing.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>Identifier for the directory consumer account with whom the directory has to be unshared.</p>
pub unshare_target: std::option::Option<crate::model::UnshareTarget>,
}
impl UnshareDirectoryInput {
/// <p>The identifier of the Managed Microsoft AD directory that you want to stop sharing.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>Identifier for the directory consumer account with whom the directory has to be unshared.</p>
pub fn unshare_target(&self) -> std::option::Option<&crate::model::UnshareTarget> {
self.unshare_target.as_ref()
}
}
impl std::fmt::Debug for UnshareDirectoryInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("UnshareDirectoryInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("unshare_target", &self.unshare_target);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct StartSchemaExtensionInput {
/// <p>The identifier of the directory for which the schema extension will be applied to.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>If true, creates a snapshot of the directory before applying the schema extension.</p>
pub create_snapshot_before_schema_extension: bool,
/// <p>The LDIF file represented as a string. To construct the LdifContent string, precede each line as it would be formatted in an ldif file with \n. See the example request below for more details. The file size can be no larger than 1MB.</p>
pub ldif_content: std::option::Option<std::string::String>,
/// <p>A description of the schema extension.</p>
pub description: std::option::Option<std::string::String>,
}
impl StartSchemaExtensionInput {
/// <p>The identifier of the directory for which the schema extension will be applied to.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>If true, creates a snapshot of the directory before applying the schema extension.</p>
pub fn create_snapshot_before_schema_extension(&self) -> bool {
self.create_snapshot_before_schema_extension
}
/// <p>The LDIF file represented as a string. To construct the LdifContent string, precede each line as it would be formatted in an ldif file with \n. See the example request below for more details. The file size can be no larger than 1MB.</p>
pub fn ldif_content(&self) -> std::option::Option<&str> {
self.ldif_content.as_deref()
}
/// <p>A description of the schema extension.</p>
pub fn description(&self) -> std::option::Option<&str> {
self.description.as_deref()
}
}
impl std::fmt::Debug for StartSchemaExtensionInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("StartSchemaExtensionInput");
formatter.field("directory_id", &self.directory_id);
formatter.field(
"create_snapshot_before_schema_extension",
&self.create_snapshot_before_schema_extension,
);
formatter.field("ldif_content", &self.ldif_content);
formatter.field("description", &self.description);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ShareDirectoryInput {
/// <p>Identifier of the Managed Microsoft AD directory that you want to share with other Amazon Web Services accounts.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>A directory share request that is sent by the directory owner to the directory consumer. The request includes a typed message to help the directory consumer administrator determine whether to approve or reject the share invitation.</p>
pub share_notes: std::option::Option<std::string::String>,
/// <p>Identifier for the directory consumer account with whom the directory is to be shared.</p>
pub share_target: std::option::Option<crate::model::ShareTarget>,
/// <p>The method used when sharing a directory to determine whether the directory should be shared within your Amazon Web Services organization (<code>ORGANIZATIONS</code>) or with any Amazon Web Services account by sending a directory sharing request (<code>HANDSHAKE</code>).</p>
pub share_method: std::option::Option<crate::model::ShareMethod>,
}
impl ShareDirectoryInput {
/// <p>Identifier of the Managed Microsoft AD directory that you want to share with other Amazon Web Services accounts.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>A directory share request that is sent by the directory owner to the directory consumer. The request includes a typed message to help the directory consumer administrator determine whether to approve or reject the share invitation.</p>
pub fn share_notes(&self) -> std::option::Option<&str> {
self.share_notes.as_deref()
}
/// <p>Identifier for the directory consumer account with whom the directory is to be shared.</p>
pub fn share_target(&self) -> std::option::Option<&crate::model::ShareTarget> {
self.share_target.as_ref()
}
/// <p>The method used when sharing a directory to determine whether the directory should be shared within your Amazon Web Services organization (<code>ORGANIZATIONS</code>) or with any Amazon Web Services account by sending a directory sharing request (<code>HANDSHAKE</code>).</p>
pub fn share_method(&self) -> std::option::Option<&crate::model::ShareMethod> {
self.share_method.as_ref()
}
}
impl std::fmt::Debug for ShareDirectoryInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ShareDirectoryInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("share_notes", &"*** Sensitive Data Redacted ***");
formatter.field("share_target", &self.share_target);
formatter.field("share_method", &self.share_method);
formatter.finish()
}
}
/// <p>An object representing the inputs for the <code>RestoreFromSnapshot</code> operation.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct RestoreFromSnapshotInput {
/// <p>The identifier of the snapshot to restore from.</p>
pub snapshot_id: std::option::Option<std::string::String>,
}
impl RestoreFromSnapshotInput {
/// <p>The identifier of the snapshot to restore from.</p>
pub fn snapshot_id(&self) -> std::option::Option<&str> {
self.snapshot_id.as_deref()
}
}
impl std::fmt::Debug for RestoreFromSnapshotInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("RestoreFromSnapshotInput");
formatter.field("snapshot_id", &self.snapshot_id);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ResetUserPasswordInput {
/// <p>Identifier of the Managed Microsoft AD or Simple AD directory in which the user resides.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The user name of the user whose password will be reset.</p>
pub user_name: std::option::Option<std::string::String>,
/// <p>The new password that will be reset.</p>
pub new_password: std::option::Option<std::string::String>,
}
impl ResetUserPasswordInput {
/// <p>Identifier of the Managed Microsoft AD or Simple AD directory in which the user resides.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The user name of the user whose password will be reset.</p>
pub fn user_name(&self) -> std::option::Option<&str> {
self.user_name.as_deref()
}
/// <p>The new password that will be reset.</p>
pub fn new_password(&self) -> std::option::Option<&str> {
self.new_password.as_deref()
}
}
impl std::fmt::Debug for ResetUserPasswordInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ResetUserPasswordInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("user_name", &self.user_name);
formatter.field("new_password", &"*** Sensitive Data Redacted ***");
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct RemoveTagsFromResourceInput {
/// <p>Identifier (ID) of the directory from which to remove the tag.</p>
pub resource_id: std::option::Option<std::string::String>,
/// <p>The tag key (name) of the tag to be removed.</p>
pub tag_keys: std::option::Option<std::vec::Vec<std::string::String>>,
}
impl RemoveTagsFromResourceInput {
/// <p>Identifier (ID) of the directory from which to remove the tag.</p>
pub fn resource_id(&self) -> std::option::Option<&str> {
self.resource_id.as_deref()
}
/// <p>The tag key (name) of the tag to be removed.</p>
pub fn tag_keys(&self) -> std::option::Option<&[std::string::String]> {
self.tag_keys.as_deref()
}
}
impl std::fmt::Debug for RemoveTagsFromResourceInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("RemoveTagsFromResourceInput");
formatter.field("resource_id", &self.resource_id);
formatter.field("tag_keys", &self.tag_keys);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct RemoveRegionInput {
/// <p>The identifier of the directory for which you want to remove Region replication.</p>
pub directory_id: std::option::Option<std::string::String>,
}
impl RemoveRegionInput {
/// <p>The identifier of the directory for which you want to remove Region replication.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
}
impl std::fmt::Debug for RemoveRegionInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("RemoveRegionInput");
formatter.field("directory_id", &self.directory_id);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct RemoveIpRoutesInput {
/// <p>Identifier (ID) of the directory from which you want to remove the IP addresses.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>IP address blocks that you want to remove.</p>
pub cidr_ips: std::option::Option<std::vec::Vec<std::string::String>>,
}
impl RemoveIpRoutesInput {
/// <p>Identifier (ID) of the directory from which you want to remove the IP addresses.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>IP address blocks that you want to remove.</p>
pub fn cidr_ips(&self) -> std::option::Option<&[std::string::String]> {
self.cidr_ips.as_deref()
}
}
impl std::fmt::Debug for RemoveIpRoutesInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("RemoveIpRoutesInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("cidr_ips", &self.cidr_ips);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct RejectSharedDirectoryInput {
/// <p>Identifier of the shared directory in the directory consumer account. This identifier is different for each directory owner account.</p>
pub shared_directory_id: std::option::Option<std::string::String>,
}
impl RejectSharedDirectoryInput {
/// <p>Identifier of the shared directory in the directory consumer account. This identifier is different for each directory owner account.</p>
pub fn shared_directory_id(&self) -> std::option::Option<&str> {
self.shared_directory_id.as_deref()
}
}
impl std::fmt::Debug for RejectSharedDirectoryInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("RejectSharedDirectoryInput");
formatter.field("shared_directory_id", &self.shared_directory_id);
formatter.finish()
}
}
/// <p>Registers a new event topic.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct RegisterEventTopicInput {
/// <p>The Directory ID that will publish status messages to the Amazon SNS topic.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The Amazon SNS topic name to which the directory will publish status messages. This Amazon SNS topic must be in the same region as the specified Directory ID.</p>
pub topic_name: std::option::Option<std::string::String>,
}
impl RegisterEventTopicInput {
/// <p>The Directory ID that will publish status messages to the Amazon SNS topic.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The Amazon SNS topic name to which the directory will publish status messages. This Amazon SNS topic must be in the same region as the specified Directory ID.</p>
pub fn topic_name(&self) -> std::option::Option<&str> {
self.topic_name.as_deref()
}
}
impl std::fmt::Debug for RegisterEventTopicInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("RegisterEventTopicInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("topic_name", &self.topic_name);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct RegisterCertificateInput {
/// <p>The identifier of the directory.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The certificate PEM string that needs to be registered.</p>
pub certificate_data: std::option::Option<std::string::String>,
/// <p>The function that the registered certificate performs. Valid values include <code>ClientLDAPS</code> or <code>ClientCertAuth</code>. The default value is <code>ClientLDAPS</code>.</p>
pub r#type: std::option::Option<crate::model::CertificateType>,
/// <p>A <code>ClientCertAuthSettings</code> object that contains client certificate authentication settings.</p>
pub client_cert_auth_settings: std::option::Option<crate::model::ClientCertAuthSettings>,
}
impl RegisterCertificateInput {
/// <p>The identifier of the directory.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The certificate PEM string that needs to be registered.</p>
pub fn certificate_data(&self) -> std::option::Option<&str> {
self.certificate_data.as_deref()
}
/// <p>The function that the registered certificate performs. Valid values include <code>ClientLDAPS</code> or <code>ClientCertAuth</code>. The default value is <code>ClientLDAPS</code>.</p>
pub fn r#type(&self) -> std::option::Option<&crate::model::CertificateType> {
self.r#type.as_ref()
}
/// <p>A <code>ClientCertAuthSettings</code> object that contains client certificate authentication settings.</p>
pub fn client_cert_auth_settings(
&self,
) -> std::option::Option<&crate::model::ClientCertAuthSettings> {
self.client_cert_auth_settings.as_ref()
}
}
impl std::fmt::Debug for RegisterCertificateInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("RegisterCertificateInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("certificate_data", &self.certificate_data);
formatter.field("r#type", &self.r#type);
formatter.field("client_cert_auth_settings", &self.client_cert_auth_settings);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ListTagsForResourceInput {
/// <p>Identifier (ID) of the directory for which you want to retrieve tags.</p>
pub resource_id: std::option::Option<std::string::String>,
/// <p>Reserved for future use.</p>
pub next_token: std::option::Option<std::string::String>,
/// <p>Reserved for future use.</p>
pub limit: std::option::Option<i32>,
}
impl ListTagsForResourceInput {
/// <p>Identifier (ID) of the directory for which you want to retrieve tags.</p>
pub fn resource_id(&self) -> std::option::Option<&str> {
self.resource_id.as_deref()
}
/// <p>Reserved for future use.</p>
pub fn next_token(&self) -> std::option::Option<&str> {
self.next_token.as_deref()
}
/// <p>Reserved for future use.</p>
pub fn limit(&self) -> std::option::Option<i32> {
self.limit
}
}
impl std::fmt::Debug for ListTagsForResourceInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ListTagsForResourceInput");
formatter.field("resource_id", &self.resource_id);
formatter.field("next_token", &self.next_token);
formatter.field("limit", &self.limit);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ListSchemaExtensionsInput {
/// <p>The identifier of the directory from which to retrieve the schema extension information.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The <code>ListSchemaExtensions.NextToken</code> value from a previous call to <code>ListSchemaExtensions</code>. Pass null if this is the first call.</p>
pub next_token: std::option::Option<std::string::String>,
/// <p>The maximum number of items to return.</p>
pub limit: std::option::Option<i32>,
}
impl ListSchemaExtensionsInput {
/// <p>The identifier of the directory from which to retrieve the schema extension information.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The <code>ListSchemaExtensions.NextToken</code> value from a previous call to <code>ListSchemaExtensions</code>. Pass null if this is the first call.</p>
pub fn next_token(&self) -> std::option::Option<&str> {
self.next_token.as_deref()
}
/// <p>The maximum number of items to return.</p>
pub fn limit(&self) -> std::option::Option<i32> {
self.limit
}
}
impl std::fmt::Debug for ListSchemaExtensionsInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ListSchemaExtensionsInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("next_token", &self.next_token);
formatter.field("limit", &self.limit);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ListLogSubscriptionsInput {
/// <p>If a <i>DirectoryID</i> is provided, lists only the log subscription associated with that directory. If no <i>DirectoryId</i> is provided, lists all log subscriptions associated with your Amazon Web Services account. If there are no log subscriptions for the Amazon Web Services account or the directory, an empty list will be returned.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The token for the next set of items to return.</p>
pub next_token: std::option::Option<std::string::String>,
/// <p>The maximum number of items returned.</p>
pub limit: std::option::Option<i32>,
}
impl ListLogSubscriptionsInput {
/// <p>If a <i>DirectoryID</i> is provided, lists only the log subscription associated with that directory. If no <i>DirectoryId</i> is provided, lists all log subscriptions associated with your Amazon Web Services account. If there are no log subscriptions for the Amazon Web Services account or the directory, an empty list will be returned.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The token for the next set of items to return.</p>
pub fn next_token(&self) -> std::option::Option<&str> {
self.next_token.as_deref()
}
/// <p>The maximum number of items returned.</p>
pub fn limit(&self) -> std::option::Option<i32> {
self.limit
}
}
impl std::fmt::Debug for ListLogSubscriptionsInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ListLogSubscriptionsInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("next_token", &self.next_token);
formatter.field("limit", &self.limit);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ListIpRoutesInput {
/// <p>Identifier (ID) of the directory for which you want to retrieve the IP addresses.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The <i>ListIpRoutes.NextToken</i> value from a previous call to <code>ListIpRoutes</code>. Pass null if this is the first call.</p>
pub next_token: std::option::Option<std::string::String>,
/// <p>Maximum number of items to return. If this value is zero, the maximum number of items is specified by the limitations of the operation.</p>
pub limit: std::option::Option<i32>,
}
impl ListIpRoutesInput {
/// <p>Identifier (ID) of the directory for which you want to retrieve the IP addresses.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The <i>ListIpRoutes.NextToken</i> value from a previous call to <code>ListIpRoutes</code>. Pass null if this is the first call.</p>
pub fn next_token(&self) -> std::option::Option<&str> {
self.next_token.as_deref()
}
/// <p>Maximum number of items to return. If this value is zero, the maximum number of items is specified by the limitations of the operation.</p>
pub fn limit(&self) -> std::option::Option<i32> {
self.limit
}
}
impl std::fmt::Debug for ListIpRoutesInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ListIpRoutesInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("next_token", &self.next_token);
formatter.field("limit", &self.limit);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ListCertificatesInput {
/// <p>The identifier of the directory.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>A token for requesting another page of certificates if the <code>NextToken</code> response element indicates that more certificates are available. Use the value of the returned <code>NextToken</code> element in your request until the token comes back as <code>null</code>. Pass <code>null</code> if this is the first call.</p>
pub next_token: std::option::Option<std::string::String>,
/// <p>The number of items that should show up on one page</p>
pub limit: std::option::Option<i32>,
}
impl ListCertificatesInput {
/// <p>The identifier of the directory.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>A token for requesting another page of certificates if the <code>NextToken</code> response element indicates that more certificates are available. Use the value of the returned <code>NextToken</code> element in your request until the token comes back as <code>null</code>. Pass <code>null</code> if this is the first call.</p>
pub fn next_token(&self) -> std::option::Option<&str> {
self.next_token.as_deref()
}
/// <p>The number of items that should show up on one page</p>
pub fn limit(&self) -> std::option::Option<i32> {
self.limit
}
}
impl std::fmt::Debug for ListCertificatesInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ListCertificatesInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("next_token", &self.next_token);
formatter.field("limit", &self.limit);
formatter.finish()
}
}
/// <p>Contains the inputs for the <code>GetSnapshotLimits</code> operation.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct GetSnapshotLimitsInput {
/// <p>Contains the identifier of the directory to obtain the limits for.</p>
pub directory_id: std::option::Option<std::string::String>,
}
impl GetSnapshotLimitsInput {
/// <p>Contains the identifier of the directory to obtain the limits for.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
}
impl std::fmt::Debug for GetSnapshotLimitsInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("GetSnapshotLimitsInput");
formatter.field("directory_id", &self.directory_id);
formatter.finish()
}
}
/// <p>Contains the inputs for the <code>GetDirectoryLimits</code> operation.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct GetDirectoryLimitsInput {}
impl std::fmt::Debug for GetDirectoryLimitsInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("GetDirectoryLimitsInput");
formatter.finish()
}
}
/// <p>Contains the inputs for the <code>EnableSso</code> operation.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct EnableSsoInput {
/// <p>The identifier of the directory for which to enable single-sign on.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The username of an alternate account to use to enable single-sign on. This is only used for AD Connector directories. This account must have privileges to add a service principal name.</p>
/// <p>If the AD Connector service account does not have privileges to add a service principal name, you can specify an alternate account with the <i>UserName</i> and <i>Password</i> parameters. These credentials are only used to enable single sign-on and are not stored by the service. The AD Connector service account is not changed.</p>
pub user_name: std::option::Option<std::string::String>,
/// <p>The password of an alternate account to use to enable single-sign on. This is only used for AD Connector directories. For more information, see the <i>UserName</i> parameter.</p>
pub password: std::option::Option<std::string::String>,
}
impl EnableSsoInput {
/// <p>The identifier of the directory for which to enable single-sign on.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The username of an alternate account to use to enable single-sign on. This is only used for AD Connector directories. This account must have privileges to add a service principal name.</p>
/// <p>If the AD Connector service account does not have privileges to add a service principal name, you can specify an alternate account with the <i>UserName</i> and <i>Password</i> parameters. These credentials are only used to enable single sign-on and are not stored by the service. The AD Connector service account is not changed.</p>
pub fn user_name(&self) -> std::option::Option<&str> {
self.user_name.as_deref()
}
/// <p>The password of an alternate account to use to enable single-sign on. This is only used for AD Connector directories. For more information, see the <i>UserName</i> parameter.</p>
pub fn password(&self) -> std::option::Option<&str> {
self.password.as_deref()
}
}
impl std::fmt::Debug for EnableSsoInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("EnableSsoInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("user_name", &self.user_name);
formatter.field("password", &"*** Sensitive Data Redacted ***");
formatter.finish()
}
}
/// <p>Contains the inputs for the <code>EnableRadius</code> operation.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct EnableRadiusInput {
/// <p>The identifier of the directory for which to enable MFA.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>A <code>RadiusSettings</code> object that contains information about the RADIUS server.</p>
pub radius_settings: std::option::Option<crate::model::RadiusSettings>,
}
impl EnableRadiusInput {
/// <p>The identifier of the directory for which to enable MFA.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>A <code>RadiusSettings</code> object that contains information about the RADIUS server.</p>
pub fn radius_settings(&self) -> std::option::Option<&crate::model::RadiusSettings> {
self.radius_settings.as_ref()
}
}
impl std::fmt::Debug for EnableRadiusInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("EnableRadiusInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("radius_settings", &self.radius_settings);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct EnableLdapsInput {
/// <p>The identifier of the directory.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The type of LDAP security to enable. Currently only the value <code>Client</code> is supported.</p>
pub r#type: std::option::Option<crate::model::LdapsType>,
}
impl EnableLdapsInput {
/// <p>The identifier of the directory.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The type of LDAP security to enable. Currently only the value <code>Client</code> is supported.</p>
pub fn r#type(&self) -> std::option::Option<&crate::model::LdapsType> {
self.r#type.as_ref()
}
}
impl std::fmt::Debug for EnableLdapsInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("EnableLdapsInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("r#type", &self.r#type);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct EnableClientAuthenticationInput {
/// <p>The identifier of the specified directory. </p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The type of client authentication to enable. Currently only the value <code>SmartCard</code> is supported. Smart card authentication in AD Connector requires that you enable Kerberos Constrained Delegation for the Service User to the LDAP service in your self-managed AD. </p>
pub r#type: std::option::Option<crate::model::ClientAuthenticationType>,
}
impl EnableClientAuthenticationInput {
/// <p>The identifier of the specified directory. </p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The type of client authentication to enable. Currently only the value <code>SmartCard</code> is supported. Smart card authentication in AD Connector requires that you enable Kerberos Constrained Delegation for the Service User to the LDAP service in your self-managed AD. </p>
pub fn r#type(&self) -> std::option::Option<&crate::model::ClientAuthenticationType> {
self.r#type.as_ref()
}
}
impl std::fmt::Debug for EnableClientAuthenticationInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("EnableClientAuthenticationInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("r#type", &self.r#type);
formatter.finish()
}
}
/// <p>Contains the inputs for the <code>DisableSso</code> operation.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DisableSsoInput {
/// <p>The identifier of the directory for which to disable single-sign on.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The username of an alternate account to use to disable single-sign on. This is only used for AD Connector directories. This account must have privileges to remove a service principal name.</p>
/// <p>If the AD Connector service account does not have privileges to remove a service principal name, you can specify an alternate account with the <i>UserName</i> and <i>Password</i> parameters. These credentials are only used to disable single sign-on and are not stored by the service. The AD Connector service account is not changed.</p>
pub user_name: std::option::Option<std::string::String>,
/// <p>The password of an alternate account to use to disable single-sign on. This is only used for AD Connector directories. For more information, see the <i>UserName</i> parameter.</p>
pub password: std::option::Option<std::string::String>,
}
impl DisableSsoInput {
/// <p>The identifier of the directory for which to disable single-sign on.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The username of an alternate account to use to disable single-sign on. This is only used for AD Connector directories. This account must have privileges to remove a service principal name.</p>
/// <p>If the AD Connector service account does not have privileges to remove a service principal name, you can specify an alternate account with the <i>UserName</i> and <i>Password</i> parameters. These credentials are only used to disable single sign-on and are not stored by the service. The AD Connector service account is not changed.</p>
pub fn user_name(&self) -> std::option::Option<&str> {
self.user_name.as_deref()
}
/// <p>The password of an alternate account to use to disable single-sign on. This is only used for AD Connector directories. For more information, see the <i>UserName</i> parameter.</p>
pub fn password(&self) -> std::option::Option<&str> {
self.password.as_deref()
}
}
impl std::fmt::Debug for DisableSsoInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DisableSsoInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("user_name", &self.user_name);
formatter.field("password", &"*** Sensitive Data Redacted ***");
formatter.finish()
}
}
/// <p>Contains the inputs for the <code>DisableRadius</code> operation.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DisableRadiusInput {
/// <p>The identifier of the directory for which to disable MFA.</p>
pub directory_id: std::option::Option<std::string::String>,
}
impl DisableRadiusInput {
/// <p>The identifier of the directory for which to disable MFA.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
}
impl std::fmt::Debug for DisableRadiusInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DisableRadiusInput");
formatter.field("directory_id", &self.directory_id);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DisableLdapsInput {
/// <p>The identifier of the directory.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The type of LDAP security to enable. Currently only the value <code>Client</code> is supported.</p>
pub r#type: std::option::Option<crate::model::LdapsType>,
}
impl DisableLdapsInput {
/// <p>The identifier of the directory.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The type of LDAP security to enable. Currently only the value <code>Client</code> is supported.</p>
pub fn r#type(&self) -> std::option::Option<&crate::model::LdapsType> {
self.r#type.as_ref()
}
}
impl std::fmt::Debug for DisableLdapsInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DisableLdapsInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("r#type", &self.r#type);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DisableClientAuthenticationInput {
/// <p>The identifier of the directory </p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The type of client authentication to disable. Currently, only the parameter, <code>SmartCard</code> is supported.</p>
pub r#type: std::option::Option<crate::model::ClientAuthenticationType>,
}
impl DisableClientAuthenticationInput {
/// <p>The identifier of the directory </p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The type of client authentication to disable. Currently, only the parameter, <code>SmartCard</code> is supported.</p>
pub fn r#type(&self) -> std::option::Option<&crate::model::ClientAuthenticationType> {
self.r#type.as_ref()
}
}
impl std::fmt::Debug for DisableClientAuthenticationInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DisableClientAuthenticationInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("r#type", &self.r#type);
formatter.finish()
}
}
/// <p>Describes the trust relationships for a particular Managed Microsoft AD directory. If no input parameters are provided, such as directory ID or trust ID, this request describes all the trust relationships.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DescribeTrustsInput {
/// <p>The Directory ID of the Amazon Web Services directory that is a part of the requested trust relationship.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>A list of identifiers of the trust relationships for which to obtain the information. If this member is null, all trust relationships that belong to the current account are returned.</p>
/// <p>An empty list results in an <code>InvalidParameterException</code> being thrown.</p>
pub trust_ids: std::option::Option<std::vec::Vec<std::string::String>>,
/// <p>The <i>DescribeTrustsResult.NextToken</i> value from a previous call to <code>DescribeTrusts</code>. Pass null if this is the first call.</p>
pub next_token: std::option::Option<std::string::String>,
/// <p>The maximum number of objects to return.</p>
pub limit: std::option::Option<i32>,
}
impl DescribeTrustsInput {
/// <p>The Directory ID of the Amazon Web Services directory that is a part of the requested trust relationship.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>A list of identifiers of the trust relationships for which to obtain the information. If this member is null, all trust relationships that belong to the current account are returned.</p>
/// <p>An empty list results in an <code>InvalidParameterException</code> being thrown.</p>
pub fn trust_ids(&self) -> std::option::Option<&[std::string::String]> {
self.trust_ids.as_deref()
}
/// <p>The <i>DescribeTrustsResult.NextToken</i> value from a previous call to <code>DescribeTrusts</code>. Pass null if this is the first call.</p>
pub fn next_token(&self) -> std::option::Option<&str> {
self.next_token.as_deref()
}
/// <p>The maximum number of objects to return.</p>
pub fn limit(&self) -> std::option::Option<i32> {
self.limit
}
}
impl std::fmt::Debug for DescribeTrustsInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DescribeTrustsInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("trust_ids", &self.trust_ids);
formatter.field("next_token", &self.next_token);
formatter.field("limit", &self.limit);
formatter.finish()
}
}
/// <p>Contains the inputs for the <code>DescribeSnapshots</code> operation.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DescribeSnapshotsInput {
/// <p>The identifier of the directory for which to retrieve snapshot information.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>A list of identifiers of the snapshots to obtain the information for. If this member is null or empty, all snapshots are returned using the <i>Limit</i> and <i>NextToken</i> members.</p>
pub snapshot_ids: std::option::Option<std::vec::Vec<std::string::String>>,
/// <p>The <i>DescribeSnapshotsResult.NextToken</i> value from a previous call to <code>DescribeSnapshots</code>. Pass null if this is the first call.</p>
pub next_token: std::option::Option<std::string::String>,
/// <p>The maximum number of objects to return.</p>
pub limit: std::option::Option<i32>,
}
impl DescribeSnapshotsInput {
/// <p>The identifier of the directory for which to retrieve snapshot information.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>A list of identifiers of the snapshots to obtain the information for. If this member is null or empty, all snapshots are returned using the <i>Limit</i> and <i>NextToken</i> members.</p>
pub fn snapshot_ids(&self) -> std::option::Option<&[std::string::String]> {
self.snapshot_ids.as_deref()
}
/// <p>The <i>DescribeSnapshotsResult.NextToken</i> value from a previous call to <code>DescribeSnapshots</code>. Pass null if this is the first call.</p>
pub fn next_token(&self) -> std::option::Option<&str> {
self.next_token.as_deref()
}
/// <p>The maximum number of objects to return.</p>
pub fn limit(&self) -> std::option::Option<i32> {
self.limit
}
}
impl std::fmt::Debug for DescribeSnapshotsInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DescribeSnapshotsInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("snapshot_ids", &self.snapshot_ids);
formatter.field("next_token", &self.next_token);
formatter.field("limit", &self.limit);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DescribeSharedDirectoriesInput {
/// <p>Returns the identifier of the directory in the directory owner account. </p>
pub owner_directory_id: std::option::Option<std::string::String>,
/// <p>A list of identifiers of all shared directories in your account. </p>
pub shared_directory_ids: std::option::Option<std::vec::Vec<std::string::String>>,
/// <p>The <code>DescribeSharedDirectoriesResult.NextToken</code> value from a previous call to <code>DescribeSharedDirectories</code>. Pass null if this is the first call. </p>
pub next_token: std::option::Option<std::string::String>,
/// <p>The number of shared directories to return in the response object.</p>
pub limit: std::option::Option<i32>,
}
impl DescribeSharedDirectoriesInput {
/// <p>Returns the identifier of the directory in the directory owner account. </p>
pub fn owner_directory_id(&self) -> std::option::Option<&str> {
self.owner_directory_id.as_deref()
}
/// <p>A list of identifiers of all shared directories in your account. </p>
pub fn shared_directory_ids(&self) -> std::option::Option<&[std::string::String]> {
self.shared_directory_ids.as_deref()
}
/// <p>The <code>DescribeSharedDirectoriesResult.NextToken</code> value from a previous call to <code>DescribeSharedDirectories</code>. Pass null if this is the first call. </p>
pub fn next_token(&self) -> std::option::Option<&str> {
self.next_token.as_deref()
}
/// <p>The number of shared directories to return in the response object.</p>
pub fn limit(&self) -> std::option::Option<i32> {
self.limit
}
}
impl std::fmt::Debug for DescribeSharedDirectoriesInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DescribeSharedDirectoriesInput");
formatter.field("owner_directory_id", &self.owner_directory_id);
formatter.field("shared_directory_ids", &self.shared_directory_ids);
formatter.field("next_token", &self.next_token);
formatter.field("limit", &self.limit);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DescribeRegionsInput {
/// <p>The identifier of the directory.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The name of the Region. For example, <code>us-east-1</code>.</p>
pub region_name: std::option::Option<std::string::String>,
/// <p>The <code>DescribeRegionsResult.NextToken</code> value from a previous call to <code>DescribeRegions</code>. Pass null if this is the first call.</p>
pub next_token: std::option::Option<std::string::String>,
}
impl DescribeRegionsInput {
/// <p>The identifier of the directory.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The name of the Region. For example, <code>us-east-1</code>.</p>
pub fn region_name(&self) -> std::option::Option<&str> {
self.region_name.as_deref()
}
/// <p>The <code>DescribeRegionsResult.NextToken</code> value from a previous call to <code>DescribeRegions</code>. Pass null if this is the first call.</p>
pub fn next_token(&self) -> std::option::Option<&str> {
self.next_token.as_deref()
}
}
impl std::fmt::Debug for DescribeRegionsInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DescribeRegionsInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("region_name", &self.region_name);
formatter.field("next_token", &self.next_token);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DescribeLdapsSettingsInput {
/// <p>The identifier of the directory.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The type of LDAP security to enable. Currently only the value <code>Client</code> is supported.</p>
pub r#type: std::option::Option<crate::model::LdapsType>,
/// <p>The type of next token used for pagination.</p>
pub next_token: std::option::Option<std::string::String>,
/// <p>Specifies the number of items that should be displayed on one page.</p>
pub limit: std::option::Option<i32>,
}
impl DescribeLdapsSettingsInput {
/// <p>The identifier of the directory.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The type of LDAP security to enable. Currently only the value <code>Client</code> is supported.</p>
pub fn r#type(&self) -> std::option::Option<&crate::model::LdapsType> {
self.r#type.as_ref()
}
/// <p>The type of next token used for pagination.</p>
pub fn next_token(&self) -> std::option::Option<&str> {
self.next_token.as_deref()
}
/// <p>Specifies the number of items that should be displayed on one page.</p>
pub fn limit(&self) -> std::option::Option<i32> {
self.limit
}
}
impl std::fmt::Debug for DescribeLdapsSettingsInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DescribeLdapsSettingsInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("r#type", &self.r#type);
formatter.field("next_token", &self.next_token);
formatter.field("limit", &self.limit);
formatter.finish()
}
}
/// <p>Describes event topics.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DescribeEventTopicsInput {
/// <p>The Directory ID for which to get the list of associated Amazon SNS topics. If this member is null, associations for all Directory IDs are returned.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>A list of Amazon SNS topic names for which to obtain the information. If this member is null, all associations for the specified Directory ID are returned.</p>
/// <p>An empty list results in an <code>InvalidParameterException</code> being thrown.</p>
pub topic_names: std::option::Option<std::vec::Vec<std::string::String>>,
}
impl DescribeEventTopicsInput {
/// <p>The Directory ID for which to get the list of associated Amazon SNS topics. If this member is null, associations for all Directory IDs are returned.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>A list of Amazon SNS topic names for which to obtain the information. If this member is null, all associations for the specified Directory ID are returned.</p>
/// <p>An empty list results in an <code>InvalidParameterException</code> being thrown.</p>
pub fn topic_names(&self) -> std::option::Option<&[std::string::String]> {
self.topic_names.as_deref()
}
}
impl std::fmt::Debug for DescribeEventTopicsInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DescribeEventTopicsInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("topic_names", &self.topic_names);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DescribeDomainControllersInput {
/// <p>Identifier of the directory for which to retrieve the domain controller information.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>A list of identifiers for the domain controllers whose information will be provided.</p>
pub domain_controller_ids: std::option::Option<std::vec::Vec<std::string::String>>,
/// <p>The <i>DescribeDomainControllers.NextToken</i> value from a previous call to <code>DescribeDomainControllers</code>. Pass null if this is the first call. </p>
pub next_token: std::option::Option<std::string::String>,
/// <p>The maximum number of items to return.</p>
pub limit: std::option::Option<i32>,
}
impl DescribeDomainControllersInput {
/// <p>Identifier of the directory for which to retrieve the domain controller information.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>A list of identifiers for the domain controllers whose information will be provided.</p>
pub fn domain_controller_ids(&self) -> std::option::Option<&[std::string::String]> {
self.domain_controller_ids.as_deref()
}
/// <p>The <i>DescribeDomainControllers.NextToken</i> value from a previous call to <code>DescribeDomainControllers</code>. Pass null if this is the first call. </p>
pub fn next_token(&self) -> std::option::Option<&str> {
self.next_token.as_deref()
}
/// <p>The maximum number of items to return.</p>
pub fn limit(&self) -> std::option::Option<i32> {
self.limit
}
}
impl std::fmt::Debug for DescribeDomainControllersInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DescribeDomainControllersInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("domain_controller_ids", &self.domain_controller_ids);
formatter.field("next_token", &self.next_token);
formatter.field("limit", &self.limit);
formatter.finish()
}
}
/// <p>Contains the inputs for the <code>DescribeDirectories</code> operation.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DescribeDirectoriesInput {
/// <p>A list of identifiers of the directories for which to obtain the information. If this member is null, all directories that belong to the current account are returned.</p>
/// <p>An empty list results in an <code>InvalidParameterException</code> being thrown.</p>
pub directory_ids: std::option::Option<std::vec::Vec<std::string::String>>,
/// <p>The <code>DescribeDirectoriesResult.NextToken</code> value from a previous call to <code>DescribeDirectories</code>. Pass null if this is the first call.</p>
pub next_token: std::option::Option<std::string::String>,
/// <p>The maximum number of items to return. If this value is zero, the maximum number of items is specified by the limitations of the operation.</p>
pub limit: std::option::Option<i32>,
}
impl DescribeDirectoriesInput {
/// <p>A list of identifiers of the directories for which to obtain the information. If this member is null, all directories that belong to the current account are returned.</p>
/// <p>An empty list results in an <code>InvalidParameterException</code> being thrown.</p>
pub fn directory_ids(&self) -> std::option::Option<&[std::string::String]> {
self.directory_ids.as_deref()
}
/// <p>The <code>DescribeDirectoriesResult.NextToken</code> value from a previous call to <code>DescribeDirectories</code>. Pass null if this is the first call.</p>
pub fn next_token(&self) -> std::option::Option<&str> {
self.next_token.as_deref()
}
/// <p>The maximum number of items to return. If this value is zero, the maximum number of items is specified by the limitations of the operation.</p>
pub fn limit(&self) -> std::option::Option<i32> {
self.limit
}
}
impl std::fmt::Debug for DescribeDirectoriesInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DescribeDirectoriesInput");
formatter.field("directory_ids", &self.directory_ids);
formatter.field("next_token", &self.next_token);
formatter.field("limit", &self.limit);
formatter.finish()
}
}
/// <p>Describes a conditional forwarder.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DescribeConditionalForwardersInput {
/// <p>The directory ID for which to get the list of associated conditional forwarders.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The fully qualified domain names (FQDN) of the remote domains for which to get the list of associated conditional forwarders. If this member is null, all conditional forwarders are returned.</p>
pub remote_domain_names: std::option::Option<std::vec::Vec<std::string::String>>,
}
impl DescribeConditionalForwardersInput {
/// <p>The directory ID for which to get the list of associated conditional forwarders.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The fully qualified domain names (FQDN) of the remote domains for which to get the list of associated conditional forwarders. If this member is null, all conditional forwarders are returned.</p>
pub fn remote_domain_names(&self) -> std::option::Option<&[std::string::String]> {
self.remote_domain_names.as_deref()
}
}
impl std::fmt::Debug for DescribeConditionalForwardersInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DescribeConditionalForwardersInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("remote_domain_names", &self.remote_domain_names);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DescribeClientAuthenticationSettingsInput {
/// <p>The identifier of the directory for which to retrieve information.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The type of client authentication for which to retrieve information. If no type is specified, a list of all client authentication types that are supported for the specified directory is retrieved.</p>
pub r#type: std::option::Option<crate::model::ClientAuthenticationType>,
/// <p>The <i>DescribeClientAuthenticationSettingsResult.NextToken</i> value from a previous call to <code>DescribeClientAuthenticationSettings</code>. Pass null if this is the first call.</p>
pub next_token: std::option::Option<std::string::String>,
/// <p>The maximum number of items to return. If this value is zero, the maximum number of items is specified by the limitations of the operation. </p>
pub limit: std::option::Option<i32>,
}
impl DescribeClientAuthenticationSettingsInput {
/// <p>The identifier of the directory for which to retrieve information.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The type of client authentication for which to retrieve information. If no type is specified, a list of all client authentication types that are supported for the specified directory is retrieved.</p>
pub fn r#type(&self) -> std::option::Option<&crate::model::ClientAuthenticationType> {
self.r#type.as_ref()
}
/// <p>The <i>DescribeClientAuthenticationSettingsResult.NextToken</i> value from a previous call to <code>DescribeClientAuthenticationSettings</code>. Pass null if this is the first call.</p>
pub fn next_token(&self) -> std::option::Option<&str> {
self.next_token.as_deref()
}
/// <p>The maximum number of items to return. If this value is zero, the maximum number of items is specified by the limitations of the operation. </p>
pub fn limit(&self) -> std::option::Option<i32> {
self.limit
}
}
impl std::fmt::Debug for DescribeClientAuthenticationSettingsInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DescribeClientAuthenticationSettingsInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("r#type", &self.r#type);
formatter.field("next_token", &self.next_token);
formatter.field("limit", &self.limit);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DescribeCertificateInput {
/// <p>The identifier of the directory.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The identifier of the certificate.</p>
pub certificate_id: std::option::Option<std::string::String>,
}
impl DescribeCertificateInput {
/// <p>The identifier of the directory.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The identifier of the certificate.</p>
pub fn certificate_id(&self) -> std::option::Option<&str> {
self.certificate_id.as_deref()
}
}
impl std::fmt::Debug for DescribeCertificateInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DescribeCertificateInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("certificate_id", &self.certificate_id);
formatter.finish()
}
}
/// <p>Removes the specified directory as a publisher to the specified Amazon SNS topic.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DeregisterEventTopicInput {
/// <p>The Directory ID to remove as a publisher. This directory will no longer send messages to the specified Amazon SNS topic.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The name of the Amazon SNS topic from which to remove the directory as a publisher.</p>
pub topic_name: std::option::Option<std::string::String>,
}
impl DeregisterEventTopicInput {
/// <p>The Directory ID to remove as a publisher. This directory will no longer send messages to the specified Amazon SNS topic.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The name of the Amazon SNS topic from which to remove the directory as a publisher.</p>
pub fn topic_name(&self) -> std::option::Option<&str> {
self.topic_name.as_deref()
}
}
impl std::fmt::Debug for DeregisterEventTopicInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DeregisterEventTopicInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("topic_name", &self.topic_name);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DeregisterCertificateInput {
/// <p>The identifier of the directory.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The identifier of the certificate.</p>
pub certificate_id: std::option::Option<std::string::String>,
}
impl DeregisterCertificateInput {
/// <p>The identifier of the directory.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The identifier of the certificate.</p>
pub fn certificate_id(&self) -> std::option::Option<&str> {
self.certificate_id.as_deref()
}
}
impl std::fmt::Debug for DeregisterCertificateInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DeregisterCertificateInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("certificate_id", &self.certificate_id);
formatter.finish()
}
}
/// <p>Deletes the local side of an existing trust relationship between the Managed Microsoft AD directory and the external domain.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DeleteTrustInput {
/// <p>The Trust ID of the trust relationship to be deleted.</p>
pub trust_id: std::option::Option<std::string::String>,
/// <p>Delete a conditional forwarder as part of a DeleteTrustRequest.</p>
pub delete_associated_conditional_forwarder: bool,
}
impl DeleteTrustInput {
/// <p>The Trust ID of the trust relationship to be deleted.</p>
pub fn trust_id(&self) -> std::option::Option<&str> {
self.trust_id.as_deref()
}
/// <p>Delete a conditional forwarder as part of a DeleteTrustRequest.</p>
pub fn delete_associated_conditional_forwarder(&self) -> bool {
self.delete_associated_conditional_forwarder
}
}
impl std::fmt::Debug for DeleteTrustInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DeleteTrustInput");
formatter.field("trust_id", &self.trust_id);
formatter.field(
"delete_associated_conditional_forwarder",
&self.delete_associated_conditional_forwarder,
);
formatter.finish()
}
}
/// <p>Contains the inputs for the <code>DeleteSnapshot</code> operation.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DeleteSnapshotInput {
/// <p>The identifier of the directory snapshot to be deleted.</p>
pub snapshot_id: std::option::Option<std::string::String>,
}
impl DeleteSnapshotInput {
/// <p>The identifier of the directory snapshot to be deleted.</p>
pub fn snapshot_id(&self) -> std::option::Option<&str> {
self.snapshot_id.as_deref()
}
}
impl std::fmt::Debug for DeleteSnapshotInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DeleteSnapshotInput");
formatter.field("snapshot_id", &self.snapshot_id);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DeleteLogSubscriptionInput {
/// <p>Identifier of the directory whose log subscription you want to delete.</p>
pub directory_id: std::option::Option<std::string::String>,
}
impl DeleteLogSubscriptionInput {
/// <p>Identifier of the directory whose log subscription you want to delete.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
}
impl std::fmt::Debug for DeleteLogSubscriptionInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DeleteLogSubscriptionInput");
formatter.field("directory_id", &self.directory_id);
formatter.finish()
}
}
/// <p>Contains the inputs for the <code>DeleteDirectory</code> operation.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DeleteDirectoryInput {
/// <p>The identifier of the directory to delete.</p>
pub directory_id: std::option::Option<std::string::String>,
}
impl DeleteDirectoryInput {
/// <p>The identifier of the directory to delete.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
}
impl std::fmt::Debug for DeleteDirectoryInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DeleteDirectoryInput");
formatter.field("directory_id", &self.directory_id);
formatter.finish()
}
}
/// <p>Deletes a conditional forwarder.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DeleteConditionalForwarderInput {
/// <p>The directory ID for which you are deleting the conditional forwarder.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The fully qualified domain name (FQDN) of the remote domain with which you are deleting the conditional forwarder.</p>
pub remote_domain_name: std::option::Option<std::string::String>,
}
impl DeleteConditionalForwarderInput {
/// <p>The directory ID for which you are deleting the conditional forwarder.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The fully qualified domain name (FQDN) of the remote domain with which you are deleting the conditional forwarder.</p>
pub fn remote_domain_name(&self) -> std::option::Option<&str> {
self.remote_domain_name.as_deref()
}
}
impl std::fmt::Debug for DeleteConditionalForwarderInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DeleteConditionalForwarderInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("remote_domain_name", &self.remote_domain_name);
formatter.finish()
}
}
/// <p>Directory Service for Microsoft Active Directory allows you to configure trust relationships. For example, you can establish a trust between your Managed Microsoft AD directory, and your existing self-managed Microsoft Active Directory. This would allow you to provide users and groups access to resources in either domain, with a single set of credentials.</p>
/// <p>This action initiates the creation of the Amazon Web Services side of a trust relationship between an Managed Microsoft AD directory and an external domain.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct CreateTrustInput {
/// <p>The Directory ID of the Managed Microsoft AD directory for which to establish the trust relationship.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The Fully Qualified Domain Name (FQDN) of the external domain for which to create the trust relationship.</p>
pub remote_domain_name: std::option::Option<std::string::String>,
/// <p>The trust password. The must be the same password that was used when creating the trust relationship on the external domain.</p>
pub trust_password: std::option::Option<std::string::String>,
/// <p>The direction of the trust relationship.</p>
pub trust_direction: std::option::Option<crate::model::TrustDirection>,
/// <p>The trust relationship type. <code>Forest</code> is the default.</p>
pub trust_type: std::option::Option<crate::model::TrustType>,
/// <p>The IP addresses of the remote DNS server associated with RemoteDomainName.</p>
pub conditional_forwarder_ip_addrs: std::option::Option<std::vec::Vec<std::string::String>>,
/// <p>Optional parameter to enable selective authentication for the trust.</p>
pub selective_auth: std::option::Option<crate::model::SelectiveAuth>,
}
impl CreateTrustInput {
/// <p>The Directory ID of the Managed Microsoft AD directory for which to establish the trust relationship.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The Fully Qualified Domain Name (FQDN) of the external domain for which to create the trust relationship.</p>
pub fn remote_domain_name(&self) -> std::option::Option<&str> {
self.remote_domain_name.as_deref()
}
/// <p>The trust password. The must be the same password that was used when creating the trust relationship on the external domain.</p>
pub fn trust_password(&self) -> std::option::Option<&str> {
self.trust_password.as_deref()
}
/// <p>The direction of the trust relationship.</p>
pub fn trust_direction(&self) -> std::option::Option<&crate::model::TrustDirection> {
self.trust_direction.as_ref()
}
/// <p>The trust relationship type. <code>Forest</code> is the default.</p>
pub fn trust_type(&self) -> std::option::Option<&crate::model::TrustType> {
self.trust_type.as_ref()
}
/// <p>The IP addresses of the remote DNS server associated with RemoteDomainName.</p>
pub fn conditional_forwarder_ip_addrs(&self) -> std::option::Option<&[std::string::String]> {
self.conditional_forwarder_ip_addrs.as_deref()
}
/// <p>Optional parameter to enable selective authentication for the trust.</p>
pub fn selective_auth(&self) -> std::option::Option<&crate::model::SelectiveAuth> {
self.selective_auth.as_ref()
}
}
impl std::fmt::Debug for CreateTrustInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("CreateTrustInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("remote_domain_name", &self.remote_domain_name);
formatter.field("trust_password", &"*** Sensitive Data Redacted ***");
formatter.field("trust_direction", &self.trust_direction);
formatter.field("trust_type", &self.trust_type);
formatter.field(
"conditional_forwarder_ip_addrs",
&self.conditional_forwarder_ip_addrs,
);
formatter.field("selective_auth", &self.selective_auth);
formatter.finish()
}
}
/// <p>Contains the inputs for the <code>CreateSnapshot</code> operation.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct CreateSnapshotInput {
/// <p>The identifier of the directory of which to take a snapshot.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The descriptive name to apply to the snapshot.</p>
pub name: std::option::Option<std::string::String>,
}
impl CreateSnapshotInput {
/// <p>The identifier of the directory of which to take a snapshot.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The descriptive name to apply to the snapshot.</p>
pub fn name(&self) -> std::option::Option<&str> {
self.name.as_deref()
}
}
impl std::fmt::Debug for CreateSnapshotInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("CreateSnapshotInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("name", &self.name);
formatter.finish()
}
}
/// <p>Creates an Managed Microsoft AD directory.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct CreateMicrosoftAdInput {
/// <p>The fully qualified domain name for the Managed Microsoft AD directory, such as <code>corp.example.com</code>. This name will resolve inside your VPC only. It does not need to be publicly resolvable.</p>
pub name: std::option::Option<std::string::String>,
/// <p>The NetBIOS name for your domain, such as <code>CORP</code>. If you don't specify a NetBIOS name, it will default to the first part of your directory DNS. For example, <code>CORP</code> for the directory DNS <code>corp.example.com</code>. </p>
pub short_name: std::option::Option<std::string::String>,
/// <p>The password for the default administrative user named <code>Admin</code>.</p>
/// <p>If you need to change the password for the administrator account, you can use the <code>ResetUserPassword</code> API call.</p>
pub password: std::option::Option<std::string::String>,
/// <p>A description for the directory. This label will appear on the Amazon Web Services console <code>Directory Details</code> page after the directory is created.</p>
pub description: std::option::Option<std::string::String>,
/// <p>Contains VPC information for the <code>CreateDirectory</code> or <code>CreateMicrosoftAD</code> operation.</p>
pub vpc_settings: std::option::Option<crate::model::DirectoryVpcSettings>,
/// <p>Managed Microsoft AD is available in two editions: <code>Standard</code> and <code>Enterprise</code>. <code>Enterprise</code> is the default.</p>
pub edition: std::option::Option<crate::model::DirectoryEdition>,
/// <p>The tags to be assigned to the Managed Microsoft AD directory.</p>
pub tags: std::option::Option<std::vec::Vec<crate::model::Tag>>,
}
impl CreateMicrosoftAdInput {
/// <p>The fully qualified domain name for the Managed Microsoft AD directory, such as <code>corp.example.com</code>. This name will resolve inside your VPC only. It does not need to be publicly resolvable.</p>
pub fn name(&self) -> std::option::Option<&str> {
self.name.as_deref()
}
/// <p>The NetBIOS name for your domain, such as <code>CORP</code>. If you don't specify a NetBIOS name, it will default to the first part of your directory DNS. For example, <code>CORP</code> for the directory DNS <code>corp.example.com</code>. </p>
pub fn short_name(&self) -> std::option::Option<&str> {
self.short_name.as_deref()
}
/// <p>The password for the default administrative user named <code>Admin</code>.</p>
/// <p>If you need to change the password for the administrator account, you can use the <code>ResetUserPassword</code> API call.</p>
pub fn password(&self) -> std::option::Option<&str> {
self.password.as_deref()
}
/// <p>A description for the directory. This label will appear on the Amazon Web Services console <code>Directory Details</code> page after the directory is created.</p>
pub fn description(&self) -> std::option::Option<&str> {
self.description.as_deref()
}
/// <p>Contains VPC information for the <code>CreateDirectory</code> or <code>CreateMicrosoftAD</code> operation.</p>
pub fn vpc_settings(&self) -> std::option::Option<&crate::model::DirectoryVpcSettings> {
self.vpc_settings.as_ref()
}
/// <p>Managed Microsoft AD is available in two editions: <code>Standard</code> and <code>Enterprise</code>. <code>Enterprise</code> is the default.</p>
pub fn edition(&self) -> std::option::Option<&crate::model::DirectoryEdition> {
self.edition.as_ref()
}
/// <p>The tags to be assigned to the Managed Microsoft AD directory.</p>
pub fn tags(&self) -> std::option::Option<&[crate::model::Tag]> {
self.tags.as_deref()
}
}
impl std::fmt::Debug for CreateMicrosoftAdInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("CreateMicrosoftAdInput");
formatter.field("name", &self.name);
formatter.field("short_name", &self.short_name);
formatter.field("password", &"*** Sensitive Data Redacted ***");
formatter.field("description", &self.description);
formatter.field("vpc_settings", &self.vpc_settings);
formatter.field("edition", &self.edition);
formatter.field("tags", &self.tags);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct CreateLogSubscriptionInput {
/// <p>Identifier of the directory to which you want to subscribe and receive real-time logs to your specified CloudWatch log group.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The name of the CloudWatch log group where the real-time domain controller logs are forwarded.</p>
pub log_group_name: std::option::Option<std::string::String>,
}
impl CreateLogSubscriptionInput {
/// <p>Identifier of the directory to which you want to subscribe and receive real-time logs to your specified CloudWatch log group.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The name of the CloudWatch log group where the real-time domain controller logs are forwarded.</p>
pub fn log_group_name(&self) -> std::option::Option<&str> {
self.log_group_name.as_deref()
}
}
impl std::fmt::Debug for CreateLogSubscriptionInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("CreateLogSubscriptionInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("log_group_name", &self.log_group_name);
formatter.finish()
}
}
/// <p>Contains the inputs for the <code>CreateDirectory</code> operation. </p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct CreateDirectoryInput {
/// <p>The fully qualified name for the directory, such as <code>corp.example.com</code>.</p>
pub name: std::option::Option<std::string::String>,
/// <p>The NetBIOS name of the directory, such as <code>CORP</code>.</p>
pub short_name: std::option::Option<std::string::String>,
/// <p>The password for the directory administrator. The directory creation process creates a directory administrator account with the user name <code>Administrator</code> and this password.</p>
/// <p>If you need to change the password for the administrator account, you can use the <code>ResetUserPassword</code> API call.</p>
/// <p>The regex pattern for this string is made up of the following conditions:</p>
/// <ul>
/// <li> <p>Length (?=^.{8,64}$) – Must be between 8 and 64 characters</p> </li>
/// </ul>
/// <p>AND any 3 of the following password complexity rules required by Active Directory:</p>
/// <ul>
/// <li> <p>Numbers and upper case and lowercase (?=.*\d)(?=.*[A-Z])(?=.*[a-z])</p> </li>
/// <li> <p>Numbers and special characters and lower case (?=.*\d)(?=.*[^A-Za-z0-9\s])(?=.*[a-z])</p> </li>
/// <li> <p>Special characters and upper case and lower case (?=.*[^A-Za-z0-9\s])(?=.*[A-Z])(?=.*[a-z])</p> </li>
/// <li> <p>Numbers and upper case and special characters (?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9\s])</p> </li>
/// </ul>
/// <p>For additional information about how Active Directory passwords are enforced, see <a href="https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/password-must-meet-complexity-requirements">Password must meet complexity requirements</a> on the Microsoft website.</p>
pub password: std::option::Option<std::string::String>,
/// <p>A description for the directory.</p>
pub description: std::option::Option<std::string::String>,
/// <p>The size of the directory.</p>
pub size: std::option::Option<crate::model::DirectorySize>,
/// <p>A <code>DirectoryVpcSettings</code> object that contains additional information for the operation.</p>
pub vpc_settings: std::option::Option<crate::model::DirectoryVpcSettings>,
/// <p>The tags to be assigned to the Simple AD directory.</p>
pub tags: std::option::Option<std::vec::Vec<crate::model::Tag>>,
}
impl CreateDirectoryInput {
/// <p>The fully qualified name for the directory, such as <code>corp.example.com</code>.</p>
pub fn name(&self) -> std::option::Option<&str> {
self.name.as_deref()
}
/// <p>The NetBIOS name of the directory, such as <code>CORP</code>.</p>
pub fn short_name(&self) -> std::option::Option<&str> {
self.short_name.as_deref()
}
/// <p>The password for the directory administrator. The directory creation process creates a directory administrator account with the user name <code>Administrator</code> and this password.</p>
/// <p>If you need to change the password for the administrator account, you can use the <code>ResetUserPassword</code> API call.</p>
/// <p>The regex pattern for this string is made up of the following conditions:</p>
/// <ul>
/// <li> <p>Length (?=^.{8,64}$) – Must be between 8 and 64 characters</p> </li>
/// </ul>
/// <p>AND any 3 of the following password complexity rules required by Active Directory:</p>
/// <ul>
/// <li> <p>Numbers and upper case and lowercase (?=.*\d)(?=.*[A-Z])(?=.*[a-z])</p> </li>
/// <li> <p>Numbers and special characters and lower case (?=.*\d)(?=.*[^A-Za-z0-9\s])(?=.*[a-z])</p> </li>
/// <li> <p>Special characters and upper case and lower case (?=.*[^A-Za-z0-9\s])(?=.*[A-Z])(?=.*[a-z])</p> </li>
/// <li> <p>Numbers and upper case and special characters (?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9\s])</p> </li>
/// </ul>
/// <p>For additional information about how Active Directory passwords are enforced, see <a href="https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/password-must-meet-complexity-requirements">Password must meet complexity requirements</a> on the Microsoft website.</p>
pub fn password(&self) -> std::option::Option<&str> {
self.password.as_deref()
}
/// <p>A description for the directory.</p>
pub fn description(&self) -> std::option::Option<&str> {
self.description.as_deref()
}
/// <p>The size of the directory.</p>
pub fn size(&self) -> std::option::Option<&crate::model::DirectorySize> {
self.size.as_ref()
}
/// <p>A <code>DirectoryVpcSettings</code> object that contains additional information for the operation.</p>
pub fn vpc_settings(&self) -> std::option::Option<&crate::model::DirectoryVpcSettings> {
self.vpc_settings.as_ref()
}
/// <p>The tags to be assigned to the Simple AD directory.</p>
pub fn tags(&self) -> std::option::Option<&[crate::model::Tag]> {
self.tags.as_deref()
}
}
impl std::fmt::Debug for CreateDirectoryInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("CreateDirectoryInput");
formatter.field("name", &self.name);
formatter.field("short_name", &self.short_name);
formatter.field("password", &"*** Sensitive Data Redacted ***");
formatter.field("description", &self.description);
formatter.field("size", &self.size);
formatter.field("vpc_settings", &self.vpc_settings);
formatter.field("tags", &self.tags);
formatter.finish()
}
}
/// <p>Initiates the creation of a conditional forwarder for your Directory Service for Microsoft Active Directory. Conditional forwarders are required in order to set up a trust relationship with another domain.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct CreateConditionalForwarderInput {
/// <p>The directory ID of the Amazon Web Services directory for which you are creating the conditional forwarder.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The fully qualified domain name (FQDN) of the remote domain with which you will set up a trust relationship.</p>
pub remote_domain_name: std::option::Option<std::string::String>,
/// <p>The IP addresses of the remote DNS server associated with RemoteDomainName.</p>
pub dns_ip_addrs: std::option::Option<std::vec::Vec<std::string::String>>,
}
impl CreateConditionalForwarderInput {
/// <p>The directory ID of the Amazon Web Services directory for which you are creating the conditional forwarder.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The fully qualified domain name (FQDN) of the remote domain with which you will set up a trust relationship.</p>
pub fn remote_domain_name(&self) -> std::option::Option<&str> {
self.remote_domain_name.as_deref()
}
/// <p>The IP addresses of the remote DNS server associated with RemoteDomainName.</p>
pub fn dns_ip_addrs(&self) -> std::option::Option<&[std::string::String]> {
self.dns_ip_addrs.as_deref()
}
}
impl std::fmt::Debug for CreateConditionalForwarderInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("CreateConditionalForwarderInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("remote_domain_name", &self.remote_domain_name);
formatter.field("dns_ip_addrs", &self.dns_ip_addrs);
formatter.finish()
}
}
/// <p>Contains the inputs for the <code>CreateComputer</code> operation.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct CreateComputerInput {
/// <p>The identifier of the directory in which to create the computer account.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The name of the computer account.</p>
pub computer_name: std::option::Option<std::string::String>,
/// <p>A one-time password that is used to join the computer to the directory. You should generate a random, strong password to use for this parameter.</p>
pub password: std::option::Option<std::string::String>,
/// <p>The fully-qualified distinguished name of the organizational unit to place the computer account in.</p>
pub organizational_unit_distinguished_name: std::option::Option<std::string::String>,
/// <p>An array of <code>Attribute</code> objects that contain any LDAP attributes to apply to the computer account.</p>
pub computer_attributes: std::option::Option<std::vec::Vec<crate::model::Attribute>>,
}
impl CreateComputerInput {
/// <p>The identifier of the directory in which to create the computer account.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The name of the computer account.</p>
pub fn computer_name(&self) -> std::option::Option<&str> {
self.computer_name.as_deref()
}
/// <p>A one-time password that is used to join the computer to the directory. You should generate a random, strong password to use for this parameter.</p>
pub fn password(&self) -> std::option::Option<&str> {
self.password.as_deref()
}
/// <p>The fully-qualified distinguished name of the organizational unit to place the computer account in.</p>
pub fn organizational_unit_distinguished_name(&self) -> std::option::Option<&str> {
self.organizational_unit_distinguished_name.as_deref()
}
/// <p>An array of <code>Attribute</code> objects that contain any LDAP attributes to apply to the computer account.</p>
pub fn computer_attributes(&self) -> std::option::Option<&[crate::model::Attribute]> {
self.computer_attributes.as_deref()
}
}
impl std::fmt::Debug for CreateComputerInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("CreateComputerInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("computer_name", &self.computer_name);
formatter.field("password", &"*** Sensitive Data Redacted ***");
formatter.field(
"organizational_unit_distinguished_name",
&self.organizational_unit_distinguished_name,
);
formatter.field("computer_attributes", &self.computer_attributes);
formatter.finish()
}
}
/// <p>Contains the inputs for the <code>CreateAlias</code> operation.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct CreateAliasInput {
/// <p>The identifier of the directory for which to create the alias.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The requested alias.</p>
/// <p>The alias must be unique amongst all aliases in Amazon Web Services. This operation throws an <code>EntityAlreadyExistsException</code> error if the alias already exists.</p>
pub alias: std::option::Option<std::string::String>,
}
impl CreateAliasInput {
/// <p>The identifier of the directory for which to create the alias.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The requested alias.</p>
/// <p>The alias must be unique amongst all aliases in Amazon Web Services. This operation throws an <code>EntityAlreadyExistsException</code> error if the alias already exists.</p>
pub fn alias(&self) -> std::option::Option<&str> {
self.alias.as_deref()
}
}
impl std::fmt::Debug for CreateAliasInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("CreateAliasInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("alias", &self.alias);
formatter.finish()
}
}
/// <p>Contains the inputs for the <code>ConnectDirectory</code> operation.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ConnectDirectoryInput {
/// <p>The fully qualified name of your self-managed directory, such as <code>corp.example.com</code>.</p>
pub name: std::option::Option<std::string::String>,
/// <p>The NetBIOS name of your self-managed directory, such as <code>CORP</code>.</p>
pub short_name: std::option::Option<std::string::String>,
/// <p>The password for your self-managed user account.</p>
pub password: std::option::Option<std::string::String>,
/// <p>A description for the directory.</p>
pub description: std::option::Option<std::string::String>,
/// <p>The size of the directory.</p>
pub size: std::option::Option<crate::model::DirectorySize>,
/// <p>A <code>DirectoryConnectSettings</code> object that contains additional information for the operation.</p>
pub connect_settings: std::option::Option<crate::model::DirectoryConnectSettings>,
/// <p>The tags to be assigned to AD Connector.</p>
pub tags: std::option::Option<std::vec::Vec<crate::model::Tag>>,
}
impl ConnectDirectoryInput {
/// <p>The fully qualified name of your self-managed directory, such as <code>corp.example.com</code>.</p>
pub fn name(&self) -> std::option::Option<&str> {
self.name.as_deref()
}
/// <p>The NetBIOS name of your self-managed directory, such as <code>CORP</code>.</p>
pub fn short_name(&self) -> std::option::Option<&str> {
self.short_name.as_deref()
}
/// <p>The password for your self-managed user account.</p>
pub fn password(&self) -> std::option::Option<&str> {
self.password.as_deref()
}
/// <p>A description for the directory.</p>
pub fn description(&self) -> std::option::Option<&str> {
self.description.as_deref()
}
/// <p>The size of the directory.</p>
pub fn size(&self) -> std::option::Option<&crate::model::DirectorySize> {
self.size.as_ref()
}
/// <p>A <code>DirectoryConnectSettings</code> object that contains additional information for the operation.</p>
pub fn connect_settings(&self) -> std::option::Option<&crate::model::DirectoryConnectSettings> {
self.connect_settings.as_ref()
}
/// <p>The tags to be assigned to AD Connector.</p>
pub fn tags(&self) -> std::option::Option<&[crate::model::Tag]> {
self.tags.as_deref()
}
}
impl std::fmt::Debug for ConnectDirectoryInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ConnectDirectoryInput");
formatter.field("name", &self.name);
formatter.field("short_name", &self.short_name);
formatter.field("password", &"*** Sensitive Data Redacted ***");
formatter.field("description", &self.description);
formatter.field("size", &self.size);
formatter.field("connect_settings", &self.connect_settings);
formatter.field("tags", &self.tags);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct CancelSchemaExtensionInput {
/// <p>The identifier of the directory whose schema extension will be canceled.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The identifier of the schema extension that will be canceled.</p>
pub schema_extension_id: std::option::Option<std::string::String>,
}
impl CancelSchemaExtensionInput {
/// <p>The identifier of the directory whose schema extension will be canceled.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The identifier of the schema extension that will be canceled.</p>
pub fn schema_extension_id(&self) -> std::option::Option<&str> {
self.schema_extension_id.as_deref()
}
}
impl std::fmt::Debug for CancelSchemaExtensionInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("CancelSchemaExtensionInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("schema_extension_id", &self.schema_extension_id);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct AddTagsToResourceInput {
/// <p>Identifier (ID) for the directory to which to add the tag.</p>
pub resource_id: std::option::Option<std::string::String>,
/// <p>The tags to be assigned to the directory.</p>
pub tags: std::option::Option<std::vec::Vec<crate::model::Tag>>,
}
impl AddTagsToResourceInput {
/// <p>Identifier (ID) for the directory to which to add the tag.</p>
pub fn resource_id(&self) -> std::option::Option<&str> {
self.resource_id.as_deref()
}
/// <p>The tags to be assigned to the directory.</p>
pub fn tags(&self) -> std::option::Option<&[crate::model::Tag]> {
self.tags.as_deref()
}
}
impl std::fmt::Debug for AddTagsToResourceInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("AddTagsToResourceInput");
formatter.field("resource_id", &self.resource_id);
formatter.field("tags", &self.tags);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct AddRegionInput {
/// <p>The identifier of the directory to which you want to add Region replication.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>The name of the Region where you want to add domain controllers for replication. For example, <code>us-east-1</code>.</p>
pub region_name: std::option::Option<std::string::String>,
/// <p>Contains VPC information for the <code>CreateDirectory</code> or <code>CreateMicrosoftAD</code> operation.</p>
pub vpc_settings: std::option::Option<crate::model::DirectoryVpcSettings>,
}
impl AddRegionInput {
/// <p>The identifier of the directory to which you want to add Region replication.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>The name of the Region where you want to add domain controllers for replication. For example, <code>us-east-1</code>.</p>
pub fn region_name(&self) -> std::option::Option<&str> {
self.region_name.as_deref()
}
/// <p>Contains VPC information for the <code>CreateDirectory</code> or <code>CreateMicrosoftAD</code> operation.</p>
pub fn vpc_settings(&self) -> std::option::Option<&crate::model::DirectoryVpcSettings> {
self.vpc_settings.as_ref()
}
}
impl std::fmt::Debug for AddRegionInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("AddRegionInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("region_name", &self.region_name);
formatter.field("vpc_settings", &self.vpc_settings);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct AddIpRoutesInput {
/// <p>Identifier (ID) of the directory to which to add the address block.</p>
pub directory_id: std::option::Option<std::string::String>,
/// <p>IP address blocks, using CIDR format, of the traffic to route. This is often the IP address block of the DNS server used for your self-managed domain.</p>
pub ip_routes: std::option::Option<std::vec::Vec<crate::model::IpRoute>>,
/// <p>If set to true, updates the inbound and outbound rules of the security group that has the description: "Amazon Web Services created security group for <i>directory ID</i> directory controllers." Following are the new rules: </p>
/// <p>Inbound:</p>
/// <ul>
/// <li> <p>Type: Custom UDP Rule, Protocol: UDP, Range: 88, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom UDP Rule, Protocol: UDP, Range: 123, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom UDP Rule, Protocol: UDP, Range: 138, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom UDP Rule, Protocol: UDP, Range: 389, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom UDP Rule, Protocol: UDP, Range: 464, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom UDP Rule, Protocol: UDP, Range: 445, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 88, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 135, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 445, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 464, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 636, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 1024-65535, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 3268-33269, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: DNS (UDP), Protocol: UDP, Range: 53, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: DNS (TCP), Protocol: TCP, Range: 53, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: LDAP, Protocol: TCP, Range: 389, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: All ICMP, Protocol: All, Range: N/A, Source: 0.0.0.0/0</p> </li>
/// </ul>
/// <p></p>
/// <p>Outbound:</p>
/// <ul>
/// <li> <p>Type: All traffic, Protocol: All, Range: All, Destination: 0.0.0.0/0</p> </li>
/// </ul>
/// <p>These security rules impact an internal network interface that is not exposed publicly.</p>
pub update_security_group_for_directory_controllers: bool,
}
impl AddIpRoutesInput {
/// <p>Identifier (ID) of the directory to which to add the address block.</p>
pub fn directory_id(&self) -> std::option::Option<&str> {
self.directory_id.as_deref()
}
/// <p>IP address blocks, using CIDR format, of the traffic to route. This is often the IP address block of the DNS server used for your self-managed domain.</p>
pub fn ip_routes(&self) -> std::option::Option<&[crate::model::IpRoute]> {
self.ip_routes.as_deref()
}
/// <p>If set to true, updates the inbound and outbound rules of the security group that has the description: "Amazon Web Services created security group for <i>directory ID</i> directory controllers." Following are the new rules: </p>
/// <p>Inbound:</p>
/// <ul>
/// <li> <p>Type: Custom UDP Rule, Protocol: UDP, Range: 88, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom UDP Rule, Protocol: UDP, Range: 123, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom UDP Rule, Protocol: UDP, Range: 138, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom UDP Rule, Protocol: UDP, Range: 389, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom UDP Rule, Protocol: UDP, Range: 464, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom UDP Rule, Protocol: UDP, Range: 445, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 88, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 135, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 445, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 464, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 636, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 1024-65535, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: Custom TCP Rule, Protocol: TCP, Range: 3268-33269, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: DNS (UDP), Protocol: UDP, Range: 53, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: DNS (TCP), Protocol: TCP, Range: 53, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: LDAP, Protocol: TCP, Range: 389, Source: 0.0.0.0/0</p> </li>
/// <li> <p>Type: All ICMP, Protocol: All, Range: N/A, Source: 0.0.0.0/0</p> </li>
/// </ul>
/// <p></p>
/// <p>Outbound:</p>
/// <ul>
/// <li> <p>Type: All traffic, Protocol: All, Range: All, Destination: 0.0.0.0/0</p> </li>
/// </ul>
/// <p>These security rules impact an internal network interface that is not exposed publicly.</p>
pub fn update_security_group_for_directory_controllers(&self) -> bool {
self.update_security_group_for_directory_controllers
}
}
impl std::fmt::Debug for AddIpRoutesInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("AddIpRoutesInput");
formatter.field("directory_id", &self.directory_id);
formatter.field("ip_routes", &self.ip_routes);
formatter.field(
"update_security_group_for_directory_controllers",
&self.update_security_group_for_directory_controllers,
);
formatter.finish()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct AcceptSharedDirectoryInput {
/// <p>Identifier of the shared directory in the directory consumer account. This identifier is different for each directory owner account. </p>
pub shared_directory_id: std::option::Option<std::string::String>,
}
impl AcceptSharedDirectoryInput {
/// <p>Identifier of the shared directory in the directory consumer account. This identifier is different for each directory owner account. </p>
pub fn shared_directory_id(&self) -> std::option::Option<&str> {
self.shared_directory_id.as_deref()
}
}
impl std::fmt::Debug for AcceptSharedDirectoryInput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("AcceptSharedDirectoryInput");
formatter.field("shared_directory_id", &self.shared_directory_id);
formatter.finish()
}
}
| 46.711534 | 368 | 0.619664 |
edf50ae27c8e7aad1a47b83dae4fd2d33ac1fb4b | 7,985 | /*! Python `property` descriptor class.
*/
use super::{PyType, PyTypeRef};
use crate::common::lock::PyRwLock;
use crate::{
class::PyClassImpl,
function::FuncArgs,
types::{Constructor, GetDescriptor, Initializer},
AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine,
};
/// Property attribute.
///
/// fget
/// function to be used for getting an attribute value
/// fset
/// function to be used for setting an attribute value
/// fdel
/// function to be used for del'ing an attribute
/// doc
/// docstring
///
/// Typical use is to define a managed attribute x:
///
/// class C(object):
/// def getx(self): return self._x
/// def setx(self, value): self._x = value
/// def delx(self): del self._x
/// x = property(getx, setx, delx, "I'm the 'x' property.")
///
/// Decorators make defining new properties or modifying existing ones easy:
///
/// class C(object):
/// @property
/// def x(self):
/// "I am the 'x' property."
/// return self._x
/// @x.setter
/// def x(self, value):
/// self._x = value
/// @x.deleter
/// def x(self):
/// del self._x
#[pyclass(module = false, name = "property")]
#[derive(Debug)]
pub struct PyProperty {
getter: PyRwLock<Option<PyObjectRef>>,
setter: PyRwLock<Option<PyObjectRef>>,
deleter: PyRwLock<Option<PyObjectRef>>,
doc: PyRwLock<Option<PyObjectRef>>,
}
impl PyPayload for PyProperty {
fn class(vm: &VirtualMachine) -> &'static Py<PyType> {
vm.ctx.types.property_type
}
}
#[derive(FromArgs)]
pub struct PropertyArgs {
#[pyarg(any, default)]
fget: Option<PyObjectRef>,
#[pyarg(any, default)]
fset: Option<PyObjectRef>,
#[pyarg(any, default)]
fdel: Option<PyObjectRef>,
#[pyarg(any, default)]
doc: Option<PyObjectRef>,
}
impl GetDescriptor for PyProperty {
fn descr_get(
zelf: PyObjectRef,
obj: Option<PyObjectRef>,
_cls: Option<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult {
let (zelf, obj) = Self::_unwrap(zelf, obj, vm)?;
if vm.is_none(&obj) {
Ok(zelf.into())
} else if let Some(getter) = zelf.getter.read().as_ref() {
vm.invoke(getter, (obj,))
} else {
Err(vm.new_attribute_error("unreadable attribute".to_string()))
}
}
}
#[pyimpl(with(Constructor, Initializer, GetDescriptor), flags(BASETYPE))]
impl PyProperty {
// Descriptor methods
#[pyslot]
fn descr_set(
zelf: PyObjectRef,
obj: PyObjectRef,
value: Option<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<()> {
let zelf = PyRef::<Self>::try_from_object(vm, zelf)?;
match value {
Some(value) => {
if let Some(setter) = zelf.setter.read().as_ref() {
vm.invoke(setter, (obj, value)).map(drop)
} else {
Err(vm.new_attribute_error("can't set attribute".to_owned()))
}
}
None => {
if let Some(deleter) = zelf.deleter.read().as_ref() {
vm.invoke(deleter, (obj,)).map(drop)
} else {
Err(vm.new_attribute_error("can't delete attribute".to_owned()))
}
}
}
}
#[pymethod]
fn __set__(
zelf: PyObjectRef,
obj: PyObjectRef,
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<()> {
Self::descr_set(zelf, obj, Some(value), vm)
}
#[pymethod]
fn __delete__(zelf: PyObjectRef, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
Self::descr_set(zelf, obj, None, vm)
}
// Access functions
#[pyproperty]
fn fget(&self) -> Option<PyObjectRef> {
self.getter.read().clone()
}
#[pyproperty]
fn fset(&self) -> Option<PyObjectRef> {
self.setter.read().clone()
}
#[pyproperty]
fn fdel(&self) -> Option<PyObjectRef> {
self.deleter.read().clone()
}
fn doc_getter(&self) -> Option<PyObjectRef> {
self.doc.read().clone()
}
fn doc_setter(&self, value: Option<PyObjectRef>) {
*self.doc.write() = value;
}
// Python builder functions
#[pymethod]
fn getter(
zelf: PyRef<Self>,
getter: Option<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<PyRef<Self>> {
PyProperty {
getter: PyRwLock::new(getter.or_else(|| zelf.fget())),
setter: PyRwLock::new(zelf.fset()),
deleter: PyRwLock::new(zelf.fdel()),
doc: PyRwLock::new(None),
}
.into_ref_with_type(vm, zelf.class().clone())
}
#[pymethod]
fn setter(
zelf: PyRef<Self>,
setter: Option<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<PyRef<Self>> {
PyProperty {
getter: PyRwLock::new(zelf.fget()),
setter: PyRwLock::new(setter.or_else(|| zelf.fset())),
deleter: PyRwLock::new(zelf.fdel()),
doc: PyRwLock::new(None),
}
.into_ref_with_type(vm, zelf.class().clone())
}
#[pymethod]
fn deleter(
zelf: PyRef<Self>,
deleter: Option<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<PyRef<Self>> {
PyProperty {
getter: PyRwLock::new(zelf.fget()),
setter: PyRwLock::new(zelf.fset()),
deleter: PyRwLock::new(deleter.or_else(|| zelf.fdel())),
doc: PyRwLock::new(None),
}
.into_ref_with_type(vm, zelf.class().clone())
}
#[pyproperty(magic)]
fn isabstractmethod(&self, vm: &VirtualMachine) -> PyObjectRef {
let getter_abstract = match self.getter.read().to_owned() {
Some(getter) => getter
.get_attr("__isabstractmethod__", vm)
.unwrap_or_else(|_| vm.ctx.new_bool(false).into()),
_ => vm.ctx.new_bool(false).into(),
};
let setter_abstract = match self.setter.read().to_owned() {
Some(setter) => setter
.get_attr("__isabstractmethod__", vm)
.unwrap_or_else(|_| vm.ctx.new_bool(false).into()),
_ => vm.ctx.new_bool(false).into(),
};
vm._or(&setter_abstract, &getter_abstract)
.unwrap_or_else(|_| vm.ctx.new_bool(false).into())
}
#[pyproperty(magic, setter)]
fn set_isabstractmethod(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
if let Some(getter) = self.getter.read().to_owned() {
getter.set_attr("__isabstractmethod__", value, vm)?;
}
Ok(())
}
}
impl Constructor for PyProperty {
type Args = FuncArgs;
fn py_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult {
PyProperty {
getter: PyRwLock::new(None),
setter: PyRwLock::new(None),
deleter: PyRwLock::new(None),
doc: PyRwLock::new(None),
}
.into_ref_with_type(vm, cls)
.map(Into::into)
}
}
impl Initializer for PyProperty {
type Args = PropertyArgs;
fn init(zelf: PyRef<Self>, args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
*zelf.getter.write() = args.fget;
*zelf.setter.write() = args.fset;
*zelf.deleter.write() = args.fdel;
*zelf.doc.write() = args.doc;
Ok(())
}
}
pub(crate) fn init(context: &Context) {
PyProperty::extend_class(context, context.types.property_type);
// This is a bit unfortunate, but this instance attribute overlaps with the
// class __doc__ string..
extend_class!(context, context.types.property_type, {
"__doc__" => context.new_getset(
"__doc__",
context.types.property_type,
PyProperty::doc_getter,
PyProperty::doc_setter,
),
});
}
| 29.356618 | 98 | 0.56293 |
5684855914253c6ad29666185a15bfca7bb4a737 | 62,182 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//! Serde code to convert from protocol buffers to Rust data structures.
use crate::error::BallistaError;
use crate::serde::{
from_proto_binary_op, proto_error, protobuf, str_to_byte, vec_to_array,
};
use crate::{convert_box_required, convert_required};
use datafusion::arrow::datatypes::{DataType, Field, Schema, TimeUnit};
use datafusion::datasource::file_format::avro::AvroFormat;
use datafusion::datasource::file_format::csv::CsvFormat;
use datafusion::datasource::file_format::parquet::ParquetFormat;
use datafusion::datasource::file_format::FileFormat;
use datafusion::datasource::listing::{ListingOptions, ListingTable};
use datafusion::datasource::object_store::local::LocalFileSystem;
use datafusion::datasource::object_store::{FileMeta, SizedFile};
use datafusion::logical_plan::window_frames::{
WindowFrame, WindowFrameBound, WindowFrameUnits,
};
use datafusion::logical_plan::{
abs, acos, asin, atan, ceil, cos, digest, exp, floor, ln, log10, log2, round, signum,
sin, sqrt, tan, trunc, Column, CreateExternalTable, DFField, DFSchema, Expr,
JoinConstraint, JoinType, LogicalPlan, LogicalPlanBuilder, Operator,
};
use datafusion::physical_plan::aggregates::AggregateFunction;
use datafusion::physical_plan::window_functions::BuiltInWindowFunction;
use datafusion::prelude::*;
use datafusion::scalar::ScalarValue;
use protobuf::listing_table_scan_node::FileFormatType;
use protobuf::logical_plan_node::LogicalPlanType;
use protobuf::{logical_expr_node::ExprType, scalar_type};
use std::{
convert::{From, TryInto},
sync::Arc,
unimplemented,
};
impl TryInto<LogicalPlan> for &protobuf::LogicalPlanNode {
type Error = BallistaError;
fn try_into(self) -> Result<LogicalPlan, Self::Error> {
let plan = self.logical_plan_type.as_ref().ok_or_else(|| {
proto_error(format!(
"logical_plan::from_proto() Unsupported logical plan '{:?}'",
self
))
})?;
match plan {
LogicalPlanType::Values(values) => {
let n_cols = values.n_cols as usize;
let values: Vec<Vec<Expr>> = if values.values_list.is_empty() {
Ok(Vec::new())
} else if values.values_list.len() % n_cols != 0 {
Err(BallistaError::General(format!(
"Invalid values list length, expect {} to be divisible by {}",
values.values_list.len(),
n_cols
)))
} else {
values
.values_list
.chunks_exact(n_cols)
.map(|r| {
r.iter()
.map(|v| v.try_into())
.collect::<Result<Vec<_>, _>>()
})
.collect::<Result<Vec<_>, _>>()
}?;
LogicalPlanBuilder::values(values)?
.build()
.map_err(|e| e.into())
}
LogicalPlanType::Projection(projection) => {
let input: LogicalPlan = convert_box_required!(projection.input)?;
let x: Vec<Expr> = projection
.expr
.iter()
.map(|expr| expr.try_into())
.collect::<Result<Vec<_>, _>>()?;
LogicalPlanBuilder::from(input)
.project_with_alias(
x,
projection.optional_alias.as_ref().map(|a| match a {
protobuf::projection_node::OptionalAlias::Alias(alias) => {
alias.clone()
}
}),
)?
.build()
.map_err(|e| e.into())
}
LogicalPlanType::Selection(selection) => {
let input: LogicalPlan = convert_box_required!(selection.input)?;
let expr: Expr = selection
.expr
.as_ref()
.ok_or_else(|| {
BallistaError::General("expression required".to_string())
})?
.try_into()?;
LogicalPlanBuilder::from(input)
.filter(expr)?
.build()
.map_err(|e| e.into())
}
LogicalPlanType::Window(window) => {
let input: LogicalPlan = convert_box_required!(window.input)?;
let window_expr = window
.window_expr
.iter()
.map(|expr| expr.try_into())
.collect::<Result<Vec<Expr>, _>>()?;
LogicalPlanBuilder::from(input)
.window(window_expr)?
.build()
.map_err(|e| e.into())
}
LogicalPlanType::Aggregate(aggregate) => {
let input: LogicalPlan = convert_box_required!(aggregate.input)?;
let group_expr = aggregate
.group_expr
.iter()
.map(|expr| expr.try_into())
.collect::<Result<Vec<Expr>, _>>()?;
let aggr_expr = aggregate
.aggr_expr
.iter()
.map(|expr| expr.try_into())
.collect::<Result<Vec<Expr>, _>>()?;
LogicalPlanBuilder::from(input)
.aggregate(group_expr, aggr_expr)?
.build()
.map_err(|e| e.into())
}
LogicalPlanType::ListingScan(scan) => {
let schema: Schema = convert_required!(scan.schema)?;
let mut projection = None;
if let Some(columns) = &scan.projection {
let column_indices = columns
.columns
.iter()
.map(|name| schema.index_of(name))
.collect::<Result<Vec<usize>, _>>()?;
projection = Some(column_indices);
}
let filters = scan
.filters
.iter()
.map(|e| e.try_into())
.collect::<Result<Vec<_>, _>>()?;
let file_format: Arc<dyn FileFormat> =
match scan.file_format_type.as_ref().ok_or_else(|| {
proto_error(format!(
"logical_plan::from_proto() Unsupported file format '{:?}'",
self
))
})? {
&FileFormatType::Parquet(protobuf::ParquetFormat {
enable_pruning,
}) => Arc::new(
ParquetFormat::default().with_enable_pruning(enable_pruning),
),
FileFormatType::Csv(protobuf::CsvFormat {
has_header,
delimiter,
}) => Arc::new(
CsvFormat::default()
.with_has_header(*has_header)
.with_delimiter(str_to_byte(delimiter)?),
),
FileFormatType::Avro(..) => Arc::new(AvroFormat::default()),
};
let options = ListingOptions {
file_extension: scan.file_extension.clone(),
format: file_format,
table_partition_cols: scan.table_partition_cols.clone(),
collect_stat: scan.collect_stat,
target_partitions: scan.target_partitions as usize,
};
let provider = ListingTable::new(
Arc::new(LocalFileSystem {}),
scan.path.clone(),
Arc::new(schema),
options,
);
LogicalPlanBuilder::scan_with_filters(
&scan.table_name,
Arc::new(provider),
projection,
filters,
)?
.build()
.map_err(|e| e.into())
}
LogicalPlanType::Sort(sort) => {
let input: LogicalPlan = convert_box_required!(sort.input)?;
let sort_expr: Vec<Expr> = sort
.expr
.iter()
.map(|expr| expr.try_into())
.collect::<Result<Vec<Expr>, _>>()?;
LogicalPlanBuilder::from(input)
.sort(sort_expr)?
.build()
.map_err(|e| e.into())
}
LogicalPlanType::Repartition(repartition) => {
use datafusion::logical_plan::Partitioning;
let input: LogicalPlan = convert_box_required!(repartition.input)?;
use protobuf::repartition_node::PartitionMethod;
let pb_partition_method = repartition.partition_method.clone().ok_or_else(|| {
BallistaError::General(String::from(
"Protobuf deserialization error, RepartitionNode was missing required field 'partition_method'",
))
})?;
let partitioning_scheme = match pb_partition_method {
PartitionMethod::Hash(protobuf::HashRepartition {
hash_expr: pb_hash_expr,
partition_count,
}) => Partitioning::Hash(
pb_hash_expr
.iter()
.map(|pb_expr| pb_expr.try_into())
.collect::<Result<Vec<_>, _>>()?,
partition_count as usize,
),
PartitionMethod::RoundRobin(partition_count) => {
Partitioning::RoundRobinBatch(partition_count as usize)
}
};
LogicalPlanBuilder::from(input)
.repartition(partitioning_scheme)?
.build()
.map_err(|e| e.into())
}
LogicalPlanType::EmptyRelation(empty_relation) => {
LogicalPlanBuilder::empty(empty_relation.produce_one_row)
.build()
.map_err(|e| e.into())
}
LogicalPlanType::CreateExternalTable(create_extern_table) => {
let pb_schema = (create_extern_table.schema.clone()).ok_or_else(|| {
BallistaError::General(String::from(
"Protobuf deserialization error, CreateExternalTableNode was missing required field schema.",
))
})?;
let pb_file_type: protobuf::FileType =
create_extern_table.file_type.try_into()?;
Ok(LogicalPlan::CreateExternalTable(CreateExternalTable {
schema: pb_schema.try_into()?,
name: create_extern_table.name.clone(),
location: create_extern_table.location.clone(),
file_type: pb_file_type.into(),
has_header: create_extern_table.has_header,
}))
}
LogicalPlanType::Analyze(analyze) => {
let input: LogicalPlan = convert_box_required!(analyze.input)?;
LogicalPlanBuilder::from(input)
.explain(analyze.verbose, true)?
.build()
.map_err(|e| e.into())
}
LogicalPlanType::Explain(explain) => {
let input: LogicalPlan = convert_box_required!(explain.input)?;
LogicalPlanBuilder::from(input)
.explain(explain.verbose, false)?
.build()
.map_err(|e| e.into())
}
LogicalPlanType::Limit(limit) => {
let input: LogicalPlan = convert_box_required!(limit.input)?;
LogicalPlanBuilder::from(input)
.limit(limit.limit as usize)?
.build()
.map_err(|e| e.into())
}
LogicalPlanType::Join(join) => {
let left_keys: Vec<Column> =
join.left_join_column.iter().map(|i| i.into()).collect();
let right_keys: Vec<Column> =
join.right_join_column.iter().map(|i| i.into()).collect();
let join_type =
protobuf::JoinType::from_i32(join.join_type).ok_or_else(|| {
proto_error(format!(
"Received a JoinNode message with unknown JoinType {}",
join.join_type
))
})?;
let join_constraint = protobuf::JoinConstraint::from_i32(
join.join_constraint,
)
.ok_or_else(|| {
proto_error(format!(
"Received a JoinNode message with unknown JoinConstraint {}",
join.join_constraint
))
})?;
let builder = LogicalPlanBuilder::from(convert_box_required!(join.left)?);
let builder = match join_constraint.into() {
JoinConstraint::On => builder.join(
&convert_box_required!(join.right)?,
join_type.into(),
(left_keys, right_keys),
)?,
JoinConstraint::Using => builder.join_using(
&convert_box_required!(join.right)?,
join_type.into(),
left_keys,
)?,
};
builder.build().map_err(|e| e.into())
}
LogicalPlanType::CrossJoin(crossjoin) => {
let left = convert_box_required!(crossjoin.left)?;
let right = convert_box_required!(crossjoin.right)?;
LogicalPlanBuilder::from(left)
.cross_join(&right)?
.build()
.map_err(|e| e.into())
}
}
}
}
impl From<&protobuf::Column> for Column {
fn from(c: &protobuf::Column) -> Column {
let c = c.clone();
Column {
relation: c.relation.map(|r| r.relation),
name: c.name,
}
}
}
impl TryInto<DFSchema> for &protobuf::DfSchema {
type Error = BallistaError;
fn try_into(self) -> Result<DFSchema, BallistaError> {
let fields = self
.columns
.iter()
.map(|c| c.try_into())
.collect::<Result<Vec<DFField>, _>>()?;
Ok(DFSchema::new(fields)?)
}
}
impl TryInto<datafusion::logical_plan::DFSchemaRef> for protobuf::DfSchema {
type Error = BallistaError;
fn try_into(self) -> Result<datafusion::logical_plan::DFSchemaRef, Self::Error> {
let dfschema: DFSchema = (&self).try_into()?;
Ok(Arc::new(dfschema))
}
}
impl TryInto<DFField> for &protobuf::DfField {
type Error = BallistaError;
fn try_into(self) -> Result<DFField, Self::Error> {
let field: Field = convert_required!(self.field)?;
Ok(match &self.qualifier {
Some(q) => DFField::from_qualified(&q.relation, field),
None => DFField::from(field),
})
}
}
impl TryInto<DataType> for &protobuf::scalar_type::Datatype {
type Error = BallistaError;
fn try_into(self) -> Result<DataType, Self::Error> {
use protobuf::scalar_type::Datatype;
Ok(match self {
Datatype::Scalar(scalar_type) => {
let pb_scalar_enum = protobuf::PrimitiveScalarType::from_i32(*scalar_type).ok_or_else(|| {
proto_error(format!(
"Protobuf deserialization error, scalar_type::Datatype missing was provided invalid enum variant: {}",
*scalar_type
))
})?;
pb_scalar_enum.into()
}
Datatype::List(protobuf::ScalarListType {
deepest_type,
field_names,
}) => {
if field_names.is_empty() {
return Err(proto_error(
"Protobuf deserialization error: found no field names in ScalarListType message which requires at least one",
));
}
let pb_scalar_type = protobuf::PrimitiveScalarType::from_i32(
*deepest_type,
)
.ok_or_else(|| {
proto_error(format!(
"Protobuf deserialization error: invalid i32 for scalar enum: {}",
*deepest_type
))
})?;
//Because length is checked above it is safe to unwrap .last()
let mut scalar_type = DataType::List(Box::new(Field::new(
field_names.last().unwrap().as_str(),
pb_scalar_type.into(),
true,
)));
//Iterate over field names in reverse order except for the last item in the vector
for name in field_names.iter().rev().skip(1) {
let new_datatype = DataType::List(Box::new(Field::new(
name.as_str(),
scalar_type,
true,
)));
scalar_type = new_datatype;
}
scalar_type
}
})
}
}
//Does not typecheck lists
fn typechecked_scalar_value_conversion(
tested_type: &protobuf::scalar_value::Value,
required_type: protobuf::PrimitiveScalarType,
) -> Result<datafusion::scalar::ScalarValue, BallistaError> {
use protobuf::scalar_value::Value;
use protobuf::PrimitiveScalarType;
Ok(match (tested_type, &required_type) {
(Value::BoolValue(v), PrimitiveScalarType::Bool) => {
ScalarValue::Boolean(Some(*v))
}
(Value::Int8Value(v), PrimitiveScalarType::Int8) => {
ScalarValue::Int8(Some(*v as i8))
}
(Value::Int16Value(v), PrimitiveScalarType::Int16) => {
ScalarValue::Int16(Some(*v as i16))
}
(Value::Int32Value(v), PrimitiveScalarType::Int32) => {
ScalarValue::Int32(Some(*v))
}
(Value::Int64Value(v), PrimitiveScalarType::Int64) => {
ScalarValue::Int64(Some(*v))
}
(Value::Uint8Value(v), PrimitiveScalarType::Uint8) => {
ScalarValue::UInt8(Some(*v as u8))
}
(Value::Uint16Value(v), PrimitiveScalarType::Uint16) => {
ScalarValue::UInt16(Some(*v as u16))
}
(Value::Uint32Value(v), PrimitiveScalarType::Uint32) => {
ScalarValue::UInt32(Some(*v))
}
(Value::Uint64Value(v), PrimitiveScalarType::Uint64) => {
ScalarValue::UInt64(Some(*v))
}
(Value::Float32Value(v), PrimitiveScalarType::Float32) => {
ScalarValue::Float32(Some(*v))
}
(Value::Float64Value(v), PrimitiveScalarType::Float64) => {
ScalarValue::Float64(Some(*v))
}
(Value::Date32Value(v), PrimitiveScalarType::Date32) => {
ScalarValue::Date32(Some(*v))
}
(Value::TimeMicrosecondValue(v), PrimitiveScalarType::TimeMicrosecond) => {
ScalarValue::TimestampMicrosecond(Some(*v), None)
}
(Value::TimeNanosecondValue(v), PrimitiveScalarType::TimeMicrosecond) => {
ScalarValue::TimestampNanosecond(Some(*v), None)
}
(Value::Utf8Value(v), PrimitiveScalarType::Utf8) => {
ScalarValue::Utf8(Some(v.to_owned()))
}
(Value::LargeUtf8Value(v), PrimitiveScalarType::LargeUtf8) => {
ScalarValue::LargeUtf8(Some(v.to_owned()))
}
(Value::NullValue(i32_enum), required_scalar_type) => {
if *i32_enum == *required_scalar_type as i32 {
let pb_scalar_type = PrimitiveScalarType::from_i32(*i32_enum).ok_or_else(|| {
BallistaError::General(format!(
"Invalid i32_enum={} when converting with PrimitiveScalarType::from_i32()",
*i32_enum
))
})?;
let scalar_value: ScalarValue = match pb_scalar_type {
PrimitiveScalarType::Bool => ScalarValue::Boolean(None),
PrimitiveScalarType::Uint8 => ScalarValue::UInt8(None),
PrimitiveScalarType::Int8 => ScalarValue::Int8(None),
PrimitiveScalarType::Uint16 => ScalarValue::UInt16(None),
PrimitiveScalarType::Int16 => ScalarValue::Int16(None),
PrimitiveScalarType::Uint32 => ScalarValue::UInt32(None),
PrimitiveScalarType::Int32 => ScalarValue::Int32(None),
PrimitiveScalarType::Uint64 => ScalarValue::UInt64(None),
PrimitiveScalarType::Int64 => ScalarValue::Int64(None),
PrimitiveScalarType::Float32 => ScalarValue::Float32(None),
PrimitiveScalarType::Float64 => ScalarValue::Float64(None),
PrimitiveScalarType::Utf8 => ScalarValue::Utf8(None),
PrimitiveScalarType::LargeUtf8 => ScalarValue::LargeUtf8(None),
PrimitiveScalarType::Date32 => ScalarValue::Date32(None),
PrimitiveScalarType::TimeMicrosecond => {
ScalarValue::TimestampMicrosecond(None, None)
}
PrimitiveScalarType::TimeNanosecond => {
ScalarValue::TimestampNanosecond(None, None)
}
PrimitiveScalarType::Null => {
return Err(proto_error(
"Untyped scalar null is not a valid scalar value",
))
}
PrimitiveScalarType::Decimal128 => {
ScalarValue::Decimal128(None, 0, 0)
}
PrimitiveScalarType::Date64 => ScalarValue::Date64(None),
PrimitiveScalarType::TimeSecond => {
ScalarValue::TimestampSecond(None, None)
}
PrimitiveScalarType::TimeMillisecond => {
ScalarValue::TimestampMillisecond(None, None)
}
PrimitiveScalarType::IntervalYearmonth => {
ScalarValue::IntervalYearMonth(None)
}
PrimitiveScalarType::IntervalDaytime => {
ScalarValue::IntervalDayTime(None)
}
};
scalar_value
} else {
return Err(proto_error("Could not convert to the proper type"));
}
}
(Value::Decimal128Value(val), PrimitiveScalarType::Decimal128) => {
let array = vec_to_array(val.value.clone());
ScalarValue::Decimal128(
Some(i128::from_be_bytes(array)),
val.p as usize,
val.s as usize,
)
}
(Value::Date64Value(v), PrimitiveScalarType::Date64) => {
ScalarValue::Date64(Some(*v))
}
(Value::TimeSecondValue(v), PrimitiveScalarType::TimeSecond) => {
ScalarValue::TimestampSecond(Some(*v), None)
}
(Value::TimeMillisecondValue(v), PrimitiveScalarType::TimeMillisecond) => {
ScalarValue::TimestampMillisecond(Some(*v), None)
}
(Value::IntervalYearmonthValue(v), PrimitiveScalarType::IntervalYearmonth) => {
ScalarValue::IntervalYearMonth(Some(*v))
}
(Value::IntervalDaytimeValue(v), PrimitiveScalarType::IntervalDaytime) => {
ScalarValue::IntervalDayTime(Some(*v))
}
_ => return Err(proto_error("Could not convert to the proper type")),
})
}
impl TryInto<datafusion::scalar::ScalarValue> for &protobuf::scalar_value::Value {
type Error = BallistaError;
fn try_into(self) -> Result<datafusion::scalar::ScalarValue, Self::Error> {
use datafusion::scalar::ScalarValue;
use protobuf::PrimitiveScalarType;
let scalar = match self {
protobuf::scalar_value::Value::BoolValue(v) => ScalarValue::Boolean(Some(*v)),
protobuf::scalar_value::Value::Utf8Value(v) => {
ScalarValue::Utf8(Some(v.to_owned()))
}
protobuf::scalar_value::Value::LargeUtf8Value(v) => {
ScalarValue::LargeUtf8(Some(v.to_owned()))
}
protobuf::scalar_value::Value::Int8Value(v) => {
ScalarValue::Int8(Some(*v as i8))
}
protobuf::scalar_value::Value::Int16Value(v) => {
ScalarValue::Int16(Some(*v as i16))
}
protobuf::scalar_value::Value::Int32Value(v) => ScalarValue::Int32(Some(*v)),
protobuf::scalar_value::Value::Int64Value(v) => ScalarValue::Int64(Some(*v)),
protobuf::scalar_value::Value::Uint8Value(v) => {
ScalarValue::UInt8(Some(*v as u8))
}
protobuf::scalar_value::Value::Uint16Value(v) => {
ScalarValue::UInt16(Some(*v as u16))
}
protobuf::scalar_value::Value::Uint32Value(v) => {
ScalarValue::UInt32(Some(*v))
}
protobuf::scalar_value::Value::Uint64Value(v) => {
ScalarValue::UInt64(Some(*v))
}
protobuf::scalar_value::Value::Float32Value(v) => {
ScalarValue::Float32(Some(*v))
}
protobuf::scalar_value::Value::Float64Value(v) => {
ScalarValue::Float64(Some(*v))
}
protobuf::scalar_value::Value::Date32Value(v) => {
ScalarValue::Date32(Some(*v))
}
protobuf::scalar_value::Value::TimeMicrosecondValue(v) => {
ScalarValue::TimestampMicrosecond(Some(*v), None)
}
protobuf::scalar_value::Value::TimeNanosecondValue(v) => {
ScalarValue::TimestampNanosecond(Some(*v), None)
}
protobuf::scalar_value::Value::ListValue(v) => v.try_into()?,
protobuf::scalar_value::Value::NullListValue(v) => {
ScalarValue::List(None, Box::new(v.try_into()?))
}
protobuf::scalar_value::Value::NullValue(null_enum) => {
PrimitiveScalarType::from_i32(*null_enum)
.ok_or_else(|| proto_error("Invalid scalar type"))?
.try_into()?
}
protobuf::scalar_value::Value::Decimal128Value(val) => {
let array = vec_to_array(val.value.clone());
ScalarValue::Decimal128(
Some(i128::from_be_bytes(array)),
val.p as usize,
val.s as usize,
)
}
protobuf::scalar_value::Value::Date64Value(v) => {
ScalarValue::Date64(Some(*v))
}
protobuf::scalar_value::Value::TimeSecondValue(v) => {
ScalarValue::TimestampSecond(Some(*v), None)
}
protobuf::scalar_value::Value::TimeMillisecondValue(v) => {
ScalarValue::TimestampMillisecond(Some(*v), None)
}
protobuf::scalar_value::Value::IntervalYearmonthValue(v) => {
ScalarValue::IntervalYearMonth(Some(*v))
}
protobuf::scalar_value::Value::IntervalDaytimeValue(v) => {
ScalarValue::IntervalDayTime(Some(*v))
}
};
Ok(scalar)
}
}
impl TryInto<datafusion::scalar::ScalarValue> for &protobuf::ScalarListValue {
type Error = BallistaError;
fn try_into(self) -> Result<datafusion::scalar::ScalarValue, Self::Error> {
use protobuf::scalar_type::Datatype;
use protobuf::PrimitiveScalarType;
let protobuf::ScalarListValue { datatype, values } = self;
let pb_scalar_type = datatype
.as_ref()
.ok_or_else(|| proto_error("Protobuf deserialization error: ScalarListValue messsage missing required field 'datatype'"))?;
let scalar_type = pb_scalar_type
.datatype
.as_ref()
.ok_or_else(|| proto_error("Protobuf deserialization error: ScalarListValue.Datatype messsage missing required field 'datatype'"))?;
let scalar_values = match scalar_type {
Datatype::Scalar(scalar_type_i32) => {
let leaf_scalar_type =
protobuf::PrimitiveScalarType::from_i32(*scalar_type_i32)
.ok_or_else(|| {
proto_error("Error converting i32 to basic scalar type")
})?;
let typechecked_values: Vec<datafusion::scalar::ScalarValue> = values
.iter()
.map(|protobuf::ScalarValue { value: opt_value }| {
let value = opt_value.as_ref().ok_or_else(|| {
proto_error(
"Protobuf deserialization error: missing required field 'value'",
)
})?;
typechecked_scalar_value_conversion(value, leaf_scalar_type)
})
.collect::<Result<Vec<_>, _>>()?;
datafusion::scalar::ScalarValue::List(
Some(Box::new(typechecked_values)),
Box::new(leaf_scalar_type.into()),
)
}
Datatype::List(list_type) => {
let protobuf::ScalarListType {
deepest_type,
field_names,
} = &list_type;
let leaf_type =
PrimitiveScalarType::from_i32(*deepest_type).ok_or_else(|| {
proto_error("Error converting i32 to basic scalar type")
})?;
let depth = field_names.len();
let typechecked_values: Vec<datafusion::scalar::ScalarValue> = if depth
== 0
{
return Err(proto_error(
"Protobuf deserialization error, ScalarListType had no field names, requires at least one",
));
} else if depth == 1 {
values
.iter()
.map(|protobuf::ScalarValue { value: opt_value }| {
let value = opt_value
.as_ref()
.ok_or_else(|| proto_error("Protobuf deserialization error: missing required field 'value'"))?;
typechecked_scalar_value_conversion(value, leaf_type)
})
.collect::<Result<Vec<_>, _>>()?
} else {
values
.iter()
.map(|protobuf::ScalarValue { value: opt_value }| {
let value = opt_value
.as_ref()
.ok_or_else(|| proto_error("Protobuf deserialization error: missing required field 'value'"))?;
value.try_into()
})
.collect::<Result<Vec<_>, _>>()?
};
datafusion::scalar::ScalarValue::List(
match typechecked_values.len() {
0 => None,
_ => Some(Box::new(typechecked_values)),
},
Box::new(list_type.try_into()?),
)
}
};
Ok(scalar_values)
}
}
impl TryInto<DataType> for &protobuf::ScalarListType {
type Error = BallistaError;
fn try_into(self) -> Result<DataType, Self::Error> {
use protobuf::PrimitiveScalarType;
let protobuf::ScalarListType {
deepest_type,
field_names,
} = self;
let depth = field_names.len();
if depth == 0 {
return Err(proto_error(
"Protobuf deserialization error: Found a ScalarListType message with no field names, at least one is required",
));
}
let mut curr_type = DataType::List(Box::new(Field::new(
//Since checked vector is not empty above this is safe to unwrap
field_names.last().unwrap(),
PrimitiveScalarType::from_i32(*deepest_type)
.ok_or_else(|| {
proto_error("Could not convert to datafusion scalar type")
})?
.into(),
true,
)));
//Iterates over field names in reverse order except for the last item in the vector
for name in field_names.iter().rev().skip(1) {
let temp_curr_type =
DataType::List(Box::new(Field::new(name, curr_type, true)));
curr_type = temp_curr_type;
}
Ok(curr_type)
}
}
impl TryInto<datafusion::scalar::ScalarValue> for protobuf::PrimitiveScalarType {
type Error = BallistaError;
fn try_into(self) -> Result<datafusion::scalar::ScalarValue, Self::Error> {
use datafusion::scalar::ScalarValue;
Ok(match self {
protobuf::PrimitiveScalarType::Null => {
return Err(proto_error("Untyped null is an invalid scalar value"))
}
protobuf::PrimitiveScalarType::Bool => ScalarValue::Boolean(None),
protobuf::PrimitiveScalarType::Uint8 => ScalarValue::UInt8(None),
protobuf::PrimitiveScalarType::Int8 => ScalarValue::Int8(None),
protobuf::PrimitiveScalarType::Uint16 => ScalarValue::UInt16(None),
protobuf::PrimitiveScalarType::Int16 => ScalarValue::Int16(None),
protobuf::PrimitiveScalarType::Uint32 => ScalarValue::UInt32(None),
protobuf::PrimitiveScalarType::Int32 => ScalarValue::Int32(None),
protobuf::PrimitiveScalarType::Uint64 => ScalarValue::UInt64(None),
protobuf::PrimitiveScalarType::Int64 => ScalarValue::Int64(None),
protobuf::PrimitiveScalarType::Float32 => ScalarValue::Float32(None),
protobuf::PrimitiveScalarType::Float64 => ScalarValue::Float64(None),
protobuf::PrimitiveScalarType::Utf8 => ScalarValue::Utf8(None),
protobuf::PrimitiveScalarType::LargeUtf8 => ScalarValue::LargeUtf8(None),
protobuf::PrimitiveScalarType::Date32 => ScalarValue::Date32(None),
protobuf::PrimitiveScalarType::TimeMicrosecond => {
ScalarValue::TimestampMicrosecond(None, None)
}
protobuf::PrimitiveScalarType::TimeNanosecond => {
ScalarValue::TimestampNanosecond(None, None)
}
protobuf::PrimitiveScalarType::Decimal128 => {
ScalarValue::Decimal128(None, 0, 0)
}
protobuf::PrimitiveScalarType::Date64 => ScalarValue::Date64(None),
protobuf::PrimitiveScalarType::TimeSecond => {
ScalarValue::TimestampSecond(None, None)
}
protobuf::PrimitiveScalarType::TimeMillisecond => {
ScalarValue::TimestampMillisecond(None, None)
}
protobuf::PrimitiveScalarType::IntervalYearmonth => {
ScalarValue::IntervalYearMonth(None)
}
protobuf::PrimitiveScalarType::IntervalDaytime => {
ScalarValue::IntervalDayTime(None)
}
})
}
}
impl TryInto<datafusion::scalar::ScalarValue> for &protobuf::ScalarValue {
type Error = BallistaError;
fn try_into(self) -> Result<datafusion::scalar::ScalarValue, Self::Error> {
let value = self.value.as_ref().ok_or_else(|| {
proto_error("Protobuf deserialization error: missing required field 'value'")
})?;
Ok(match value {
protobuf::scalar_value::Value::BoolValue(v) => ScalarValue::Boolean(Some(*v)),
protobuf::scalar_value::Value::Utf8Value(v) => {
ScalarValue::Utf8(Some(v.to_owned()))
}
protobuf::scalar_value::Value::LargeUtf8Value(v) => {
ScalarValue::LargeUtf8(Some(v.to_owned()))
}
protobuf::scalar_value::Value::Int8Value(v) => {
ScalarValue::Int8(Some(*v as i8))
}
protobuf::scalar_value::Value::Int16Value(v) => {
ScalarValue::Int16(Some(*v as i16))
}
protobuf::scalar_value::Value::Int32Value(v) => ScalarValue::Int32(Some(*v)),
protobuf::scalar_value::Value::Int64Value(v) => ScalarValue::Int64(Some(*v)),
protobuf::scalar_value::Value::Uint8Value(v) => {
ScalarValue::UInt8(Some(*v as u8))
}
protobuf::scalar_value::Value::Uint16Value(v) => {
ScalarValue::UInt16(Some(*v as u16))
}
protobuf::scalar_value::Value::Uint32Value(v) => {
ScalarValue::UInt32(Some(*v))
}
protobuf::scalar_value::Value::Uint64Value(v) => {
ScalarValue::UInt64(Some(*v))
}
protobuf::scalar_value::Value::Float32Value(v) => {
ScalarValue::Float32(Some(*v))
}
protobuf::scalar_value::Value::Float64Value(v) => {
ScalarValue::Float64(Some(*v))
}
protobuf::scalar_value::Value::Date32Value(v) => {
ScalarValue::Date32(Some(*v))
}
protobuf::scalar_value::Value::TimeMicrosecondValue(v) => {
ScalarValue::TimestampMicrosecond(Some(*v), None)
}
protobuf::scalar_value::Value::TimeNanosecondValue(v) => {
ScalarValue::TimestampNanosecond(Some(*v), None)
}
protobuf::scalar_value::Value::ListValue(scalar_list) => {
let protobuf::ScalarListValue {
values,
datatype: opt_scalar_type,
} = &scalar_list;
let pb_scalar_type = opt_scalar_type
.as_ref()
.ok_or_else(|| proto_error("Protobuf deserialization err: ScalaListValue missing required field 'datatype'"))?;
let typechecked_values: Vec<ScalarValue> = values
.iter()
.map(|val| val.try_into())
.collect::<Result<Vec<_>, _>>()?;
let scalar_type: DataType = pb_scalar_type.try_into()?;
let scalar_type = Box::new(scalar_type);
ScalarValue::List(Some(Box::new(typechecked_values)), scalar_type)
}
protobuf::scalar_value::Value::NullListValue(v) => {
let pb_datatype = v
.datatype
.as_ref()
.ok_or_else(|| proto_error("Protobuf deserialization error: NullListValue message missing required field 'datatyp'"))?;
let pb_datatype = Box::new(pb_datatype.try_into()?);
ScalarValue::List(None, pb_datatype)
}
protobuf::scalar_value::Value::NullValue(v) => {
let null_type_enum = protobuf::PrimitiveScalarType::from_i32(*v)
.ok_or_else(|| proto_error("Protobuf deserialization error found invalid enum variant for DatafusionScalar"))?;
null_type_enum.try_into()?
}
protobuf::scalar_value::Value::Decimal128Value(val) => {
let array = vec_to_array(val.value.clone());
ScalarValue::Decimal128(
Some(i128::from_be_bytes(array)),
val.p as usize,
val.s as usize,
)
}
protobuf::scalar_value::Value::Date64Value(v) => {
ScalarValue::Date64(Some(*v))
}
protobuf::scalar_value::Value::TimeSecondValue(v) => {
ScalarValue::TimestampSecond(Some(*v), None)
}
protobuf::scalar_value::Value::TimeMillisecondValue(v) => {
ScalarValue::TimestampMillisecond(Some(*v), None)
}
protobuf::scalar_value::Value::IntervalYearmonthValue(v) => {
ScalarValue::IntervalYearMonth(Some(*v))
}
protobuf::scalar_value::Value::IntervalDaytimeValue(v) => {
ScalarValue::IntervalDayTime(Some(*v))
}
})
}
}
impl TryInto<Expr> for &protobuf::LogicalExprNode {
type Error = BallistaError;
fn try_into(self) -> Result<Expr, Self::Error> {
use datafusion::physical_plan::window_functions;
use protobuf::logical_expr_node::ExprType;
use protobuf::window_expr_node;
use protobuf::WindowExprNode;
let expr_type = self
.expr_type
.as_ref()
.ok_or_else(|| proto_error("Unexpected empty logical expression"))?;
match expr_type {
ExprType::BinaryExpr(binary_expr) => Ok(Expr::BinaryExpr {
left: Box::new(parse_required_expr(&binary_expr.l)?),
op: from_proto_binary_op(&binary_expr.op)?,
right: Box::new(parse_required_expr(&binary_expr.r)?),
}),
ExprType::Column(column) => Ok(Expr::Column(column.into())),
ExprType::Literal(literal) => {
use datafusion::scalar::ScalarValue;
let scalar_value: datafusion::scalar::ScalarValue = literal.try_into()?;
Ok(Expr::Literal(scalar_value))
}
ExprType::WindowExpr(expr) => {
let window_function = expr
.window_function
.as_ref()
.ok_or_else(|| proto_error("Received empty window function"))?;
let partition_by = expr
.partition_by
.iter()
.map(|e| e.try_into())
.collect::<Result<Vec<_>, _>>()?;
let order_by = expr
.order_by
.iter()
.map(|e| e.try_into())
.collect::<Result<Vec<_>, _>>()?;
let window_frame = expr
.window_frame
.as_ref()
.map::<Result<WindowFrame, _>, _>(|e| match e {
window_expr_node::WindowFrame::Frame(frame) => {
let window_frame: WindowFrame = frame.clone().try_into()?;
if WindowFrameUnits::Range == window_frame.units
&& order_by.len() != 1
{
Err(proto_error("With window frame of type RANGE, the order by expression must be of length 1"))
} else {
Ok(window_frame)
}
}
})
.transpose()?;
match window_function {
window_expr_node::WindowFunction::AggrFunction(i) => {
let aggr_function = protobuf::AggregateFunction::from_i32(*i)
.ok_or_else(|| {
proto_error(format!(
"Received an unknown aggregate window function: {}",
i
))
})?;
Ok(Expr::WindowFunction {
fun: window_functions::WindowFunction::AggregateFunction(
AggregateFunction::from(aggr_function),
),
args: vec![parse_required_expr(&expr.expr)?],
partition_by,
order_by,
window_frame,
})
}
window_expr_node::WindowFunction::BuiltInFunction(i) => {
let built_in_function =
protobuf::BuiltInWindowFunction::from_i32(*i).ok_or_else(
|| {
proto_error(format!(
"Received an unknown built-in window function: {}",
i
))
},
)?;
Ok(Expr::WindowFunction {
fun: window_functions::WindowFunction::BuiltInWindowFunction(
BuiltInWindowFunction::from(built_in_function),
),
args: vec![parse_required_expr(&expr.expr)?],
partition_by,
order_by,
window_frame,
})
}
}
}
ExprType::AggregateExpr(expr) => {
let aggr_function =
protobuf::AggregateFunction::from_i32(expr.aggr_function)
.ok_or_else(|| {
proto_error(format!(
"Received an unknown aggregate function: {}",
expr.aggr_function
))
})?;
let fun = AggregateFunction::from(aggr_function);
Ok(Expr::AggregateFunction {
fun,
args: vec![parse_required_expr(&expr.expr)?],
distinct: false, //TODO
})
}
ExprType::Alias(alias) => Ok(Expr::Alias(
Box::new(parse_required_expr(&alias.expr)?),
alias.alias.clone(),
)),
ExprType::IsNullExpr(is_null) => {
Ok(Expr::IsNull(Box::new(parse_required_expr(&is_null.expr)?)))
}
ExprType::IsNotNullExpr(is_not_null) => Ok(Expr::IsNotNull(Box::new(
parse_required_expr(&is_not_null.expr)?,
))),
ExprType::NotExpr(not) => {
Ok(Expr::Not(Box::new(parse_required_expr(¬.expr)?)))
}
ExprType::Between(between) => Ok(Expr::Between {
expr: Box::new(parse_required_expr(&between.expr)?),
negated: between.negated,
low: Box::new(parse_required_expr(&between.low)?),
high: Box::new(parse_required_expr(&between.high)?),
}),
ExprType::Case(case) => {
let when_then_expr = case
.when_then_expr
.iter()
.map(|e| {
Ok((
Box::new(match &e.when_expr {
Some(e) => e.try_into(),
None => Err(proto_error("Missing required expression")),
}?),
Box::new(match &e.then_expr {
Some(e) => e.try_into(),
None => Err(proto_error("Missing required expression")),
}?),
))
})
.collect::<Result<Vec<(Box<Expr>, Box<Expr>)>, BallistaError>>()?;
Ok(Expr::Case {
expr: parse_optional_expr(&case.expr)?.map(Box::new),
when_then_expr,
else_expr: parse_optional_expr(&case.else_expr)?.map(Box::new),
})
}
ExprType::Cast(cast) => {
let expr = Box::new(parse_required_expr(&cast.expr)?);
let arrow_type: &protobuf::ArrowType = cast
.arrow_type
.as_ref()
.ok_or_else(|| proto_error("Protobuf deserialization error: CastNode message missing required field 'arrow_type'"))?;
let data_type = arrow_type.try_into()?;
Ok(Expr::Cast { expr, data_type })
}
ExprType::TryCast(cast) => {
let expr = Box::new(parse_required_expr(&cast.expr)?);
let arrow_type: &protobuf::ArrowType = cast
.arrow_type
.as_ref()
.ok_or_else(|| proto_error("Protobuf deserialization error: CastNode message missing required field 'arrow_type'"))?;
let data_type = arrow_type.try_into()?;
Ok(Expr::TryCast { expr, data_type })
}
ExprType::Sort(sort) => Ok(Expr::Sort {
expr: Box::new(parse_required_expr(&sort.expr)?),
asc: sort.asc,
nulls_first: sort.nulls_first,
}),
ExprType::Negative(negative) => Ok(Expr::Negative(Box::new(
parse_required_expr(&negative.expr)?,
))),
ExprType::InList(in_list) => Ok(Expr::InList {
expr: Box::new(parse_required_expr(&in_list.expr)?),
list: in_list
.list
.iter()
.map(|expr| expr.try_into())
.collect::<Result<Vec<_>, _>>()?,
negated: in_list.negated,
}),
ExprType::Wildcard(_) => Ok(Expr::Wildcard),
ExprType::ScalarFunction(expr) => {
let scalar_function = protobuf::ScalarFunction::from_i32(expr.fun)
.ok_or_else(|| {
proto_error(format!(
"Received an unknown scalar function: {}",
expr.fun
))
})?;
let args = &expr.args;
match scalar_function {
protobuf::ScalarFunction::Sqrt => Ok(sqrt((&args[0]).try_into()?)),
protobuf::ScalarFunction::Sin => Ok(sin((&args[0]).try_into()?)),
protobuf::ScalarFunction::Cos => Ok(cos((&args[0]).try_into()?)),
protobuf::ScalarFunction::Tan => Ok(tan((&args[0]).try_into()?)),
// protobuf::ScalarFunction::Asin => Ok(asin(&args[0]).try_into()?)),
// protobuf::ScalarFunction::Acos => Ok(acos(&args[0]).try_into()?)),
protobuf::ScalarFunction::Atan => Ok(atan((&args[0]).try_into()?)),
protobuf::ScalarFunction::Exp => Ok(exp((&args[0]).try_into()?)),
protobuf::ScalarFunction::Log2 => Ok(log2((&args[0]).try_into()?)),
protobuf::ScalarFunction::Ln => Ok(ln((&args[0]).try_into()?)),
protobuf::ScalarFunction::Log10 => Ok(log10((&args[0]).try_into()?)),
protobuf::ScalarFunction::Floor => Ok(floor((&args[0]).try_into()?)),
protobuf::ScalarFunction::Ceil => Ok(ceil((&args[0]).try_into()?)),
protobuf::ScalarFunction::Round => Ok(round((&args[0]).try_into()?)),
protobuf::ScalarFunction::Trunc => Ok(trunc((&args[0]).try_into()?)),
protobuf::ScalarFunction::Abs => Ok(abs((&args[0]).try_into()?)),
protobuf::ScalarFunction::Signum => {
Ok(signum((&args[0]).try_into()?))
}
protobuf::ScalarFunction::Octetlength => {
Ok(length((&args[0]).try_into()?))
}
// // protobuf::ScalarFunction::Concat => Ok(concat((&args[0]).try_into()?)),
protobuf::ScalarFunction::Lower => Ok(lower((&args[0]).try_into()?)),
protobuf::ScalarFunction::Upper => Ok(upper((&args[0]).try_into()?)),
protobuf::ScalarFunction::Trim => Ok(trim((&args[0]).try_into()?)),
protobuf::ScalarFunction::Ltrim => Ok(ltrim((&args[0]).try_into()?)),
protobuf::ScalarFunction::Rtrim => Ok(rtrim((&args[0]).try_into()?)),
// protobuf::ScalarFunction::Totimestamp => Ok(to_timestamp((&args[0]).try_into()?)),
// protobuf::ScalarFunction::Array => Ok(array((&args[0]).try_into()?)),
// // protobuf::ScalarFunction::Nullif => Ok(nulli((&args[0]).try_into()?)),
protobuf::ScalarFunction::Datepart => {
Ok(date_part((&args[0]).try_into()?, (&args[1]).try_into()?))
}
protobuf::ScalarFunction::Datetrunc => {
Ok(date_trunc((&args[0]).try_into()?, (&args[1]).try_into()?))
}
// protobuf::ScalarFunction::Md5 => Ok(md5((&args[0]).try_into()?)),
protobuf::ScalarFunction::Sha224 => {
Ok(sha224((&args[0]).try_into()?))
}
protobuf::ScalarFunction::Sha256 => {
Ok(sha256((&args[0]).try_into()?))
}
protobuf::ScalarFunction::Sha384 => {
Ok(sha384((&args[0]).try_into()?))
}
protobuf::ScalarFunction::Sha512 => {
Ok(sha512((&args[0]).try_into()?))
}
protobuf::ScalarFunction::Digest => {
Ok(digest((&args[0]).try_into()?, (&args[1]).try_into()?))
}
_ => Err(proto_error(
"Protobuf deserialization error: Unsupported scalar function",
)),
}
}
}
}
}
impl TryInto<DataType> for &protobuf::ScalarType {
type Error = BallistaError;
fn try_into(self) -> Result<DataType, Self::Error> {
let pb_scalartype = self.datatype.as_ref().ok_or_else(|| {
proto_error("ScalarType message missing required field 'datatype'")
})?;
pb_scalartype.try_into()
}
}
impl TryInto<Schema> for &protobuf::Schema {
type Error = BallistaError;
fn try_into(self) -> Result<Schema, BallistaError> {
let fields = self
.columns
.iter()
.map(|c| {
let pb_arrow_type_res = c
.arrow_type
.as_ref()
.ok_or_else(|| proto_error("Protobuf deserialization error: Field message was missing required field 'arrow_type'"));
let pb_arrow_type: &protobuf::ArrowType = match pb_arrow_type_res {
Ok(res) => res,
Err(e) => return Err(e),
};
Ok(Field::new(&c.name, pb_arrow_type.try_into()?, c.nullable))
})
.collect::<Result<Vec<_>, _>>()?;
Ok(Schema::new(fields))
}
}
impl TryInto<Field> for &protobuf::Field {
type Error = BallistaError;
fn try_into(self) -> Result<Field, Self::Error> {
let pb_datatype = self.arrow_type.as_ref().ok_or_else(|| {
proto_error(
"Protobuf deserialization error: Field message missing required field 'arrow_type'",
)
})?;
Ok(Field::new(
self.name.as_str(),
pb_datatype.as_ref().try_into()?,
self.nullable,
))
}
}
use crate::serde::protobuf::ColumnStats;
use datafusion::physical_plan::{aggregates, windows};
use datafusion::prelude::{
array, date_part, date_trunc, length, lower, ltrim, md5, rtrim, sha224, sha256,
sha384, sha512, trim, upper,
};
use std::convert::TryFrom;
impl TryFrom<i32> for protobuf::FileType {
type Error = BallistaError;
fn try_from(value: i32) -> Result<Self, Self::Error> {
use protobuf::FileType;
match value {
_x if _x == FileType::NdJson as i32 => Ok(FileType::NdJson),
_x if _x == FileType::Parquet as i32 => Ok(FileType::Parquet),
_x if _x == FileType::Csv as i32 => Ok(FileType::Csv),
_x if _x == FileType::Avro as i32 => Ok(FileType::Avro),
invalid => Err(BallistaError::General(format!(
"Attempted to convert invalid i32 to protobuf::Filetype: {}",
invalid
))),
}
}
}
#[allow(clippy::from_over_into)]
impl Into<datafusion::sql::parser::FileType> for protobuf::FileType {
fn into(self) -> datafusion::sql::parser::FileType {
use datafusion::sql::parser::FileType;
match self {
protobuf::FileType::NdJson => FileType::NdJson,
protobuf::FileType::Parquet => FileType::Parquet,
protobuf::FileType::Csv => FileType::CSV,
protobuf::FileType::Avro => FileType::Avro,
}
}
}
fn parse_required_expr(
p: &Option<Box<protobuf::LogicalExprNode>>,
) -> Result<Expr, BallistaError> {
match p {
Some(expr) => expr.as_ref().try_into(),
None => Err(proto_error("Missing required expression")),
}
}
fn parse_optional_expr(
p: &Option<Box<protobuf::LogicalExprNode>>,
) -> Result<Option<Expr>, BallistaError> {
match p {
Some(expr) => expr.as_ref().try_into().map(Some),
None => Ok(None),
}
}
impl From<protobuf::WindowFrameUnits> for WindowFrameUnits {
fn from(units: protobuf::WindowFrameUnits) -> Self {
match units {
protobuf::WindowFrameUnits::Rows => WindowFrameUnits::Rows,
protobuf::WindowFrameUnits::Range => WindowFrameUnits::Range,
protobuf::WindowFrameUnits::Groups => WindowFrameUnits::Groups,
}
}
}
impl TryFrom<protobuf::WindowFrameBound> for WindowFrameBound {
type Error = BallistaError;
fn try_from(bound: protobuf::WindowFrameBound) -> Result<Self, Self::Error> {
let bound_type = protobuf::WindowFrameBoundType::from_i32(bound.window_frame_bound_type).ok_or_else(|| {
proto_error(format!(
"Received a WindowFrameBound message with unknown WindowFrameBoundType {}",
bound.window_frame_bound_type
))
})?;
match bound_type {
protobuf::WindowFrameBoundType::CurrentRow => {
Ok(WindowFrameBound::CurrentRow)
}
protobuf::WindowFrameBoundType::Preceding => {
// FIXME implement bound value parsing
// https://github.com/apache/arrow-datafusion/issues/361
Ok(WindowFrameBound::Preceding(Some(1)))
}
protobuf::WindowFrameBoundType::Following => {
// FIXME implement bound value parsing
// https://github.com/apache/arrow-datafusion/issues/361
Ok(WindowFrameBound::Following(Some(1)))
}
}
}
}
impl TryFrom<protobuf::WindowFrame> for WindowFrame {
type Error = BallistaError;
fn try_from(window: protobuf::WindowFrame) -> Result<Self, Self::Error> {
let units = protobuf::WindowFrameUnits::from_i32(window.window_frame_units)
.ok_or_else(|| {
proto_error(format!(
"Received a WindowFrame message with unknown WindowFrameUnits {}",
window.window_frame_units
))
})?
.into();
let start_bound = window
.start_bound
.ok_or_else(|| {
proto_error(
"Received a WindowFrame message with no start_bound".to_owned(),
)
})?
.try_into()?;
let end_bound = window
.end_bound
.map(|end_bound| match end_bound {
protobuf::window_frame::EndBound::Bound(end_bound) => {
end_bound.try_into()
}
})
.transpose()?
.unwrap_or(WindowFrameBound::CurrentRow);
Ok(WindowFrame {
units,
start_bound,
end_bound,
})
}
}
| 44.320741 | 144 | 0.503168 |
ef8e4e568e01cefbfe726db7b53f6db1c531b273 | 1,782 | #![cfg_attr(not(feature = "std"), no_std)]
pub use pallet::*;
#[frame_support::pallet]
pub mod pallet {
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::OriginFor;
use frame_support::inherent::Vec;
use frame_system::ensure_signed;
#[pallet::pallet]
pub struct Pallet<T>(_);
#[pallet::config]
pub trait Config: frame_system::Config + pallet_kitties::Config {
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
}
#[pallet::error]
pub enum Error<T> {}
#[pallet::event]
#[pallet::generate_deposit(pub (super) fn deposit_event)]
pub enum Event<T: Config> {
CountOfKitties(u32),
Kitties(Vec<(T::Hash, pallet_kitties::pallet::Kitty<T>)>),
KittiesByPrice(Vec<(T::Hash, pallet_kitties::pallet::Kitty<T>)>),
KittiesByOwner((T::AccountId, Vec<T::Hash>)),
}
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::weight(100)]
pub fn get_all_kitties(origin: OriginFor<T>) -> DispatchResult {
let _ = ensure_signed(origin)?;
let kitties_value = pallet_kitties::Pallet::<T>::get_all_kitties();
Self::deposit_event(Event::Kitties(kitties_value));
Ok(())
}
#[pallet::weight(100)]
pub fn get_all_kitties_by_owner(origin: OriginFor<T>, owner: T::AccountId) -> DispatchResult {
let _ = ensure_signed(origin)?;
let kitties_owned = pallet_kitties::Pallet::<T>::get_kitties_by_owner(&owner);
Self::deposit_event(Event::KittiesByOwner((owner, kitties_owned)));
Ok(())
}
#[pallet::weight(100)]
pub fn get_all_my_kitties(origin: OriginFor<T>) -> DispatchResult {
let sender = ensure_signed(origin)?;
let kitties_owned = pallet_kitties::Pallet::<T>::get_kitties_by_owner(&sender);
Self::deposit_event(Event::KittiesByOwner((sender, kitties_owned)));
Ok(())
}
}
}
| 28.741935 | 96 | 0.694725 |
75cfb8775400e312e3228f4d3e1206fcf3cf4272 | 20,136 | // Copyright 2018 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate grin_apiwallet as apiwallet;
extern crate grin_libwallet as libwallet;
extern crate grin_refwallet as wallet;
extern crate grin_wallet_config as wallet_config;
use self::keychain::Keychain;
use self::util::Mutex;
use self::wallet::{HTTPNodeClient, HTTPWalletCommAdapter, LMDBBackend};
use self::wallet_config::WalletConfig;
use blake2_rfc as blake2;
use grin_api as api;
use grin_core as core;
use grin_keychain as keychain;
use grin_p2p as p2p;
use grin_servers as servers;
use grin_util as util;
use p2p::PeerAddr;
use std::default::Default;
use std::ops::Deref;
use std::sync::Arc;
use std::{fs, thread, time};
/// Just removes all results from previous runs
pub fn clean_all_output(test_name_dir: &str) {
let target_dir = format!("target/tmp/{}", test_name_dir);
if let Err(e) = fs::remove_dir_all(target_dir) {
println!("can't remove output from previous test :{}, may be ok", e);
}
}
/// Errors that can be returned by LocalServerContainer
#[derive(Debug)]
#[allow(dead_code)]
pub enum Error {
Internal(String),
Argument(String),
NotFound,
}
/// All-in-one server configuration struct, for convenience
///
#[derive(Clone)]
pub struct LocalServerContainerConfig {
// user friendly name for the server, also denotes what dir
// the data files will appear in
pub name: String,
// Base IP address
pub base_addr: String,
// Port the server (p2p) is running on
pub p2p_server_port: u16,
// Port the API server is running on
pub api_server_port: u16,
// Port the wallet server is running on
pub wallet_port: u16,
// Port the wallet owner API is running on
pub owner_port: u16,
// Whether to include the foreign API endpoints in the owner API
pub owner_api_include_foreign: bool,
// Whether we're going to mine
pub start_miner: bool,
// time in millis by which to artificially slow down the mining loop
// in this container
pub miner_slowdown_in_millis: u64,
// Whether we're going to run a wallet as well,
// can use same server instance as a validating node for convenience
pub start_wallet: bool,
// address of a server to use as a seed
pub seed_addr: String,
// keep track of whether this server is supposed to be seeding
pub is_seeding: bool,
// Whether to burn mining rewards
pub burn_mining_rewards: bool,
// full address to send coinbase rewards to
pub coinbase_wallet_address: String,
// When running a wallet, the address to check inputs and send
// finalised transactions to,
pub wallet_validating_node_url: String,
}
/// Default server config
impl Default for LocalServerContainerConfig {
fn default() -> LocalServerContainerConfig {
LocalServerContainerConfig {
name: String::from("test_host"),
base_addr: String::from("127.0.0.1"),
api_server_port: 13413,
p2p_server_port: 13414,
wallet_port: 13415,
owner_port: 13420,
owner_api_include_foreign: false,
seed_addr: String::from(""),
is_seeding: false,
start_miner: false,
start_wallet: false,
burn_mining_rewards: false,
coinbase_wallet_address: String::from(""),
wallet_validating_node_url: String::from(""),
miner_slowdown_in_millis: 0,
}
}
}
/// A top-level container to hold everything that might be running
/// on a server, i.e. server, wallet in send or receive mode
#[allow(dead_code)]
pub struct LocalServerContainer {
// Configuration
config: LocalServerContainerConfig,
// Structure of references to the
// internal server data
pub p2p_server_stats: Option<servers::ServerStats>,
// The API server instance
api_server: Option<api::ApiServer>,
// whether the server is running
pub server_is_running: bool,
// Whether the server is mining
pub server_is_mining: bool,
// Whether the server is also running a wallet
// Not used if running wallet without server
pub wallet_is_running: bool,
// the list of peers to connect to
pub peer_list: Vec<String>,
// base directory for the server instance
pub working_dir: String,
// Wallet configuration
pub wallet_config: WalletConfig,
}
impl LocalServerContainer {
/// Create a new local server container with defaults, with the given name
/// all related files will be created in the directory
/// target/tmp/{name}
pub fn new(config: LocalServerContainerConfig) -> Result<LocalServerContainer, Error> {
let working_dir = format!("target/tmp/{}", config.name);
let mut wallet_config = WalletConfig::default();
wallet_config.api_listen_port = config.wallet_port;
wallet_config.check_node_api_http_addr = config.wallet_validating_node_url.clone();
wallet_config.owner_api_include_foreign = Some(config.owner_api_include_foreign);
wallet_config.data_file_dir = working_dir.clone();
Ok(LocalServerContainer {
config: config,
p2p_server_stats: None,
api_server: None,
server_is_running: false,
server_is_mining: false,
wallet_is_running: false,
working_dir: working_dir,
peer_list: Vec::new(),
wallet_config: wallet_config,
})
}
pub fn run_server(&mut self, duration_in_seconds: u64) -> servers::Server {
let api_addr = format!("{}:{}", self.config.base_addr, self.config.api_server_port);
let mut seeding_type = p2p::Seeding::None;
let mut seeds = Vec::new();
if self.config.seed_addr.len() > 0 {
seeding_type = p2p::Seeding::List;
seeds = vec![PeerAddr::from_ip(
self.config.seed_addr.to_string().parse().unwrap(),
)];
}
let s = servers::Server::new(servers::ServerConfig {
api_http_addr: api_addr,
api_secret_path: None,
db_root: format!("{}/.mwc", self.working_dir),
p2p_config: p2p::P2PConfig {
port: self.config.p2p_server_port,
seeds: Some(seeds),
seeding_type: seeding_type,
..p2p::P2PConfig::default()
},
chain_type: core::global::ChainTypes::AutomatedTesting,
skip_sync_wait: Some(true),
stratum_mining_config: None,
..Default::default()
})
.unwrap();
self.p2p_server_stats = Some(s.get_server_stats().unwrap());
let mut wallet_url = None;
if self.config.start_wallet == true {
self.run_wallet(duration_in_seconds + 5);
// give a second to start wallet before continuing
thread::sleep(time::Duration::from_millis(1000));
wallet_url = Some(format!(
"http://{}:{}",
self.config.base_addr, self.config.wallet_port
));
}
if self.config.start_miner == true {
println!(
"starting test Miner on port {}",
self.config.p2p_server_port
);
s.start_test_miner(wallet_url, s.stop_state.clone());
}
for p in &mut self.peer_list {
println!("{} connecting to peer: {}", self.config.p2p_server_port, p);
let _ = s.connect_peer(PeerAddr::from_ip(p.parse().unwrap()));
}
if self.wallet_is_running {
self.stop_wallet();
}
s
}
/// Make a wallet for use in test endpoints (run_wallet and run_owner).
fn make_wallet_for_tests(
&mut self,
) -> Arc<Mutex<LMDBBackend<HTTPNodeClient, keychain::ExtKeychain>>> {
// URL on which to start the wallet listener (i.e. api server)
let _url = format!("{}:{}", self.config.base_addr, self.config.wallet_port);
// Just use the name of the server for a seed for now
let seed = format!("{}", self.config.name);
let _seed = blake2::blake2b::blake2b(32, &[], seed.as_bytes());
println!(
"Starting the MWC wallet receiving daemon on {} ",
self.config.wallet_port
);
self.wallet_config = WalletConfig::default();
self.wallet_config.api_listen_port = self.config.wallet_port;
self.wallet_config.check_node_api_http_addr =
self.config.wallet_validating_node_url.clone();
self.wallet_config.data_file_dir = self.working_dir.clone();
self.wallet_config.owner_api_include_foreign = Some(self.config.owner_api_include_foreign);
let _ = fs::create_dir_all(self.wallet_config.clone().data_file_dir);
let r = wallet::WalletSeed::init_file(&self.wallet_config, 32, None, "", false);
let client_n = HTTPNodeClient::new(&self.wallet_config.check_node_api_http_addr, None);
if let Err(_e) = r {
//panic!("Error initializing wallet seed: {}", e);
}
let wallet: LMDBBackend<HTTPNodeClient, keychain::ExtKeychain> =
LMDBBackend::new(self.wallet_config.clone(), "", client_n).unwrap_or_else(|e| {
panic!(
"Error creating wallet: {:?} Config: {:?}",
e, self.wallet_config
)
});
Arc::new(Mutex::new(wallet))
}
/// Starts a wallet daemon to receive
pub fn run_wallet(&mut self, _duration_in_mills: u64) {
let wallet = self.make_wallet_for_tests();
wallet::controller::foreign_listener(wallet, &self.wallet_config.api_listen_addr(), None)
.unwrap_or_else(|e| {
panic!(
"Error creating wallet listener: {:?} Config: {:?}",
e, self.wallet_config
)
});
self.wallet_is_running = true;
}
/// Starts a wallet owner daemon
#[allow(dead_code)]
pub fn run_owner(&mut self) {
let wallet = self.make_wallet_for_tests();
// WalletConfig doesn't allow changing the owner API path, so we build
// the path ourselves
let owner_listen_addr = format!("127.0.0.1:{}", self.config.owner_port);
wallet::controller::owner_listener(
wallet,
&owner_listen_addr,
None,
None,
self.wallet_config.owner_api_include_foreign.clone(),
)
.unwrap_or_else(|e| {
panic!(
"Error creating wallet owner listener: {:?} Config: {:?}",
e, self.wallet_config
)
});
}
#[allow(dead_code)]
pub fn get_wallet_seed(config: &WalletConfig) -> wallet::WalletSeed {
let _ = fs::create_dir_all(config.clone().data_file_dir);
wallet::WalletSeed::init_file(config, 32, None, "", false).unwrap();
let wallet_seed =
wallet::WalletSeed::from_file(config, "").expect("Failed to read wallet seed file.");
wallet_seed
}
#[allow(dead_code)]
pub fn get_wallet_info(
config: &WalletConfig,
wallet_seed: &wallet::WalletSeed,
) -> wallet::WalletInfo {
let keychain: keychain::ExtKeychain = wallet_seed
.derive_keychain(false)
.expect("Failed to derive keychain from seed file and passphrase.");
let client_n = HTTPNodeClient::new(&config.check_node_api_http_addr, None);
let mut wallet = LMDBBackend::new(config.clone(), "", client_n)
.unwrap_or_else(|e| panic!("Error creating wallet: {:?} Config: {:?}", e, config));
wallet.keychain = Some(keychain);
let parent_id = keychain::ExtKeychain::derive_key_id(2, 0, 0, 0, 0);
let _ = libwallet::internal::updater::refresh_outputs(&mut wallet, &parent_id, false);
libwallet::internal::updater::retrieve_info(&mut wallet, &parent_id, 1).unwrap()
}
#[allow(dead_code)]
pub fn send_amount_to(
config: &WalletConfig,
amount: &str,
minimum_confirmations: u64,
selection_strategy: &str,
dest: &str,
_fluff: bool,
) {
let amount = core::core::amount_from_hr_string(amount)
.expect("Could not parse amount as a number with optional decimal point.");
let wallet_seed =
wallet::WalletSeed::from_file(config, "").expect("Failed to read wallet seed file.");
let keychain: keychain::ExtKeychain = wallet_seed
.derive_keychain(false)
.expect("Failed to derive keychain from seed file and passphrase.");
let client_n = HTTPNodeClient::new(&config.check_node_api_http_addr, None);
let client_w = HTTPWalletCommAdapter::new();
let max_outputs = 500;
let change_outputs = 1;
let mut wallet = LMDBBackend::new(config.clone(), "", client_n)
.unwrap_or_else(|e| panic!("Error creating wallet: {:?} Config: {:?}", e, config));
wallet.keychain = Some(keychain);
let _ = wallet::controller::owner_single_use(Arc::new(Mutex::new(wallet)), |api| {
let (mut slate, lock_fn) = api.initiate_tx(
None,
amount,
minimum_confirmations,
max_outputs,
change_outputs,
selection_strategy == "all",
None,
)?;
slate = client_w.send_tx_sync(dest, &slate)?;
slate = api.finalize_tx(&slate)?;
api.tx_lock_outputs(&slate, lock_fn)?;
println!(
"Tx sent: {} mwc to {} (strategy '{}')",
core::core::amount_to_hr_string(amount, false),
dest,
selection_strategy,
);
Ok(())
})
.unwrap_or_else(|e| panic!("Error creating wallet: {:?} Config: {:?}", e, config));
}
/// Stops the running wallet server
pub fn stop_wallet(&mut self) {
println!("Stop wallet!");
let api_server = self.api_server.as_mut().unwrap();
api_server.stop();
}
/// Adds a peer to this server to connect to upon running
#[allow(dead_code)]
pub fn add_peer(&mut self, addr: String) {
self.peer_list.push(addr);
}
}
/// Configuration values for container pool
pub struct LocalServerContainerPoolConfig {
// Base name to append to all the servers in this pool
pub base_name: String,
// Base http address for all of the servers in this pool
pub base_http_addr: String,
// Base port server for all of the servers in this pool
// Increment the number by 1 for each new server
pub base_p2p_port: u16,
// Base api port for all of the servers in this pool
// Increment this number by 1 for each new server
pub base_api_port: u16,
// Base wallet port for this server
//
pub base_wallet_port: u16,
// Base wallet owner port for this server
//
pub base_owner_port: u16,
// How long the servers in the pool are going to run
pub run_length_in_seconds: u64,
}
/// Default server config
///
impl Default for LocalServerContainerPoolConfig {
fn default() -> LocalServerContainerPoolConfig {
LocalServerContainerPoolConfig {
base_name: String::from("test_pool"),
base_http_addr: String::from("127.0.0.1"),
base_p2p_port: 10000,
base_api_port: 11000,
base_wallet_port: 12000,
base_owner_port: 13000,
run_length_in_seconds: 30,
}
}
}
/// A convenience pool for running many servers simultaneously
/// without necessarily having to configure each one manually
#[allow(dead_code)]
pub struct LocalServerContainerPool {
// configuration
pub config: LocalServerContainerPoolConfig,
// keep ahold of all the created servers thread-safely
server_containers: Vec<LocalServerContainer>,
// Keep track of what the last ports a server was opened on
next_p2p_port: u16,
next_api_port: u16,
next_wallet_port: u16,
next_owner_port: u16,
// keep track of whether a seed exists, and pause a bit if so
is_seeding: bool,
}
#[allow(dead_code)]
impl LocalServerContainerPool {
pub fn new(config: LocalServerContainerPoolConfig) -> LocalServerContainerPool {
(LocalServerContainerPool {
next_api_port: config.base_api_port,
next_p2p_port: config.base_p2p_port,
next_wallet_port: config.base_wallet_port,
next_owner_port: config.base_owner_port,
config: config,
server_containers: Vec::new(),
is_seeding: false,
})
}
/// adds a single server on the next available port
/// overriding passed-in values as necessary. Config object is an OUT value
/// with
/// ports/addresses filled in
///
#[allow(dead_code)]
pub fn create_server(&mut self, server_config: &mut LocalServerContainerConfig) {
// If we're calling it this way, need to override these
server_config.p2p_server_port = self.next_p2p_port;
server_config.api_server_port = self.next_api_port;
server_config.wallet_port = self.next_wallet_port;
server_config.owner_port = self.next_owner_port;
server_config.name = String::from(format!(
"{}/{}-{}",
self.config.base_name, self.config.base_name, server_config.p2p_server_port
));
// Use self as coinbase wallet
server_config.coinbase_wallet_address = String::from(format!(
"http://{}:{}",
server_config.base_addr, server_config.wallet_port
));
self.next_p2p_port += 1;
self.next_api_port += 1;
self.next_wallet_port += 1;
self.next_owner_port += 1;
if server_config.is_seeding {
self.is_seeding = true;
}
let _server_address = format!(
"{}:{}",
server_config.base_addr, server_config.p2p_server_port
);
let server_container = LocalServerContainer::new(server_config.clone()).unwrap();
// self.server_containers.push(server_arc);
// Create a future that runs the server for however many seconds
// collect them all and run them in the run_all_servers
let _run_time = self.config.run_length_in_seconds;
self.server_containers.push(server_container);
}
/// adds n servers, ready to run
///
///
#[allow(dead_code)]
pub fn create_servers(&mut self, number: u16) {
for _ in 0..number {
// self.create_server();
}
}
/// runs all servers, and returns a vector of references to the servers
/// once they've all been run
///
#[allow(dead_code)]
pub fn run_all_servers(self) -> Arc<Mutex<Vec<servers::Server>>> {
let run_length = self.config.run_length_in_seconds;
let mut handles = vec![];
// return handles to all of the servers, wrapped in mutexes, handles, etc
let return_containers = Arc::new(Mutex::new(Vec::new()));
let is_seeding = self.is_seeding.clone();
for mut s in self.server_containers {
let return_container_ref = return_containers.clone();
let handle = thread::spawn(move || {
if is_seeding && !s.config.is_seeding {
// there's a seed and we're not it, so hang around longer and give the seed
// a chance to start
thread::sleep(time::Duration::from_millis(2000));
}
let server_ref = s.run_server(run_length);
return_container_ref.lock().push(server_ref);
});
// Not a big fan of sleeping hack here, but there appears to be a
// concurrency issue when creating files in rocksdb that causes
// failure if we don't pause a bit before starting the next server
thread::sleep(time::Duration::from_millis(500));
handles.push(handle);
}
for handle in handles {
match handle.join() {
Ok(_) => {}
Err(e) => {
println!("Error starting server thread: {:?}", e);
panic!(e);
}
}
}
// return a much simplified version of the results
return_containers.clone()
}
#[allow(dead_code)]
pub fn connect_all_peers(&mut self) {
// just pull out all currently active servers, build a list,
// and feed into all servers
let mut server_addresses: Vec<String> = Vec::new();
for s in &self.server_containers {
let server_address = format!("{}:{}", s.config.base_addr, s.config.p2p_server_port);
server_addresses.push(server_address);
}
for a in server_addresses {
for s in &mut self.server_containers {
if format!("{}:{}", s.config.base_addr, s.config.p2p_server_port) != a {
s.add_peer(a.clone());
}
}
}
}
}
#[allow(dead_code)]
pub fn stop_all_servers(servers: Arc<Mutex<Vec<servers::Server>>>) {
let locked_servs = servers.lock();
for s in locked_servs.deref() {
s.stop();
}
}
/// Create and return a ServerConfig
#[allow(dead_code)]
pub fn config(n: u16, test_name_dir: &str, seed_n: u16) -> servers::ServerConfig {
servers::ServerConfig {
api_http_addr: format!("127.0.0.1:{}", 20000 + n),
api_secret_path: None,
db_root: format!("target/tmp/{}/mwc-sync-{}", test_name_dir, n),
p2p_config: p2p::P2PConfig {
port: 10000 + n,
seeding_type: p2p::Seeding::List,
seeds: Some(vec![PeerAddr::from_ip(
format!("127.0.0.1:{}", 10000 + seed_n).parse().unwrap(),
)]),
..p2p::P2PConfig::default()
},
chain_type: core::global::ChainTypes::AutomatedTesting,
archive_mode: Some(true),
skip_sync_wait: Some(true),
..Default::default()
}
}
/// return stratum mining config
#[allow(dead_code)]
pub fn stratum_config() -> servers::common::types::StratumServerConfig {
servers::common::types::StratumServerConfig {
enable_stratum_server: Some(true),
stratum_server_addr: Some(String::from("127.0.0.1:13416")),
attempt_time_per_block: 60,
minimum_share_difficulty: 1,
wallet_listener_url: String::from("http://127.0.0.1:13415"),
burn_reward: false,
}
}
| 29.481698 | 93 | 0.710866 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.